-
Notifications
You must be signed in to change notification settings - Fork 22
/
collection.go
230 lines (194 loc) · 5.76 KB
/
collection.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
package LibraDB
import (
"bytes"
"encoding/binary"
)
type Collection struct {
name []byte
root pgnum
counter uint64
// associated transaction
tx *tx
}
func newCollection(name []byte, root pgnum) *Collection {
return &Collection{
name: name,
root: root,
}
}
func newEmptyCollection() *Collection {
return &Collection{}
}
func (c *Collection) ID() uint64 {
if !c.tx.write {
return 0
}
id := c.counter
c.counter += 1
return id
}
func (c *Collection) serialize() *Item {
b := make([]byte, collectionSize)
leftPos := 0
binary.LittleEndian.PutUint64(b[leftPos:], uint64(c.root))
leftPos += pageNumSize
binary.LittleEndian.PutUint64(b[leftPos:], c.counter)
leftPos += counterSize
return newItem(c.name, b)
}
func (c *Collection) deserialize(item *Item) {
c.name = item.key
if len(item.value) != 0 {
leftPos := 0
c.root = pgnum(binary.LittleEndian.Uint64(item.value[leftPos:]))
leftPos += pageNumSize
c.counter = binary.LittleEndian.Uint64(item.value[leftPos:])
leftPos += counterSize
}
}
// Put adds a key to the tree. It finds the correct node and the insertion index and adds the item. When performing the
// search, the ancestors are returned as well. This way we can iterate over them to check which nodes were modified and
// rebalance by splitting them accordingly. If the root has too many items, then a new root of a new layer is
// created and the created nodes from the split are added as children.
func (c *Collection) Put(key []byte, value []byte) error {
if !c.tx.write {
return writeInsideReadTxErr
}
i := newItem(key, value)
// On first insertion the root node does not exist, so it should be created
var root *Node
var err error
if c.root == 0 {
root = c.tx.writeNode(c.tx.newNode([]*Item{i}, []pgnum{}))
c.root = root.pageNum
return nil
} else {
root, err = c.tx.getNode(c.root)
if err != nil {
return err
}
}
// Find the path to the node where the insertion should happen
insertionIndex, nodeToInsertIn, ancestorsIndexes, err := root.findKey(i.key, false)
if err != nil {
return err
}
// If key already exists
if nodeToInsertIn.items != nil && insertionIndex < len(nodeToInsertIn.items) && bytes.Compare(nodeToInsertIn.items[insertionIndex].key, key) == 0 {
nodeToInsertIn.items[insertionIndex] = i
} else {
// Add item to the leaf node
nodeToInsertIn.addItem(i, insertionIndex)
}
nodeToInsertIn.writeNode(nodeToInsertIn)
ancestors, err := c.getNodes(ancestorsIndexes)
if err != nil {
return err
}
// Rebalance the nodes all the way up. Start From one node before the last and go all the way up. Exclude root.
for i := len(ancestors) - 2; i >= 0; i-- {
pnode := ancestors[i]
node := ancestors[i+1]
nodeIndex := ancestorsIndexes[i+1]
if node.isOverPopulated() {
pnode.split(node, nodeIndex)
}
}
// Handle root
rootNode := ancestors[0]
if rootNode.isOverPopulated() {
newRoot := c.tx.newNode([]*Item{}, []pgnum{rootNode.pageNum})
newRoot.split(rootNode, 0)
// commit newly created root
newRoot = c.tx.writeNode(newRoot)
c.root = newRoot.pageNum
}
return nil
}
// Find Returns an item according based on the given key by performing a binary search.
func (c *Collection) Find(key []byte) (*Item, error) {
n, err := c.tx.getNode(c.root)
if err != nil {
return nil, err
}
index, containingNode, _, err := n.findKey(key, true)
if err != nil {
return nil, err
}
if index == -1 {
return nil, nil
}
return containingNode.items[index], nil
}
// Remove removes a key from the tree. It finds the correct node and the index to remove the item from and removes it.
// When performing the search, the ancestors are returned as well. This way we can iterate over them to check which
// nodes were modified and rebalance by rotating or merging the unbalanced nodes. Rotation is done first. If the
// siblings don't have enough items, then merging occurs. If the root is without items after a split, then the root is
// removed and the tree is one level shorter.
func (c *Collection) Remove(key []byte) error {
if !c.tx.write {
return writeInsideReadTxErr
}
// Find the path to the node where the deletion should happen
rootNode, err := c.tx.getNode(c.root)
if err != nil {
return err
}
removeItemIndex, nodeToRemoveFrom, ancestorsIndexes, err := rootNode.findKey(key, true)
if err != nil {
return err
}
if removeItemIndex == -1 {
return nil
}
if nodeToRemoveFrom.isLeaf() {
nodeToRemoveFrom.removeItemFromLeaf(removeItemIndex)
} else {
affectedNodes, err := nodeToRemoveFrom.removeItemFromInternal(removeItemIndex)
if err != nil {
return err
}
ancestorsIndexes = append(ancestorsIndexes, affectedNodes...)
}
ancestors, err := c.getNodes(ancestorsIndexes)
if err != nil {
return err
}
// Rebalance the nodes all the way up. Start From one node before the last and go all the way up. Exclude root.
for i := len(ancestors) - 2; i >= 0; i-- {
pnode := ancestors[i]
node := ancestors[i+1]
if node.isUnderPopulated() {
err = pnode.rebalanceRemove(node, ancestorsIndexes[i+1])
if err != nil {
return err
}
}
}
rootNode = ancestors[0]
// If the root has no items after rebalancing, there's no need to save it because we ignore it.
if len(rootNode.items) == 0 && len(rootNode.childNodes) > 0 {
c.root = ancestors[1].pageNum
}
return nil
}
// getNodes returns a list of nodes based on their indexes (the breadcrumbs) from the root
// p
// / \
// a b
// / \ / \
// c d e f
// For [0,1,0] -> p,b,e
func (c *Collection) getNodes(indexes []int) ([]*Node, error) {
root, err := c.tx.getNode(c.root)
if err != nil {
return nil, err
}
nodes := []*Node{root}
child := root
for i := 1; i < len(indexes); i++ {
child, _ = c.tx.getNode(child.childNodes[indexes[i]])
nodes = append(nodes, child)
}
return nodes, nil
}