-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmerge.go
56 lines (54 loc) · 1.74 KB
/
merge.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
package btree
import (
"github.com/golang/protobuf/proto"
"sync/atomic"
)
func (n *TreeNode) merge(tree *Btree, index int) int64 {
left, err := tree.getTreeNode(n.Childrens[index])
if err != nil {
return -1
}
right, err := tree.getTreeNode(n.Childrens[index+1])
if err != nil {
return -1
}
if len(left.Keys)+len(right.Keys) > int(tree.GetNodeMax()) {
return -1
}
if (len(left.Values) + len(right.Values)) > int(tree.GetLeafMax()) {
return -1
}
leftClone := left.clone(tree)
n.Childrens[index] = leftClone.GetId()
if leftClone.GetNodeType() == isLeaf {
if index == len(n.Keys) {
n.Childrens = n.Childrens[:index]
n.Keys = n.Keys[:index-1]
} else {
n.Childrens = append(n.Childrens[:index+1], n.Childrens[index+2:]...)
n.Keys = append(n.Keys[:index], n.Keys[index+1:]...)
}
// add right to left
leftClone.Values = append(leftClone.Values, right.Values...)
leftClone.Keys = append(leftClone.Keys, right.Keys...)
} else {
leftClone.Keys = append(leftClone.Keys, append([][]byte{n.Keys[index]}, right.Keys...)...)
// merge childrens
leftClone.Childrens = append(leftClone.Childrens, right.Childrens...)
// remove old key
n.Keys = append(n.Keys[:index], n.Keys[index+1:]...)
// remove old right node
n.Childrens = append(n.Childrens[:index+1], n.Childrens[index+2:]...)
// check size, spilt if over size
if len(leftClone.Keys) > int(tree.GetNodeMax()) {
key, left, right := leftClone.split(tree)
n.insertOnce(key, left, right, tree)
}
}
atomic.StoreInt32(right.IsDirt, 1)
atomic.StoreInt32(left.IsDirt, 1)
tree.Nodes[right.GetId()], err = proto.Marshal(right)
tree.Nodes[left.GetId()], err = proto.Marshal(left)
tree.Nodes[leftClone.GetId()], err = proto.Marshal(leftClone)
return leftClone.GetId()
}