Debian Codegraph @

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