Debian Codegraph @

third_party/forked/golang/btree/btree.go

raw
1 // Copyright 2014-2022 Google Inc.
2 // Copyright 2025 The Kubernetes Authors.
3 //
4 // This file is derived from github.com/google/btree and has been
5 // modified for use in the Kubernetes util package.
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18
19 // Package btree implements in-memory B-Trees of arbitrary degree.
20 //
21 // btree implements an in-memory B-Tree for use as an ordered data structure.
22 // It is not meant for persistent storage solutions.
23 //
24 // It has a flatter structure than an equivalent red-black or other binary tree,
25 // which in some cases yields better memory usage and/or performance.
26 // See some discussion on the matter here:
27 //
28 // http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
29 //
30 // Note, though, that this project is in no way related to the C++ B-Tree
31 // implementation written about there.
32 //
33 // Within this tree, each node contains a slice of items and a (possibly nil)
34 // slice of children. For basic numeric values or raw structs, this can cause
35 // efficiency differences when compared to equivalent C++ template code that
36 // stores values in arrays within the node:
37 // - Due to the overhead of storing values as interfaces (each
38 // value needs to be stored as the value itself, then 2 words for the
39 // interface pointing to that value and its type), resulting in higher
40 // memory use.
41 // - Since interfaces can point to values anywhere in memory, values are
42 // most likely not stored in contiguous blocks, resulting in a higher
43 // number of cache misses.
44 //
45 // These issues don't tend to matter, though, when working with strings or other
46 // heap-allocated structures, since C++-equivalent structures also must store
47 // pointers and also distribute their values across the heap.
48 //
49 // This implementation is designed to be a drop-in replacement to gollrb.LLRB
50 // trees, (http://github.com/petar/gollrb), an excellent and probably the most
51 // widely used ordered tree implementation in the Go ecosystem currently.
52 // Its functions, therefore, exactly mirror those of
53 // llrb.LLRB where possible. Unlike gollrb, though, we currently don't
54 // support storing multiple equivalent values.
55 package btree
56
57 import (
58 "cmp"
59 "sort"
60 "sync"
61 )
62
63 // DefaultFreeListSize is the default capacity of a BTree node free list.
64 const DefaultFreeListSize = 32
65
66 // FreeList represents a free list of btree nodes. By default each
67 // BTree has its own FreeList, but multiple BTrees can share the same
68 // FreeList, in particular when they're created with Clone.
69 // Two Btrees using the same freelist are safe for concurrent write access.
70 type FreeList[T any] struct {
71 mu sync.Mutex
72 freelist []*node[T]
73 }
74
75 // NewFreeList creates a new free list.
76 // size is the maximum size of the returned free list.
77 func NewFreeList[T any](size int) *FreeList[T] {
78 return &FreeList[T]{freelist: make([]*node[T], 0, size)}
79 }
80
81 func (f *FreeList[T]) newNode() (n *node[T]) {
82 f.mu.Lock()
83 index := len(f.freelist) - 1
84 if index < 0 {
85 f.mu.Unlock()
86 return new(node[T])
87 }
88 n = f.freelist[index]
89 f.freelist[index] = nil
90 f.freelist = f.freelist[:index]
91 f.mu.Unlock()
92 return
93 }
94
95 func (f *FreeList[T]) freeNode(n *node[T]) (out bool) {
96 f.mu.Lock()
97 if len(f.freelist) < cap(f.freelist) {
98 f.freelist = append(f.freelist, n)
99 out = true
100 }
101 f.mu.Unlock()
102 return
103 }
104
105 // ItemIterator allows callers of {A/De}scend* to iterate in-order over portions of
106 // the tree. When this function returns false, iteration will stop and the
107 // associated Ascend* function will immediately return.
108 type ItemIterator[T any] func(item T) bool
109
110 // Less returns a default LessFunc that uses the '<' operator for types that support it.
111 func Less[T cmp.Ordered]() LessFunc[T] {
112 return func(a, b T) bool { return a < b }
113 }
114
115 // NewOrdered creates a new B-Tree for ordered types.
116 func NewOrdered[T cmp.Ordered](degree int) *BTree[T] {
117 return New[T](degree, Less[T]())
118 }
119
120 // New creates a new B-Tree with the given degree.
121 //
122 // New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items
123 // and 2-4 children).
124 //
125 // The passed-in LessFunc determines how objects of type T are ordered.
126 func New[T any](degree int, less LessFunc[T]) *BTree[T] {
127 return NewWithFreeList(degree, less, NewFreeList[T](DefaultFreeListSize))
128 }
129
130 // NewWithFreeList creates a new B-Tree that uses the given node free list.
131 func NewWithFreeList[T any](degree int, less LessFunc[T], f *FreeList[T]) *BTree[T] {
132 if degree <= 1 {
133 panic("bad degree")
134 }
135 return &BTree[T]{
136 degree: degree,
137 cow: &copyOnWriteContext[T]{freelist: f, less: less},
138 }
139 }
140
141 // items stores items in a node.
142 type items[T any] []T
143
144 // insertAt inserts a value into the given index, pushing all subsequent values
145 // forward.
146 func (s *items[T]) insertAt(index int, item T) {
147 var zero T
148 *s = append(*s, zero)
149 if index < len(*s) {
150 copy((*s)[index+1:], (*s)[index:])
151 }
152 (*s)[index] = item
153 }
154
155 // removeAt removes a value at a given index, pulling all subsequent values
156 // back.
157 func (s *items[T]) removeAt(index int) T {
158 item := (*s)[index]
159 copy((*s)[index:], (*s)[index+1:])
160 var zero T
161 (*s)[len(*s)-1] = zero
162 *s = (*s)[:len(*s)-1]
163 return item
164 }
165
166 // pop removes and returns the last element in the list.
167 func (s *items[T]) pop() (out T) {
168 index := len(*s) - 1
169 out = (*s)[index]
170 var zero T
171 (*s)[index] = zero
172 *s = (*s)[:index]
173 return
174 }
175
176 // truncate truncates this instance at index so that it contains only the
177 // first index items. index must be less than or equal to length.
178 func (s *items[T]) truncate(index int) {
179 var toClear items[T]
180 *s, toClear = (*s)[:index], (*s)[index:]
181 var zero T
182 for i := 0; i < len(toClear); i++ {
183 toClear[i] = zero
184 }
185 }
186
187 // find returns the index where the given item should be inserted into this
188 // list. 'found' is true if the item already exists in the list at the given
189 // index.
190 func (s items[T]) find(item T, less func(T, T) bool) (index int, found bool) {
191 i := sort.Search(len(s), func(i int) bool {
192 return less(item, s[i])
193 })
194 if i > 0 && !less(s[i-1], item) {
195 return i - 1, true
196 }
197 return i, false
198 }
199
200 // node is an internal node in a tree.
201 //
202 // It must at all times maintain the invariant that either
203 // - len(children) == 0, len(items) unconstrained
204 // - len(children) == len(items) + 1
205 type node[T any] struct {
206 items items[T]
207 children items[*node[T]]
208 cow *copyOnWriteContext[T]
209 }
210
211 func (n *node[T]) mutableFor(cow *copyOnWriteContext[T]) *node[T] {
212 if n.cow == cow {
213 return n
214 }
215 out := cow.newNode()
216 if cap(out.items) >= len(n.items) {
217 out.items = out.items[:len(n.items)]
218 } else {
219 out.items = make(items[T], len(n.items), cap(n.items))
220 }
221 copy(out.items, n.items)
222 // Copy children
223 if cap(out.children) >= len(n.children) {
224 out.children = out.children[:len(n.children)]
225 } else {
226 out.children = make(items[*node[T]], len(n.children), cap(n.children))
227 }
228 copy(out.children, n.children)
229 return out
230 }
231
232 func (n *node[T]) mutableChild(i int) *node[T] {
233 c := n.children[i].mutableFor(n.cow)
234 n.children[i] = c
235 return c
236 }
237
238 // split splits the given node at the given index. The current node shrinks,
239 // and this function returns the item that existed at that index and a new node
240 // containing all items/children after it.
241 func (n *node[T]) split(i int) (T, *node[T]) {
242 item := n.items[i]
243 next := n.cow.newNode()
244 next.items = append(next.items, n.items[i+1:]...)
245 n.items.truncate(i)
246 if len(n.children) > 0 {
247 next.children = append(next.children, n.children[i+1:]...)
248 n.children.truncate(i + 1)
249 }
250 return item, next
251 }
252
253 // maybeSplitChild checks if a child should be split, and if so splits it.
254 // Returns whether or not a split occurred.
255 func (n *node[T]) maybeSplitChild(i, maxItems int) bool {
256 if len(n.children[i].items) < maxItems {
257 return false
258 }
259 first := n.mutableChild(i)
260 item, second := first.split(maxItems / 2)
261 n.items.insertAt(i, item)
262 n.children.insertAt(i+1, second)
263 return true
264 }
265
266 // insert inserts an item into the subtree rooted at this node, making sure
267 // no nodes in the subtree exceed maxItems items. Should an equivalent item be
268 // be found/replaced by insert, it will be returned.
269 func (n *node[T]) insert(item T, maxItems int) (_ T, _ bool) {
270 i, found := n.items.find(item, n.cow.less)
271 if found {
272 out := n.items[i]
273 n.items[i] = item
274 return out, true
275 }
276 if len(n.children) == 0 {
277 n.items.insertAt(i, item)
278 return
279 }
280 if n.maybeSplitChild(i, maxItems) {
281 inTree := n.items[i]
282 switch {
283 case n.cow.less(item, inTree):
284 // no change, we want first split node
285 case n.cow.less(inTree, item):
286 i++ // we want second split node
287 default:
288 out := n.items[i]
289 n.items[i] = item
290 return out, true
291 }
292 }
293 return n.mutableChild(i).insert(item, maxItems)
294 }
295
296 // get finds the given key in the subtree and returns it.
297 func (n *node[T]) get(key T) (_ T, _ bool) {
298 i, found := n.items.find(key, n.cow.less)
299 if found {
300 return n.items[i], true
301 } else if len(n.children) > 0 {
302 return n.children[i].get(key)
303 }
304 return
305 }
306
307 // min returns the first item in the subtree.
308 func min[T any](n *node[T]) (_ T, found bool) {
309 if n == nil {
310 return
311 }
312 for len(n.children) > 0 {
313 n = n.children[0]
314 }
315 if len(n.items) == 0 {
316 return
317 }
318 return n.items[0], true
319 }
320
321 // max returns the last item in the subtree.
322 func max[T any](n *node[T]) (_ T, found bool) {
323 if n == nil {
324 return
325 }
326 for len(n.children) > 0 {
327 n = n.children[len(n.children)-1]
328 }
329 if len(n.items) == 0 {
330 return
331 }
332 return n.items[len(n.items)-1], true
333 }
334
335 // toRemove details what item to remove in a node.remove call.
336 type toRemove int
337
338 const (
339 removeItem toRemove = iota // removes the given item
340 removeMin // removes smallest item in the subtree
341 removeMax // removes largest item in the subtree
342 )
343
344 // remove removes an item from the subtree rooted at this node.
345 func (n *node[T]) remove(item T, minItems int, typ toRemove) (_ T, _ bool) {
346 var i int
347 var found bool
348 switch typ {
349 case removeMax:
350 if len(n.children) == 0 {
351 return n.items.pop(), true
352 }
353 i = len(n.items)
354 case removeMin:
355 if len(n.children) == 0 {
356 return n.items.removeAt(0), true
357 }
358 i = 0
359 case removeItem:
360 i, found = n.items.find(item, n.cow.less)
361 if len(n.children) == 0 {
362 if found {
363 return n.items.removeAt(i), true
364 }
365 return
366 }
367 default:
368 panic("invalid type")
369 }
370 // If we get to here, we have children.
371 if len(n.children[i].items) <= minItems {
372 return n.growChildAndRemove(i, item, minItems, typ)
373 }
374 child := n.mutableChild(i)
375 // Either we had enough items to begin with, or we've done some
376 // merging/stealing, because we've got enough now and we're ready to return
377 // stuff.
378 if found {
379 // The item exists at index 'i', and the child we've selected can give us a
380 // predecessor, since if we've gotten here it's got > minItems items in it.
381 out := n.items[i]
382 // We use our special-case 'remove' call with typ=maxItem to pull the
383 // predecessor of item i (the rightmost leaf of our immediate left child)
384 // and set it into where we pulled the item from.
385 var zero T
386 n.items[i], _ = child.remove(zero, minItems, removeMax)
387 return out, true
388 }
389 // Final recursive call. Once we're here, we know that the item isn't in this
390 // node and that the child is big enough to remove from.
391 return child.remove(item, minItems, typ)
392 }
393
394 // growChildAndRemove grows child 'i' to make sure it's possible to remove an
395 // item from it while keeping it at minItems, then calls remove to actually
396 // remove it.
397 //
398 // Most documentation says we have to do two sets of special casing:
399 // 1. item is in this node
400 // 2. item is in child
401 //
402 // In both cases, we need to handle the two subcases:
403 //
404 // A) node has enough values that it can spare one
405 // B) node doesn't have enough values
406 //
407 // For the latter, we have to check:
408 //
409 // a) left sibling has node to spare
410 // b) right sibling has node to spare
411 // c) we must merge
412 //
413 // To simplify our code here, we handle cases #1 and #2 the same:
414 // If a node doesn't have enough items, we make sure it does (using a,b,c).
415 // We then simply redo our remove call, and the second time (regardless of
416 // whether we're in case 1 or 2), we'll have enough items and can guarantee
417 // that we hit case A.
418 func (n *node[T]) growChildAndRemove(i int, item T, minItems int, typ toRemove) (T, bool) {
419 if i > 0 && len(n.children[i-1].items) > minItems {
420 // Steal from left child
421 child := n.mutableChild(i)
422 stealFrom := n.mutableChild(i - 1)
423 stolenItem := stealFrom.items.pop()
424 child.items.insertAt(0, n.items[i-1])
425 n.items[i-1] = stolenItem
426 if len(stealFrom.children) > 0 {
427 child.children.insertAt(0, stealFrom.children.pop())
428 }
429 } else if i < len(n.items) && len(n.children[i+1].items) > minItems {
430 // steal from right child
431 child := n.mutableChild(i)
432 stealFrom := n.mutableChild(i + 1)
433 stolenItem := stealFrom.items.removeAt(0)
434 child.items = append(child.items, n.items[i])
435 n.items[i] = stolenItem
436 if len(stealFrom.children) > 0 {
437 child.children = append(child.children, stealFrom.children.removeAt(0))
438 }
439 } else {
440 if i >= len(n.items) {
441 i--
442 }
443 child := n.mutableChild(i)
444 // merge with right child
445 mergeItem := n.items.removeAt(i)
446 mergeChild := n.children.removeAt(i + 1)
447 child.items = append(child.items, mergeItem)
448 child.items = append(child.items, mergeChild.items...)
449 child.children = append(child.children, mergeChild.children...)
450 n.cow.freeNode(mergeChild)
451 }
452 return n.remove(item, minItems, typ)
453 }
454
455 type direction int
456
457 const (
458 descend = direction(-1)
459 ascend = direction(+1)
460 )
461
462 type optionalItem[T any] struct {
463 item T
464 valid bool
465 }
466
467 func optional[T any](item T) optionalItem[T] {
468 return optionalItem[T]{item: item, valid: true}
469 }
470 func empty[T any]() optionalItem[T] {
471 return optionalItem[T]{}
472 }
473
474 // iterate provides a simple method for iterating over elements in the tree.
475 //
476 // When ascending, the 'start' should be less than 'stop' and when descending,
477 // the 'start' should be greater than 'stop'. Setting 'includeStart' to true
478 // will force the iterator to include the first item when it equals 'start',
479 // thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a
480 // "greaterThan" or "lessThan" queries.
481 func (n *node[T]) iterate(dir direction, start, stop optionalItem[T], includeStart bool, hit bool, iter ItemIterator[T]) (bool, bool) {
482 var ok, found bool
483 var index int
484 switch dir {
485 case ascend:
486 if start.valid {
487 index, _ = n.items.find(start.item, n.cow.less)
488 }
489 for i := index; i < len(n.items); i++ {
490 if len(n.children) > 0 {
491 if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok {
492 return hit, false
493 }
494 }
495 if !includeStart && !hit && start.valid && !n.cow.less(start.item, n.items[i]) {
496 hit = true
497 continue
498 }
499 hit = true
500 if stop.valid && !n.cow.less(n.items[i], stop.item) {
501 return hit, false
502 }
503 if !iter(n.items[i]) {
504 return hit, false
505 }
506 }
507 if len(n.children) > 0 {
508 if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
509 return hit, false
510 }
511 }
512 case descend:
513 if start.valid {
514 index, found = n.items.find(start.item, n.cow.less)
515 if !found {
516 index = index - 1
517 }
518 } else {
519 index = len(n.items) - 1
520 }
521 for i := index; i >= 0; i-- {
522 if start.valid && !n.cow.less(n.items[i], start.item) {
523 if !includeStart || hit || n.cow.less(start.item, n.items[i]) {
524 continue
525 }
526 }
527 if len(n.children) > 0 {
528 if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
529 return hit, false
530 }
531 }
532 if stop.valid && !n.cow.less(stop.item, n.items[i]) {
533 return hit, false // continue
534 }
535 hit = true
536 if !iter(n.items[i]) {
537 return hit, false
538 }
539 }
540 if len(n.children) > 0 {
541 if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok {
542 return hit, false
543 }
544 }
545 }
546 return hit, true
547 }
548
549 // BTree is a generic implementation of a B-Tree.
550 //
551 // BTree stores items of type T in an ordered structure, allowing easy insertion,
552 // removal, and iteration.
553 //
554 // Write operations are not safe for concurrent mutation by multiple
555 // goroutines, but Read operations are.
556 type BTree[T any] struct {
557 degree int
558 length int
559 root *node[T]
560 cow *copyOnWriteContext[T]
561 }
562
563 // LessFunc determines how to order a type 'T'. It should implement a strict
564 // ordering, and should return true if within that ordering, 'a' < 'b'.
565 type LessFunc[T any] func(a, b T) bool
566
567 // copyOnWriteContext pointers determine node ownership... a tree with a write
568 // context equivalent to a node's write context is allowed to modify that node.
569 // A tree whose write context does not match a node's is not allowed to modify
570 // it, and must create a new, writable copy (IE: it's a Clone).
571 //
572 // When doing any write operation, we maintain the invariant that the current
573 // node's context is equal to the context of the tree that requested the write.
574 // We do this by, before we descend into any node, creating a copy with the
575 // correct context if the contexts don't match.
576 //
577 // Since the node we're currently visiting on any write has the requesting
578 // tree's context, that node is modifiable in place. Children of that node may
579 // not share context, but before we descend into them, we'll make a mutable
580 // copy.
581 type copyOnWriteContext[T any] struct {
582 freelist *FreeList[T]
583 less LessFunc[T]
584 }
585
586 // Clone clones the btree, lazily. Clone should not be called concurrently,
587 // but the original tree (t) and the new tree (t2) can be used concurrently
588 // once the Clone call completes.
589 //
590 // The internal tree structure of b is marked read-only and shared between t and
591 // t2. Writes to both t and t2 use copy-on-write logic, creating new nodes
592 // whenever one of b's original nodes would have been modified. Read operations
593 // should have no performance degredation. Write operations for both t and t2
594 // will initially experience minor slow-downs caused by additional allocs and
595 // copies due to the aforementioned copy-on-write logic, but should converge to
596 // the original performance characteristics of the original tree.
597 func (t *BTree[T]) Clone() (t2 *BTree[T]) {
598 // Create two entirely new copy-on-write contexts.
599 // This operation effectively creates three trees:
600 // the original, shared nodes (old b.cow)
601 // the new b.cow nodes
602 // the new out.cow nodes
603 cow1, cow2 := *t.cow, *t.cow
604 out := *t
605 t.cow = &cow1
606 out.cow = &cow2
607 return &out
608 }
609
610 // maxItems returns the max number of items to allow per node.
611 func (t *BTree[T]) maxItems() int {
612 return t.degree*2 - 1
613 }
614
615 // minItems returns the min number of items to allow per node (ignored for the
616 // root node).
617 func (t *BTree[T]) minItems() int {
618 return t.degree - 1
619 }
620
621 func (c *copyOnWriteContext[T]) newNode() (n *node[T]) {
622 n = c.freelist.newNode()
623 n.cow = c
624 return
625 }
626
627 type freeType int
628
629 const (
630 ftFreelistFull freeType = iota // node was freed (available for GC, not stored in freelist)
631 ftStored // node was stored in the freelist for later use
632 ftNotOwned // node was ignored by COW, since it's owned by another one
633 )
634
635 // freeNode frees a node within a given COW context, if it's owned by that
636 // context. It returns what happened to the node (see freeType const
637 // documentation).
638 func (c *copyOnWriteContext[T]) freeNode(n *node[T]) freeType {
639 if n.cow == c {
640 // clear to allow GC
641 n.items.truncate(0)
642 n.children.truncate(0)
643 n.cow = nil
644 if c.freelist.freeNode(n) {
645 return ftStored
646 }
647 return ftFreelistFull
648 }
649 return ftNotOwned
650 }
651
652 // ReplaceOrInsert adds the given item to the tree. If an item in the tree
653 // already equals the given one, it is removed from the tree and returned,
654 // and the second return value is true. Otherwise, (zeroValue, false)
655 //
656 // nil cannot be added to the tree (will panic).
657 func (t *BTree[T]) ReplaceOrInsert(item T) (_ T, _ bool) {
658 if t.root == nil {
659 t.root = t.cow.newNode()
660 t.root.items = append(t.root.items, item)
661 t.length++
662 return
663 }
664 t.root = t.root.mutableFor(t.cow)
665 if len(t.root.items) >= t.maxItems() {
666 item2, second := t.root.split(t.maxItems() / 2)
667 oldroot := t.root
668 t.root = t.cow.newNode()
669 t.root.items = append(t.root.items, item2)
670 t.root.children = append(t.root.children, oldroot, second)
671 }
672 out, outb := t.root.insert(item, t.maxItems())
673 if !outb {
674 t.length++
675 }
676 return out, outb
677 }
678
679 // Delete removes an item equal to the passed in item from the tree, returning
680 // it. If no such item exists, returns (zeroValue, false).
681 func (t *BTree[T]) Delete(item T) (T, bool) {
682 return t.deleteItem(item, removeItem)
683 }
684
685 // DeleteMin removes the smallest item in the tree and returns it.
686 // If no such item exists, returns (zeroValue, false).
687 func (t *BTree[T]) DeleteMin() (T, bool) {
688 var zero T
689 return t.deleteItem(zero, removeMin)
690 }
691
692 // DeleteMax removes the largest item in the tree and returns it.
693 // If no such item exists, returns (zeroValue, false).
694 func (t *BTree[T]) DeleteMax() (T, bool) {
695 var zero T
696 return t.deleteItem(zero, removeMax)
697 }
698
699 func (t *BTree[T]) deleteItem(item T, typ toRemove) (_ T, _ bool) {
700 if t.root == nil || len(t.root.items) == 0 {
701 return
702 }
703 t.root = t.root.mutableFor(t.cow)
704 out, outb := t.root.remove(item, t.minItems(), typ)
705 if len(t.root.items) == 0 && len(t.root.children) > 0 {
706 oldroot := t.root
707 t.root = t.root.children[0]
708 t.cow.freeNode(oldroot)
709 }
710 if outb {
711 t.length--
712 }
713 return out, outb
714 }
715
716 // AscendRange calls the iterator for every value in the tree within the range
717 // [greaterOrEqual, lessThan), until iterator returns false.
718 func (t *BTree[T]) AscendRange(greaterOrEqual, lessThan T, iterator ItemIterator[T]) {
719 if t.root == nil {
720 return
721 }
722 t.root.iterate(ascend, optional[T](greaterOrEqual), optional[T](lessThan), true, false, iterator)
723 }
724
725 // AscendLessThan calls the iterator for every value in the tree within the range
726 // [first, pivot), until iterator returns false.
727 func (t *BTree[T]) AscendLessThan(pivot T, iterator ItemIterator[T]) {
728 if t.root == nil {
729 return
730 }
731 t.root.iterate(ascend, empty[T](), optional(pivot), false, false, iterator)
732 }
733
734 // AscendGreaterOrEqual calls the iterator for every value in the tree within
735 // the range [pivot, last], until iterator returns false.
736 func (t *BTree[T]) AscendGreaterOrEqual(pivot T, iterator ItemIterator[T]) {
737 if t.root == nil {
738 return
739 }
740 t.root.iterate(ascend, optional[T](pivot), empty[T](), true, false, iterator)
741 }
742
743 // Ascend calls the iterator for every value in the tree within the range
744 // [first, last], until iterator returns false.
745 func (t *BTree[T]) Ascend(iterator ItemIterator[T]) {
746 if t.root == nil {
747 return
748 }
749 t.root.iterate(ascend, empty[T](), empty[T](), false, false, iterator)
750 }
751
752 // DescendRange calls the iterator for every value in the tree within the range
753 // [lessOrEqual, greaterThan), until iterator returns false.
754 func (t *BTree[T]) DescendRange(lessOrEqual, greaterThan T, iterator ItemIterator[T]) {
755 if t.root == nil {
756 return
757 }
758 t.root.iterate(descend, optional[T](lessOrEqual), optional[T](greaterThan), true, false, iterator)
759 }
760
761 // DescendLessOrEqual calls the iterator for every value in the tree within the range
762 // [pivot, first], until iterator returns false.
763 func (t *BTree[T]) DescendLessOrEqual(pivot T, iterator ItemIterator[T]) {
764 if t.root == nil {
765 return
766 }
767 t.root.iterate(descend, optional[T](pivot), empty[T](), true, false, iterator)
768 }
769
770 // DescendGreaterThan calls the iterator for every value in the tree within
771 // the range [last, pivot), until iterator returns false.
772 func (t *BTree[T]) DescendGreaterThan(pivot T, iterator ItemIterator[T]) {
773 if t.root == nil {
774 return
775 }
776 t.root.iterate(descend, empty[T](), optional[T](pivot), false, false, iterator)
777 }
778
779 // Descend calls the iterator for every value in the tree within the range
780 // [last, first], until iterator returns false.
781 func (t *BTree[T]) Descend(iterator ItemIterator[T]) {
782 if t.root == nil {
783 return
784 }
785 t.root.iterate(descend, empty[T](), empty[T](), false, false, iterator)
786 }
787
788 // Get looks for the key item in the tree, returning it. It returns
789 // (zeroValue, false) if unable to find that item.
790 func (t *BTree[T]) Get(key T) (_ T, _ bool) {
791 if t.root == nil {
792 return
793 }
794 return t.root.get(key)
795 }
796
797 // Min returns the smallest item in the tree, or (zeroValue, false) if the tree is empty.
798 func (t *BTree[T]) Min() (_ T, _ bool) {
799 return min(t.root)
800 }
801
802 // Max returns the largest item in the tree, or (zeroValue, false) if the tree is empty.
803 func (t *BTree[T]) Max() (_ T, _ bool) {
804 return max(t.root)
805 }
806
807 // Has returns true if the given key is in the tree.
808 func (t *BTree[T]) Has(key T) bool {
809 _, ok := t.Get(key)
810 return ok
811 }
812
813 // Len returns the number of items currently in the tree.
814 func (t *BTree[T]) Len() int {
815 return t.length
816 }
817
818 // Clear removes all items from the btree. If addNodesToFreelist is true,
819 // t's nodes are added to its freelist as part of this call, until the freelist
820 // is full. Otherwise, the root node is simply dereferenced and the subtree
821 // left to Go's normal GC processes.
822 //
823 // This can be much faster
824 // than calling Delete on all elements, because that requires finding/removing
825 // each element in the tree and updating the tree accordingly. It also is
826 // somewhat faster than creating a new tree to replace the old one, because
827 // nodes from the old tree are reclaimed into the freelist for use by the new
828 // one, instead of being lost to the garbage collector.
829 //
830 // This call takes:
831 //
832 // O(1): when addNodesToFreelist is false, this is a single operation.
833 // O(1): when the freelist is already full, it breaks out immediately
834 // O(freelist size): when the freelist is empty and the nodes are all owned
835 // by this tree, nodes are added to the freelist until full.
836 // O(tree size): when all nodes are owned by another tree, all nodes are
837 // iterated over looking for nodes to add to the freelist, and due to
838 // ownership, none are.
839 func (t *BTree[T]) Clear(addNodesToFreelist bool) {
840 if t.root != nil && addNodesToFreelist {
841 t.root.reset(t.cow)
842 }
843 t.root, t.length = nil, 0
844 }
845
846 // reset returns a subtree to the freelist. It breaks out immediately if the
847 // freelist is full, since the only benefit of iterating is to fill that
848 // freelist up. Returns true if parent reset call should continue.
849 func (n *node[T]) reset(c *copyOnWriteContext[T]) bool {
850 for _, child := range n.children {
851 if !child.reset(c) {
852 return false
853 }
854 }
855 return c.freeNode(n) != ftFreelistFull
856 }