Debian Codegraph @

server/stree/node16.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 16 children
17 // Order of struct fields for best memory alignment (as per govet/fieldalignment)
18 type node16 struct {
19 child [16]node
20 meta
21 key [16]byte
22 }
23
24 func newNode16(prefix []byte) *node16 {
25 nn := &node16{}
26 nn.setPrefix(prefix)
27 return nn
28 }
29
30 // Currently we do not keep node16 sorted or use bitfields for traversal so just add to the end.
31 // TODO(dlc) - We should revisit here with more detailed benchmarks.
32 func (n *node16) addChild(c byte, nn node) {
33 if n.size >= 16 {
34 panic("node16 full!")
35 }
36 n.key[n.size] = c
37 n.child[n.size] = nn
38 n.size++
39 }
40
41 func (n *node16) findChild(c byte) *node {
42 for i := uint16(0); i < n.size; i++ {
43 if n.key[i] == c {
44 return &n.child[i]
45 }
46 }
47 return nil
48 }
49
50 func (n *node16) isFull() bool { return n.size >= 16 }
51
52 func (n *node16) grow() node {
53 nn := &node48{}
54 nn.prefix = n.prefix
55 for i := 0; i < 16; i++ {
56 nn.addChild(n.key[i], n.child[i])
57 }
58 return nn
59 }
60
61 // Deletes a child from the node.
62 func (n *node16) deleteChild(c byte) {
63 for i, last := uint16(0), n.size-1; i < n.size; i++ {
64 if n.key[i] == c {
65 // Unsorted so just swap in last one here, else nil if last.
66 if i < last {
67 n.key[i] = n.key[last]
68 n.child[i] = n.child[last]
69 n.key[last] = 0
70 n.child[last] = nil
71 } else {
72 n.key[i] = 0
73 n.child[i] = nil
74 }
75 n.size--
76 return
77 }
78 }
79 }
80
81 // Shrink if needed and return new node, otherwise return nil.
82 func (n *node16) shrink() node {
83 if n.size > 10 {
84 return nil
85 }
86 nn := newNode10(nil)
87 for i := uint16(0); i < n.size; i++ {
88 nn.addChild(n.key[i], n.child[i])
89 }
90 return nn
91 }
92
93 // Iterate over all children calling func f.
94 func (n *node16) iter(f func(node) bool) {
95 for i := uint16(0); i < n.size; i++ {
96 if !f(n.child[i]) {
97 return
98 }
99 }
100 }
101
102 // Return our children as a slice.
103 func (n *node16) children() []node {
104 return n.child[:n.size]
105 }