entry_writer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 rafthttp
  15. import (
  16. "encoding/binary"
  17. "io"
  18. "github.com/coreos/etcd/pkg/types"
  19. "github.com/coreos/etcd/raft/raftpb"
  20. )
  21. type entryWriter struct {
  22. w io.Writer
  23. id types.ID
  24. }
  25. func newEntryWriter(w io.Writer, id types.ID) *entryWriter {
  26. ew := &entryWriter{
  27. w: w,
  28. id: id,
  29. }
  30. return ew
  31. }
  32. func (ew *entryWriter) writeEntries(ents []raftpb.Entry) error {
  33. l := len(ents)
  34. if l == 0 {
  35. return nil
  36. }
  37. if err := binary.Write(ew.w, binary.BigEndian, uint64(l)); err != nil {
  38. return err
  39. }
  40. for i := 0; i < l; i++ {
  41. if err := ew.writeEntry(&ents[i]); err != nil {
  42. return err
  43. }
  44. }
  45. return nil
  46. }
  47. func (ew *entryWriter) writeEntry(ent *raftpb.Entry) error {
  48. size := ent.Size()
  49. if err := binary.Write(ew.w, binary.BigEndian, uint64(size)); err != nil {
  50. return err
  51. }
  52. b, err := ent.Marshal()
  53. if err != nil {
  54. return err
  55. }
  56. _, err = ew.w.Write(b)
  57. return err
  58. }