encoder.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright 2015 The etcd Authors
  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. lenField, padBytes := encodeFrameSize(len(data))
  63. if err = writeUint64(e.bw, lenField, e.uint64buf); err != nil {
  64. return err
  65. }
  66. if padBytes != 0 {
  67. data = append(data, make([]byte, padBytes)...)
  68. }
  69. _, err = e.bw.Write(data)
  70. return err
  71. }
  72. func encodeFrameSize(dataBytes int) (lenField uint64, padBytes int) {
  73. lenField = uint64(dataBytes)
  74. // force 8 byte alignment so length never gets a torn write
  75. padBytes = (8 - (dataBytes % 8)) % 8
  76. if padBytes != 0 {
  77. lenField |= uint64(0x80|padBytes) << 56
  78. }
  79. return
  80. }
  81. func (e *encoder) flush() error {
  82. e.mu.Lock()
  83. defer e.mu.Unlock()
  84. return e.bw.Flush()
  85. }
  86. func writeUint64(w io.Writer, n uint64, buf []byte) error {
  87. // http://golang.org/src/encoding/binary/binary.go
  88. binary.LittleEndian.PutUint64(buf, n)
  89. _, err := w.Write(buf)
  90. return err
  91. }