Debian Codegraph @

debian/go/src/github.com/gohugoio/go-radix/radix.go

raw
1 package radix
2
3 import (
4 "sort"
5 "strings"
6 )
7
8 // WalkFlag is a bitmask return value for Walk functions.
9 type WalkFlag uint32
10
11 const (
12 WalkContinue WalkFlag = 0
13 WalkSkip WalkFlag = 1 << 0
14 WalkStop WalkFlag = 1 << 1
15 WalkSet WalkFlag = 1 << 2
16 )
17
18 // ShouldStop returns true if the walk should terminate.
19 func (w WalkFlag) ShouldStop() bool {
20 return w&WalkStop != 0
21 }
22
23 // ShouldSet returns true if the walk function wants to set a new value.
24 func (w WalkFlag) ShouldSet() bool {
25 return w&WalkSet != 0
26 }
27
28 // ShouldSkip returns true if the walk should skip this node.
29 func (w WalkFlag) ShouldSkip() bool {
30 return w&WalkSkip != 0
31 }
32
33 // WalkFn is used when walking the tree. Takes a
34 // key and value, returning a WalkFlag to indicate
35 // how to proceed and possibly a new value to set.
36 type WalkFn[T any] func(s string, v T) (WalkFlag, T, error)
37
38 func (wf WalkFn[T]) Check(s string) (WalkFlag, error) {
39 return WalkContinue, nil
40 }
41
42 func (wf WalkFn[T]) Handle(s string, v T) (WalkFlag, T, error) {
43 return wf(s, v)
44 }
45
46 // WalkHandler is the handler passed to Walk functions.
47 // When split into two steps, this allows us to walk the
48 // keys withut reading the values.
49 type WalkHandler[T any] interface {
50 Check(s string) (WalkFlag, error)
51 Handle(s string, v T) (WalkFlag, T, error)
52 }
53
54 // leafNode is used to represent a value
55 type leafNode[T any] struct {
56 key string
57 val T
58 }
59
60 // edge is used to represent an edge node
61 type edge[T any] struct {
62 label byte
63 node *node[T]
64 }
65
66 type node[T any] struct {
67 // leaf is used to store possible leaf
68 leaf *leafNode[T]
69
70 // prefix is the common prefix we ignore
71 prefix string
72
73 // Edges should be stored in-order for iteration.
74 // We avoid a fully materialized slice to save memory,
75 // since in most cases we expect to be sparse
76 edges edges[T]
77 }
78
79 func (n *node[T]) isLeaf() bool {
80 return n.leaf != nil
81 }
82
83 func (n *node[T]) addEdge(e edge[T]) {
84 num := len(n.edges)
85 idx := sort.Search(num, func(i int) bool {
86 return n.edges[i].label >= e.label
87 })
88
89 n.edges = append(n.edges, edge[T]{})
90 copy(n.edges[idx+1:], n.edges[idx:])
91 n.edges[idx] = e
92 }
93
94 func (n *node[T]) updateEdge(label byte, node *node[T]) {
95 num := len(n.edges)
96 idx := sort.Search(num, func(i int) bool {
97 return n.edges[i].label >= label
98 })
99 if idx < num && n.edges[idx].label == label {
100 n.edges[idx].node = node
101 return
102 }
103 panic("replacing missing edge")
104 }
105
106 func (n *node[T]) getEdge(label byte) *node[T] {
107 num := len(n.edges)
108 idx := sort.Search(num, func(i int) bool {
109 return n.edges[i].label >= label
110 })
111 if idx < num && n.edges[idx].label == label {
112 return n.edges[idx].node
113 }
114 return nil
115 }
116
117 func (n *node[T]) delEdge(label byte) {
118 num := len(n.edges)
119 idx := sort.Search(num, func(i int) bool {
120 return n.edges[i].label >= label
121 })
122 if idx < num && n.edges[idx].label == label {
123 copy(n.edges[idx:], n.edges[idx+1:])
124 n.edges[len(n.edges)-1] = edge[T]{}
125 n.edges = n.edges[:len(n.edges)-1]
126 }
127 }
128
129 type edges[T any] []edge[T]
130
131 func (e edges[T]) Len() int {
132 return len(e)
133 }
134
135 func (e edges[T]) Less(i, j int) bool {
136 return e[i].label < e[j].label
137 }
138
139 func (e edges[T]) Swap(i, j int) {
140 e[i], e[j] = e[j], e[i]
141 }
142
143 func (e edges[T]) Sort() {
144 sort.Sort(e)
145 }
146
147 // Tree implements a radix tree. This can be treated as a
148 // Dictionary abstract data type. The main advantage over
149 // a standard hash map is prefix-based lookups and
150 // ordered iteration,
151 type Tree[T any] struct {
152 root *node[T]
153 size int
154 }
155
156 // New returns an empty Tree
157 func New[T any]() *Tree[T] {
158 return NewFromMap[T](nil)
159 }
160
161 // NewFromMap returns a new tree containing the keys
162 // from an existing map
163 func NewFromMap[T any](m map[string]T) *Tree[T] {
164 t := &Tree[T]{root: &node[T]{}}
165 for k, v := range m {
166 t.Insert(k, v)
167 }
168 return t
169 }
170
171 // Len is used to return the number of elements in the tree
172 func (t *Tree[T]) Len() int {
173 return t.size
174 }
175
176 // longestPrefix finds the length of the shared prefix
177 // of two strings
178 func longestPrefix(k1, k2 string) int {
179 max := len(k1)
180 if l := len(k2); l < max {
181 max = l
182 }
183 var i int
184 for i = 0; i < max; i++ {
185 if k1[i] != k2[i] {
186 break
187 }
188 }
189 return i
190 }
191
192 // Insert is used to add a newentry or update
193 // an existing entry. Returns true if an existing record is updated.
194 func (t *Tree[T]) Insert(s string, v T) (T, bool) {
195 var parent *node[T]
196 n := t.root
197 search := s
198 for {
199 // Handle key exhaution
200 if len(search) == 0 {
201 if n.isLeaf() {
202 old := n.leaf.val
203 n.leaf.val = v
204 return old, true
205 }
206
207 n.leaf = &leafNode[T]{
208 key: s,
209 val: v,
210 }
211 t.size++
212 var zero T
213 return zero, false
214 }
215
216 // Look for the edge
217 parent = n
218 n = n.getEdge(search[0])
219
220 // No edge, create one
221 if n == nil {
222 e := edge[T]{
223 label: search[0],
224 node: &node[T]{
225 leaf: &leafNode[T]{
226 key: s,
227 val: v,
228 },
229 prefix: search,
230 },
231 }
232 parent.addEdge(e)
233 t.size++
234 var zero T
235 return zero, false
236 }
237
238 // Determine longest prefix of the search key on match
239 commonPrefix := longestPrefix(search, n.prefix)
240 if commonPrefix == len(n.prefix) {
241 search = search[commonPrefix:]
242 continue
243 }
244
245 // Split the node
246 t.size++
247 child := &node[T]{
248 prefix: search[:commonPrefix],
249 }
250 parent.updateEdge(search[0], child)
251
252 // Restore the existing node
253 child.addEdge(edge[T]{
254 label: n.prefix[commonPrefix],
255 node: n,
256 })
257 n.prefix = n.prefix[commonPrefix:]
258
259 // Create a new leaf node
260 leaf := &leafNode[T]{
261 key: s,
262 val: v,
263 }
264
265 // If the new key is a subset, add to this node
266 search = search[commonPrefix:]
267 if len(search) == 0 {
268 child.leaf = leaf
269 var zero T
270 return zero, false
271 }
272
273 // Create a new edge for the node
274 child.addEdge(edge[T]{
275 label: search[0],
276 node: &node[T]{
277 leaf: leaf,
278 prefix: search,
279 },
280 })
281 var zero T
282 return zero, false
283 }
284 }
285
286 // Delete is used to delete a key, returning the previous
287 // value and if it was deleted
288 func (t *Tree[T]) Delete(s string) (T, bool) {
289 var parent *node[T]
290 var label byte
291 n := t.root
292 search := s
293 var zero T
294 for {
295 // Check for key exhaution
296 if len(search) == 0 {
297 if !n.isLeaf() {
298 break
299 }
300 goto DELETE
301 }
302
303 // Look for an edge
304 parent = n
305 label = search[0]
306 n = n.getEdge(label)
307 if n == nil {
308 break
309 }
310
311 // Consume the search prefix
312 if strings.HasPrefix(search, n.prefix) {
313 search = search[len(n.prefix):]
314 } else {
315 break
316 }
317 }
318 return zero, false
319
320 DELETE:
321 // Delete the leaf
322 leaf := n.leaf
323 n.leaf = nil
324 t.size--
325
326 // Check if we should delete this node from the parent
327 if parent != nil && len(n.edges) == 0 {
328 parent.delEdge(label)
329 }
330
331 // Check if we should merge this node
332 if n != t.root && len(n.edges) == 1 {
333 n.mergeChild()
334 }
335
336 // Check if we should merge the parent's other child
337 if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
338 parent.mergeChild()
339 }
340
341 return leaf.val, true
342 }
343
344 // DeletePrefix is used to delete the subtree under a prefix
345 // Returns how many nodes were deleted
346 // Use this to delete large subtrees efficiently
347 func (t *Tree[T]) DeletePrefix(s string) int {
348 return t.deletePrefix(nil, t.root, s)
349 }
350
351 // delete does a recursive deletion
352 func (t *Tree[T]) deletePrefix(parent, n *node[T], prefix string) int {
353 // Check for key exhaustion
354 if len(prefix) == 0 {
355 // Remove the leaf node
356 subTreeSize := 0
357 var fn WalkFn[T] = func(s string, v T) (WalkFlag, T, error) {
358 subTreeSize++
359 return WalkContinue, v, nil
360 }
361 // recursively walk from all edges of the node to be deleted
362 recursiveWalk(n, fn)
363 if n.isLeaf() {
364 n.leaf = nil
365 }
366 n.edges = nil // deletes the entire subtree
367
368 // Check if we should merge the parent's other child
369 if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
370 parent.mergeChild()
371 }
372 t.size -= subTreeSize
373 return subTreeSize
374 }
375
376 // Look for an edge
377 label := prefix[0]
378 child := n.getEdge(label)
379 if child == nil || (!strings.HasPrefix(child.prefix, prefix) && !strings.HasPrefix(prefix, child.prefix)) {
380 return 0
381 }
382
383 // Consume the search prefix
384 if len(child.prefix) > len(prefix) {
385 prefix = prefix[len(prefix):]
386 } else {
387 prefix = prefix[len(child.prefix):]
388 }
389 return t.deletePrefix(n, child, prefix)
390 }
391
392 func (n *node[T]) mergeChild() {
393 e := n.edges[0]
394 child := e.node
395 n.prefix = n.prefix + child.prefix
396 n.leaf = child.leaf
397 n.edges = child.edges
398 }
399
400 // Get is used to lookup a specific key, returning
401 // the value and if it was found
402 func (t *Tree[T]) Get(s string) (T, bool) {
403 n := t.root
404 search := s
405 for {
406 // Check for key exhaution
407 if len(search) == 0 {
408 if n.isLeaf() {
409 return n.leaf.val, true
410 }
411 break
412 }
413
414 // Look for an edge
415 n = n.getEdge(search[0])
416 if n == nil {
417 break
418 }
419
420 // Consume the search prefix
421 if strings.HasPrefix(search, n.prefix) {
422 search = search[len(n.prefix):]
423 } else {
424 break
425 }
426 }
427 var zero T
428 return zero, false
429 }
430
431 // LongestPrefix is like Get, but instead of an
432 // exact match, it will return the longest prefix match.
433 func (t *Tree[T]) LongestPrefix(s string) (string, T, bool) {
434 var last *leafNode[T]
435 n := t.root
436 search := s
437 for {
438 // Look for a leaf node
439 if n.isLeaf() {
440 last = n.leaf
441 }
442
443 // Check for key exhaution
444 if len(search) == 0 {
445 break
446 }
447
448 // Look for an edge
449 n = n.getEdge(search[0])
450 if n == nil {
451 break
452 }
453
454 // Consume the search prefix
455 if strings.HasPrefix(search, n.prefix) {
456 search = search[len(n.prefix):]
457 } else {
458 break
459 }
460 }
461 if last != nil {
462 return last.key, last.val, true
463 }
464 var zero T
465 return "", zero, false
466 }
467
468 // Minimum is used to return the minimum value in the tree
469 func (t *Tree[T]) Minimum() (string, T, bool) {
470 n := t.root
471 for {
472 if n.isLeaf() {
473 return n.leaf.key, n.leaf.val, true
474 }
475 if len(n.edges) > 0 {
476 n = n.edges[0].node
477 } else {
478 break
479 }
480 }
481 var zero T
482 return "", zero, false
483 }
484
485 // Maximum is used to return the maximum value in the tree
486 func (t *Tree[T]) Maximum() (string, T, bool) {
487 n := t.root
488 for {
489 if num := len(n.edges); num > 0 {
490 n = n.edges[num-1].node
491 continue
492 }
493 if n.isLeaf() {
494 return n.leaf.key, n.leaf.val, true
495 }
496 break
497 }
498 var zero T
499 return "", zero, false
500 }
501
502 // Walk is used to walk the tree
503 func (t *Tree[T]) Walk(h WalkHandler[T]) error {
504 _, err := recursiveWalk(t.root, h)
505 return err
506 }
507
508 // WalkPrefix is used to walk the tree under a prefix
509 func (t *Tree[T]) WalkPrefix(prefix string, h WalkHandler[T]) error {
510 n := t.root
511 search := prefix
512 for {
513 // Check for key exhaustion
514 if len(search) == 0 {
515 _, err := recursiveWalk(n, h)
516 return err
517 }
518
519 // Look for an edge
520 n = n.getEdge(search[0])
521 if n == nil {
522 return nil
523 }
524
525 // Consume the search prefix
526 if strings.HasPrefix(search, n.prefix) {
527 search = search[len(n.prefix):]
528 continue
529 }
530 if strings.HasPrefix(n.prefix, search) {
531 // Child may be under our search prefix
532 _, err := recursiveWalk(n, h)
533 return err
534 }
535 return nil
536 }
537 }
538
539 // WalkPath is used to walk the tree, but only visiting nodes
540 // from the root down to a given leaf. Where WalkPrefix walks
541 // all the entries *under* the given prefix, this walks the
542 // entries *above* the given prefix.
543 func (t *Tree[T]) WalkPath(path string, h WalkHandler[T]) error {
544 n := t.root
545 search := path
546 for {
547 // Visit the leaf values if any
548 if n.leaf != nil {
549 f, err := h.Check(n.leaf.key)
550 if err != nil {
551 return err
552 }
553 if f.ShouldStop() {
554 return nil
555 }
556 if !f.ShouldSkip() {
557 f, n2, err := h.Handle(n.leaf.key, n.leaf.val)
558 if err != nil {
559 return err
560 }
561 if f.ShouldSet() {
562 n.leaf.val = n2
563 }
564 if f.ShouldStop() {
565 return nil
566 }
567 }
568 }
569
570 // Check for key exhaustion
571 if len(search) == 0 {
572 return nil
573 }
574
575 // Look for an edge
576 n = n.getEdge(search[0])
577 if n == nil {
578 return nil
579 }
580
581 // Consume the search prefix
582 if strings.HasPrefix(search, n.prefix) {
583 search = search[len(n.prefix):]
584 } else {
585 break
586 }
587 }
588 return nil
589 }
590
591 // recursiveWalk is used to do a pre-order walk of a node
592 // recursively. Returns true if the walk should be aborted
593 func recursiveWalk[T any](n *node[T], h WalkHandler[T]) (bool, error) {
594 // Visit the leaf values if any
595 if n.leaf != nil {
596 f, err := h.Check(n.leaf.key)
597 if err != nil {
598 return false, err
599 }
600 if f.ShouldStop() {
601 return true, nil
602 }
603 if !f.ShouldSkip() {
604 f, n2, err := h.Handle(n.leaf.key, n.leaf.val)
605 if err != nil {
606 return false, err
607 }
608 if f.ShouldSet() {
609 n.leaf.val = n2
610 }
611 if f.ShouldStop() {
612 return true, nil
613 }
614 }
615 }
616
617 // Recurse on the children
618 i := 0
619 k := len(n.edges) // keeps track of number of edges in previous iteration
620 for i < k {
621 e := n.edges[i]
622 if stop, err := recursiveWalk(e.node, h); stop || err != nil {
623 return stop, err
624 }
625 // It is a possibility that the WalkFn modified the node we are
626 // iterating on. If there are no more edges, mergeChild happened,
627 // so the last edge became the current node n, on which we'll
628 // iterate one last time.
629 if len(n.edges) == 0 {
630 return recursiveWalk(n, h)
631 }
632 // If there are now less edges than in the previous iteration,
633 // then do not increment the loop index, since the current index
634 // points to a new edge. Otherwise, get to the next index.
635 if len(n.edges) >= k {
636 i++
637 }
638 k = len(n.edges)
639 }
640 return false, nil
641 }
642
643 // ToMap is used to walk the tree and convert it into a map
644 func (t *Tree[T]) ToMap() map[string]T {
645 out := make(map[string]T, t.size)
646 var zero T
647 var fn WalkFn[T] = func(k string, v T) (WalkFlag, T, error) {
648 out[k] = v
649 return WalkContinue, zero, nil
650 }
651 t.Walk(fn)
652 return out
653 }