encoder.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package wal
  14. import (
  15. "bufio"
  16. "encoding/binary"
  17. "hash"
  18. "io"
  19. "github.com/coreos/etcd/pkg/crc"
  20. "github.com/coreos/etcd/wal/walpb"
  21. )
  22. type encoder struct {
  23. bw *bufio.Writer
  24. crc hash.Hash32
  25. }
  26. func newEncoder(w io.Writer, prevCrc uint32) *encoder {
  27. return &encoder{
  28. bw: bufio.NewWriter(w),
  29. crc: crc.New(prevCrc, crcTable),
  30. }
  31. }
  32. func (e *encoder) encode(rec *walpb.Record) error {
  33. e.crc.Write(rec.Data)
  34. rec.Crc = e.crc.Sum32()
  35. data, err := rec.Marshal()
  36. if err != nil {
  37. return err
  38. }
  39. if err := writeInt64(e.bw, int64(len(data))); err != nil {
  40. return err
  41. }
  42. _, err = e.bw.Write(data)
  43. return err
  44. }
  45. func (e *encoder) flush() error {
  46. return e.bw.Flush()
  47. }
  48. func (e *encoder) buffered() int {
  49. return e.bw.Buffered()
  50. }
  51. func writeInt64(w io.Writer, n int64) error {
  52. return binary.Write(w, binary.LittleEndian, n)
  53. }