block.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "fmt"
  16. "io"
  17. )
  18. type block struct {
  19. t int64
  20. d []byte
  21. }
  22. func writeBlock(w io.Writer, t int64, d []byte) error {
  23. if err := writeInt64(w, t); err != nil {
  24. return err
  25. }
  26. if err := writeInt64(w, int64(len(d))); err != nil {
  27. return err
  28. }
  29. _, err := w.Write(d)
  30. return err
  31. }
  32. func readBlock(r io.Reader, b *block) error {
  33. t, err := readInt64(r)
  34. if err != nil {
  35. return err
  36. }
  37. l, err := readInt64(r)
  38. if err != nil {
  39. return unexpectedEOF(err)
  40. }
  41. d := make([]byte, l)
  42. n, err := r.Read(d)
  43. if err != nil {
  44. return unexpectedEOF(err)
  45. }
  46. if n != int(l) {
  47. return fmt.Errorf("len(data) = %d, want %d", n, l)
  48. }
  49. b.t = t
  50. b.d = d
  51. return nil
  52. }
  53. func unexpectedEOF(err error) error {
  54. if err == io.EOF {
  55. return io.ErrUnexpectedEOF
  56. }
  57. return err
  58. }