Debian Codegraph @

server/stree/node48.go

raw
1 // Copyright 2023-2024 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package stree
15
16 // Node with 48 children
17 // Memory saving vs node256 comes from the fact that the child array is 16 bytes
18 // per `node` entry, so node256's 256*16=4096 vs node48's 256+(48*16)=1024
19 // Note that `key` is effectively 1-indexed, as 0 means no entry, so offset by 1
20 // Order of struct fields for best memory alignment (as per govet/fieldalignment)
21 type node48 struct {
22 child [48]node
23 meta
24 key [256]byte
25 }
26
27 func newNode48(prefix []byte) *node48 {
28 nn := &node48{}
29 nn.setPrefix(prefix)
30 return nn
31 }
32
33 func (n *node48) addChild(c byte, nn node) {
34 if n.size >= 48 {
35 panic("node48 full!")
36 }
37 n.child[n.size] = nn
38 n.key[c] = byte(n.size + 1) // 1-indexed
39 n.size++
40 }
41
42 func (n *node48) findChild(c byte) *node {
43 i := n.key[c]
44 if i == 0 {
45 return nil
46 }
47 return &n.child[i-1]
48 }
49
50 func (n *node48) isFull() bool { return n.size >= 48 }
51
52 func (n *node48) grow() node {
53 nn := &node256{}
54 nn.prefix = n.prefix
55 for c := 0; c < len(n.key); c++ {
56 if i := n.key[byte(c)]; i > 0 {
57 nn.addChild(byte(c), n.child[i-1])
58 }
59 }
60 return nn
61 }
62
63 // Deletes a child from the node.
64 func (n *node48) deleteChild(c byte) {
65 i := n.key[c]
66 if i == 0 {
67 return
68 }
69 i-- // Adjust for 1-indexing
70 last := byte(n.size - 1)
71 if i < last {
72 n.child[i] = n.child[last]
73 for ic := 0; ic < len(n.key); ic++ {
74 if n.key[byte(ic)] == last+1 {
75 n.key[byte(ic)] = i + 1
76 break
77 }
78 }
79 }
80 n.child[last] = nil
81 n.key[c] = 0
82 n.size--
83 }
84
85 // Shrink if needed and return new node, otherwise return nil.
86 func (n *node48) shrink() node {
87 if n.size > 16 {
88 return nil
89 }
90 nn := newNode16(nil)
91 for c := 0; c < len(n.key); c++ {
92 if i := n.key[byte(c)]; i > 0 {
93 nn.addChild(byte(c), n.child[i-1])
94 }
95 }
96 return nn
97 }
98
99 // Iterate over all children calling func f.
100 func (n *node48) iter(f func(node) bool) {
101 for _, c := range n.child {
102 if c != nil && !f(c) {
103 return
104 }
105 }
106 }
107
108 // Return our children as a slice.
109 func (n *node48) children() []node {
110 return n.child[:n.size]
111 }