encoder.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. "github.com/coreos/etcd/pkg/crc"
  21. "github.com/coreos/etcd/wal/walpb"
  22. )
  23. type encoder struct {
  24. bw *bufio.Writer
  25. crc hash.Hash32
  26. }
  27. func newEncoder(w io.Writer, prevCrc uint32) *encoder {
  28. return &encoder{
  29. bw: bufio.NewWriter(w),
  30. crc: crc.New(prevCrc, crcTable),
  31. }
  32. }
  33. func (e *encoder) encode(rec *walpb.Record) error {
  34. e.crc.Write(rec.Data)
  35. rec.Crc = e.crc.Sum32()
  36. data, err := rec.Marshal()
  37. if err != nil {
  38. return err
  39. }
  40. if err := writeInt64(e.bw, int64(len(data))); err != nil {
  41. return err
  42. }
  43. _, err = e.bw.Write(data)
  44. return err
  45. }
  46. func (e *encoder) flush() error {
  47. return e.bw.Flush()
  48. }
  49. func writeInt64(w io.Writer, n int64) error {
  50. return binary.Write(w, binary.LittleEndian, n)
  51. }