-
Notifications
You must be signed in to change notification settings - Fork 672
/
codec.go
341 lines (294 loc) · 7.22 KB
/
codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package merkledb
import (
"bytes"
"encoding/binary"
"errors"
"io"
"math"
"math/bits"
"slices"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/maybe"
)
const (
boolLen = 1
trueByte = 1
falseByte = 0
)
var (
trueBytes = []byte{trueByte}
falseBytes = []byte{falseByte}
errChildIndexTooLarge = errors.New("invalid child index. Must be less than branching factor")
errLeadingZeroes = errors.New("varint has leading zeroes")
errInvalidBool = errors.New("decoded bool is neither true nor false")
errNonZeroKeyPadding = errors.New("key partial byte should be padded with 0s")
errExtraSpace = errors.New("trailing buffer space")
errIntOverflow = errors.New("value overflows int")
errTooManyChildren = errors.New("too many children")
)
func childSize(index byte, childEntry *child) int {
// * index
// * child ID
// * child key
// * bool indicating whether the child has a value
return uintSize(uint64(index)) + ids.IDLen + keySize(childEntry.compressedKey) + boolLen
}
// based on the implementation of encodeUint which uses binary.PutUvarint
func uintSize(value uint64) int {
if value == 0 {
return 1
}
return (bits.Len64(value) + 6) / 7
}
func keySize(p Key) int {
return uintSize(uint64(p.length)) + bytesNeeded(p.length)
}
// Assumes [n] is non-nil.
func encodedDBNodeSize(n *dbNode) int {
// * number of children
// * bool indicating whether [n] has a value
// * the value (optional)
// * children
size := uintSize(uint64(len(n.children))) + boolLen
if n.value.HasValue() {
valueLen := len(n.value.Value())
size += uintSize(uint64(valueLen)) + valueLen
}
// for each non-nil entry, we add the additional size of the child entry
for index, entry := range n.children {
size += childSize(index, entry)
}
return size
}
// Assumes [n] is non-nil.
func encodeDBNode(n *dbNode) []byte {
length := encodedDBNodeSize(n)
w := codecWriter{
b: make([]byte, 0, length),
}
w.MaybeBytes(n.value)
numChildren := len(n.children)
w.Uvarint(uint64(numChildren))
// Avoid allocating keys entirely if the node doesn't have any children.
if numChildren == 0 {
return w.b
}
// By allocating BranchFactorLargest rather than [numChildren], this slice
// is allocated on the stack rather than the heap. BranchFactorLargest is
// at least [numChildren] which avoids memory allocations.
keys := make([]byte, numChildren, BranchFactorLargest)
i := 0
for k := range n.children {
keys[i] = k
i++
}
// Ensure that the order of entries is correct.
slices.Sort(keys)
for _, index := range keys {
entry := n.children[index]
w.Uvarint(uint64(index))
w.Key(entry.compressedKey)
w.ID(entry.id)
w.Bool(entry.hasValue)
}
return w.b
}
func encodeKey(key Key) []byte {
length := uintSize(uint64(key.length)) + len(key.Bytes())
w := codecWriter{
b: make([]byte, 0, length),
}
w.Key(key)
return w.b
}
type codecWriter struct {
b []byte
}
func (w *codecWriter) Bool(v bool) {
if v {
w.b = append(w.b, trueByte)
} else {
w.b = append(w.b, falseByte)
}
}
func (w *codecWriter) Uvarint(v uint64) {
w.b = binary.AppendUvarint(w.b, v)
}
func (w *codecWriter) ID(v ids.ID) {
w.b = append(w.b, v[:]...)
}
func (w *codecWriter) Bytes(v []byte) {
w.Uvarint(uint64(len(v)))
w.b = append(w.b, v...)
}
func (w *codecWriter) MaybeBytes(v maybe.Maybe[[]byte]) {
hasValue := v.HasValue()
w.Bool(hasValue)
if hasValue {
w.Bytes(v.Value())
}
}
func (w *codecWriter) Key(v Key) {
w.Uvarint(uint64(v.length))
w.b = append(w.b, v.Bytes()...)
}
// Assumes [n] is non-nil.
func decodeDBNode(b []byte, n *dbNode) error {
r := codecReader{
b: b,
copy: true,
}
var err error
n.value, err = r.MaybeBytes()
if err != nil {
return err
}
numChildren, err := r.Uvarint()
if err != nil {
return err
}
if numChildren > uint64(BranchFactorLargest) {
return errTooManyChildren
}
n.children = make(map[byte]*child, numChildren)
var previousChild uint64
for i := uint64(0); i < numChildren; i++ {
index, err := r.Uvarint()
if err != nil {
return err
}
if (i != 0 && index <= previousChild) || index > math.MaxUint8 {
return errChildIndexTooLarge
}
previousChild = index
compressedKey, err := r.Key()
if err != nil {
return err
}
childID, err := r.ID()
if err != nil {
return err
}
hasValue, err := r.Bool()
if err != nil {
return err
}
n.children[byte(index)] = &child{
compressedKey: compressedKey,
id: childID,
hasValue: hasValue,
}
}
if len(r.b) != 0 {
return errExtraSpace
}
return nil
}
func decodeKey(b []byte) (Key, error) {
r := codecReader{
b: b,
copy: true,
}
key, err := r.Key()
if err != nil {
return Key{}, err
}
if len(r.b) != 0 {
return Key{}, errExtraSpace
}
return key, nil
}
type codecReader struct {
b []byte
// copy is used to flag to the reader if it is required to copy references
// to [b].
copy bool
}
func (r *codecReader) Bool() (bool, error) {
if len(r.b) < boolLen {
return false, io.ErrUnexpectedEOF
}
boolByte := r.b[0]
if boolByte > trueByte {
return false, errInvalidBool
}
r.b = r.b[boolLen:]
return boolByte == trueByte, nil
}
func (r *codecReader) Uvarint() (uint64, error) {
length, bytesRead := binary.Uvarint(r.b)
if bytesRead <= 0 {
return 0, io.ErrUnexpectedEOF
}
// To ensure decoding is canonical, we check for leading zeroes in the
// varint.
// The last byte of the varint includes the most significant bits.
// If the last byte is 0, then the number should have been encoded more
// efficiently by removing this leading zero.
if bytesRead > 1 && r.b[bytesRead-1] == 0x00 {
return 0, errLeadingZeroes
}
r.b = r.b[bytesRead:]
return length, nil
}
func (r *codecReader) ID() (ids.ID, error) {
if len(r.b) < ids.IDLen {
return ids.Empty, io.ErrUnexpectedEOF
}
id := ids.ID(r.b[:ids.IDLen])
r.b = r.b[ids.IDLen:]
return id, nil
}
func (r *codecReader) Bytes() ([]byte, error) {
length, err := r.Uvarint()
if err != nil {
return nil, err
}
if length > uint64(len(r.b)) {
return nil, io.ErrUnexpectedEOF
}
result := r.b[:length]
if r.copy {
result = bytes.Clone(result)
}
r.b = r.b[length:]
return result, nil
}
func (r *codecReader) MaybeBytes() (maybe.Maybe[[]byte], error) {
if hasValue, err := r.Bool(); err != nil || !hasValue {
return maybe.Nothing[[]byte](), err
}
bytes, err := r.Bytes()
return maybe.Some(bytes), err
}
func (r *codecReader) Key() (Key, error) {
bitLen, err := r.Uvarint()
if err != nil {
return Key{}, err
}
if bitLen > math.MaxInt {
return Key{}, errIntOverflow
}
result := Key{
length: int(bitLen),
}
byteLen := bytesNeeded(result.length)
if byteLen > len(r.b) {
return Key{}, io.ErrUnexpectedEOF
}
if result.hasPartialByte() {
// Confirm that the padding bits in the partial byte are 0.
// We want to only look at the bits to the right of the last token,
// which is at index length-1.
// Generate a mask where the (result.length % 8) left bits are 0.
paddingMask := byte(0xFF >> (result.length % 8))
if r.b[byteLen-1]&paddingMask != 0 {
return Key{}, errNonZeroKeyPadding
}
}
result.value = string(r.b[:byteLen])
r.b = r.b[byteLen:]
return result, nil
}