record.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "encoding/binary"
  16. "io"
  17. )
  18. func writeRecord(w io.Writer, rec *Record) error {
  19. data, err := rec.Marshal()
  20. if err != nil {
  21. return err
  22. }
  23. if err := writeInt64(w, int64(len(data))); err != nil {
  24. return err
  25. }
  26. _, err = w.Write(data)
  27. return err
  28. }
  29. func readRecord(r io.Reader, rec *Record) error {
  30. rec.Reset()
  31. l, err := readInt64(r)
  32. if err != nil {
  33. return err
  34. }
  35. d := make([]byte, l)
  36. if _, err = io.ReadFull(r, d); err != nil {
  37. return err
  38. }
  39. return rec.Unmarshal(d)
  40. }
  41. func writeInt64(w io.Writer, n int64) error {
  42. return binary.Write(w, binary.LittleEndian, n)
  43. }
  44. func readInt64(r io.Reader) (int64, error) {
  45. var n int64
  46. err := binary.Read(r, binary.LittleEndian, &n)
  47. return n, err
  48. }