forked from cosmos/iavl
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfast_node.go
86 lines (71 loc) · 1.98 KB
/
fast_node.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
package fastnode
import (
"errors"
"fmt"
"io"
"github.com/cosmos/iavl/cache"
"github.com/cosmos/iavl/internal/encoding"
)
// NOTE: This file favors int64 as opposed to int for size/counts.
// The Tree on the other hand favors int. This is intentional.
type Node struct {
key []byte
versionLastUpdatedAt int64
value []byte
}
var _ cache.Node = (*Node)(nil)
// NewNode returns a new fast node from a value and version.
func NewNode(key []byte, value []byte, version int64) *Node {
return &Node{
key: key,
versionLastUpdatedAt: version,
value: value,
}
}
// DeserializeNode constructs an *FastNode from an encoded byte slice.
// It assumes we do not mutate this input []byte.
func DeserializeNode(key []byte, buf []byte) (*Node, error) {
ver, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding fastnode.version, %w", err)
}
buf = buf[n:]
val, _, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding fastnode.value, %w", err)
}
fastNode := &Node{
key: key,
versionLastUpdatedAt: ver,
value: val,
}
return fastNode, nil
}
func (fn *Node) GetKey() []byte {
return fn.key
}
func (fn *Node) EncodedSize() int {
n := encoding.EncodeVarintSize(fn.versionLastUpdatedAt) + encoding.EncodeBytesSize(fn.value)
return n
}
func (fn *Node) GetValue() []byte {
return fn.value
}
func (fn *Node) GetVersionLastUpdatedAt() int64 {
return fn.versionLastUpdatedAt
}
// WriteBytes writes the FastNode as a serialized byte slice to the supplied io.Writer.
func (fn *Node) WriteBytes(w io.Writer) error {
if fn == nil {
return errors.New("cannot write nil node")
}
err := encoding.EncodeVarint(w, fn.versionLastUpdatedAt)
if err != nil {
return fmt.Errorf("writing version last updated at, %w", err)
}
err = encoding.EncodeBytes(w, fn.value)
if err != nil {
return fmt.Errorf("writing value, %w", err)
}
return nil
}