encoder.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. }
  30. func newEncoder(w io.Writer, prevCrc uint32) *encoder {
  31. return &encoder{
  32. bw: bufio.NewWriter(w),
  33. crc: crc.New(prevCrc, crcTable),
  34. // 1MB buffer
  35. buf: make([]byte, 1024*1024),
  36. }
  37. }
  38. func (e *encoder) encode(rec *walpb.Record) error {
  39. e.mu.Lock()
  40. defer e.mu.Unlock()
  41. e.crc.Write(rec.Data)
  42. rec.Crc = e.crc.Sum32()
  43. var (
  44. data []byte
  45. err error
  46. n int
  47. )
  48. if rec.Size() > len(e.buf) {
  49. data, err = rec.Marshal()
  50. if err != nil {
  51. return err
  52. }
  53. } else {
  54. n, err = rec.MarshalTo(e.buf)
  55. if err != nil {
  56. return err
  57. }
  58. data = e.buf[:n]
  59. }
  60. if err := writeInt64(e.bw, int64(len(data))); err != nil {
  61. return err
  62. }
  63. _, err = e.bw.Write(data)
  64. return err
  65. }
  66. func (e *encoder) flush() error {
  67. e.mu.Lock()
  68. defer e.mu.Unlock()
  69. return e.bw.Flush()
  70. }
  71. func writeInt64(w io.Writer, n int64) error {
  72. // TODO: use putuint64 to reduce two alloctions
  73. return binary.Write(w, binary.LittleEndian, n)
  74. }