iterator.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package y
  6. import (
  7. "bytes"
  8. "encoding/binary"
  9. )
  10. // ValueStruct represents the value info that can be associated with a key, but also the internal
  11. // Meta field.
  12. type ValueStruct struct {
  13. Meta byte
  14. UserMeta byte
  15. ExpiresAt uint64
  16. Value []byte
  17. Version uint64 // This field is not serialized. Only for internal usage.
  18. }
  19. func sizeVarint(x uint64) (n int) {
  20. for {
  21. n++
  22. x >>= 7
  23. if x == 0 {
  24. break
  25. }
  26. }
  27. return n
  28. }
  29. // EncodedSize is the size of the ValueStruct when encoded
  30. func (v *ValueStruct) EncodedSize() uint32 {
  31. sz := len(v.Value) + 2 // meta, usermeta.
  32. enc := sizeVarint(v.ExpiresAt)
  33. return uint32(sz + enc)
  34. }
  35. // Decode uses the length of the slice to infer the length of the Value field.
  36. func (v *ValueStruct) Decode(b []byte) {
  37. v.Meta = b[0]
  38. v.UserMeta = b[1]
  39. var sz int
  40. v.ExpiresAt, sz = binary.Uvarint(b[2:])
  41. v.Value = b[2+sz:]
  42. }
  43. // Encode expects a slice of length at least v.EncodedSize().
  44. func (v *ValueStruct) Encode(b []byte) uint32 {
  45. b[0] = v.Meta
  46. b[1] = v.UserMeta
  47. sz := binary.PutUvarint(b[2:], v.ExpiresAt)
  48. n := copy(b[2+sz:], v.Value)
  49. return uint32(2 + sz + n)
  50. }
  51. // EncodeTo should be kept in sync with the Encode function above. The reason
  52. // this function exists is to avoid creating byte arrays per key-value pair in
  53. // table/builder.go.
  54. func (v *ValueStruct) EncodeTo(buf *bytes.Buffer) {
  55. buf.WriteByte(v.Meta)
  56. buf.WriteByte(v.UserMeta)
  57. var enc [binary.MaxVarintLen64]byte
  58. sz := binary.PutUvarint(enc[:], v.ExpiresAt)
  59. buf.Write(enc[:sz])
  60. buf.Write(v.Value)
  61. }
  62. // Iterator is an interface for a basic iterator.
  63. type Iterator interface {
  64. Next()
  65. Rewind()
  66. Seek(key []byte)
  67. Key() []byte
  68. Value() ValueStruct
  69. Valid() bool
  70. // All iterators should be closed so that file garbage collection works.
  71. Close() error
  72. }