-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.go
72 lines (55 loc) · 1.63 KB
/
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
package diskbst
import "encoding/binary"
type node struct {
key []byte
value []byte
leftChild uint64 // stores the file offset positions of left child node
rightChild uint64 // stores the file offset positions of right child node
}
func (n *node) serialize() []byte {
// 8 bytes for the total node length.
// 8 bytes for the key length, followed by the key itself.
// 8 bytes for the value length, followed by the value itself.
// 8 bytes each for the leftChild and rightChild offsets.
res := make([]byte, 8+uint64(8+len(n.key)+8+len(n.value)+8+8))
var pos int
// node length
binary.LittleEndian.PutUint64(res[pos:], uint64(8+len(n.key)+8+len(n.value)+8+8))
pos += 8
// key length
binary.LittleEndian.PutUint64(res[pos:], uint64(len(n.key)))
pos += 8
// key
copy(res[pos:pos+len(n.key)], n.key)
pos += len(n.key)
// value length
binary.LittleEndian.PutUint64(res[pos:], uint64(len(n.value)))
pos += 8
// value
copy(res[pos:pos+len(n.value)], n.value)
pos += len(n.value)
// left child
binary.LittleEndian.PutUint64(res[pos:], n.leftChild)
pos += 8
// right child
binary.LittleEndian.PutUint64(res[pos:], n.rightChild)
pos += 8
return res
}
func (n *node) deserialize(data []byte) {
var pos int
keyLen := binary.LittleEndian.Uint64(data[pos:])
pos += 8
n.key = make([]byte, keyLen)
copy(n.key, data[pos:])
pos += len(n.key)
valueLen := binary.LittleEndian.Uint64(data[pos:])
n.value = make([]byte, valueLen)
pos += 8
copy(n.value, data[pos:])
pos += len(n.value)
n.leftChild = binary.LittleEndian.Uint64(data[pos:])
pos += 8
n.rightChild = binary.LittleEndian.Uint64(data[pos:])
pos += 8
}