encoder.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package wal
  15. import (
  16. "bufio"
  17. "encoding/binary"
  18. "hash"
  19. "io"
  20. "sync"
  21. "github.com/coreos/etcd/pkg/crc"
  22. "github.com/coreos/etcd/wal/walpb"
  23. )
  24. type encoder struct {
  25. mu sync.Mutex
  26. bw *bufio.Writer
  27. crc hash.Hash32
  28. buf []byte
  29. uint64buf []byte
  30. }
  31. func newEncoder(w io.Writer, prevCrc uint32) *encoder {
  32. return &encoder{
  33. bw: bufio.NewWriter(w),
  34. crc: crc.New(prevCrc, crcTable),
  35. // 1MB buffer
  36. buf: make([]byte, 1024*1024),
  37. uint64buf: make([]byte, 8),
  38. }
  39. }
  40. func (e *encoder) encode(rec *walpb.Record) error {
  41. e.mu.Lock()
  42. defer e.mu.Unlock()
  43. e.crc.Write(rec.Data)
  44. rec.Crc = e.crc.Sum32()
  45. var (
  46. data []byte
  47. err error
  48. n int
  49. )
  50. if rec.Size() > len(e.buf) {
  51. data, err = rec.Marshal()
  52. if err != nil {
  53. return err
  54. }
  55. } else {
  56. n, err = rec.MarshalTo(e.buf)
  57. if err != nil {
  58. return err
  59. }
  60. data = e.buf[:n]
  61. }
  62. if err = writeInt64(e.bw, int64(len(data)), e.uint64buf); err != nil {
  63. return err
  64. }
  65. _, err = e.bw.Write(data)
  66. return err
  67. }
  68. func (e *encoder) flush() error {
  69. e.mu.Lock()
  70. defer e.mu.Unlock()
  71. return e.bw.Flush()
  72. }
  73. func writeInt64(w io.Writer, n int64, buf []byte) error {
  74. // http://golang.org/src/encoding/binary/binary.go
  75. binary.LittleEndian.PutUint64(buf, uint64(n))
  76. _, err := w.Write(buf)
  77. return err
  78. }