Debian Codegraph @

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