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