-
Notifications
You must be signed in to change notification settings - Fork 0
/
n48.go
145 lines (129 loc) · 2.41 KB
/
n48.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
package art
import (
"bytes"
"encoding/hex"
)
type node48[T any] struct {
lth uint8
keys [256]uint16
children [48]node[T]
}
func (n *node48[T]) Kind() Kind {
return Node48
}
func (n *node48[T]) leftmost() (v node[T]) {
idx := 0
for ; n.keys[idx] == 0; idx++ {
}
return n.children[n.keys[idx]-1].leftmost()
}
func (n *node48[T]) child(k byte) (int, node[T]) {
idx := n.keys[k]
if idx == 0 {
return 0, nil
}
return int(k), n.children[idx-1]
}
func (n *node48[T]) next(k *byte) (byte, node[T]) {
for b, idx := range n.keys {
if (k == nil || byte(b) > *k) && idx != 0 {
return byte(b), n.children[idx-1]
}
}
return 0, nil
}
func (n *node48[T]) prev(k *byte) (byte, node[T]) {
for b := n.lth - 1; b >= 0; b-- {
idx := n.keys[b]
if (k == nil || byte(b) < *k) && idx != 0 {
return byte(b), n.children[idx]
}
}
return 0, nil
}
func (n *node48[T]) full() bool {
return n.lth == 48
}
func (n *node48[T]) addChild(k byte, child node[T]) {
for idx, existing := range n.children {
if existing == nil {
n.keys[k] = uint16(idx + 1)
n.children[idx] = child
n.lth++
return
}
}
panic("no empty slots")
}
func (n *node48[T]) grow() inode[T] {
nn := &node256[T]{
lth: uint16(n.lth),
}
for b, i := range n.keys {
if i == 0 {
continue
}
nn.children[b] = n.children[i-1]
}
return nn
}
func (n *node48[T]) replace(k int, child node[T]) (old node[T]) {
idx := n.keys[k]
if idx == 0 {
panic("replace can't be called for idx=0")
}
old = n.children[idx-1]
n.children[idx-1] = child
if child == nil {
n.keys[k] = 0
n.lth--
}
return
}
func (n *node48[T]) min() bool {
return n.lth <= 17
}
func (n *node48[T]) shrink() inode[T] {
nn := &node16[T]{
lth: n.lth,
}
nni := 0
for i, idx := range n.keys {
if idx == 0 {
continue
}
child := n.children[idx-1]
if child != nil {
nn.keys[nni] = byte(i)
nn.children[nni] = child
nni++
}
}
return nn
}
func (n *node48[T]) walk(fn walkFn[T], depth int) bool {
for _, child := range n.children {
if child != nil {
if !child.walk(fn, depth) {
return false
}
}
}
return true
}
func (n *node48[T]) String() string {
var b bytes.Buffer
_, _ = b.WriteString("n48[")
encoder := hex.NewEncoder(&b)
for i, idx := range n.keys {
if idx == 0 {
continue
}
child := n.children[idx-1]
if child != nil {
_, _ = encoder.Write([]byte{byte(i)})
}
}
_, _ = b.WriteString("]")
return b.String()
}