Debian Codegraph @

vendor/github.com/google/btree/btree.go

raw
1 // Copyright 2014 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package btree implements in-memory B-Trees of arbitrary degree.
16 //
17 // btree implements an in-memory B-Tree for use as an ordered data structure.
18 // It is not meant for persistent storage solutions.
19 //
20 // It has a flatter structure than an equivalent red-black or other binary tree,
21 // which in some cases yields better memory usage and/or performance.
22 // See some discussion on the matter here:
23 // http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
24 // Note, though, that this project is in no way related to the C++ B-Tree
25 // implementation written about there.
26 //
27 // Within this tree, each node contains a slice of items and a (possibly nil)
28 // slice of children. For basic numeric values or raw structs, this can cause
29 // efficiency differences when compared to equivalent C++ template code that
30 // stores values in arrays within the node:
31 // * Due to the overhead of storing values as interfaces (each
32 // value needs to be stored as the value itself, then 2 words for the
33 // interface pointing to that value and its type), resulting in higher
34 // memory use.
35 // * Since interfaces can point to values anywhere in memory, values are
36 // most likely not stored in contiguous blocks, resulting in a higher
37 // number of cache misses.
38 // These issues don't tend to matter, though, when working with strings or other
39 // heap-allocated structures, since C++-equivalent structures also must store
40 // pointers and also distribute their values across the heap.
41 //
42 // This implementation is designed to be a drop-in replacement to gollrb.LLRB
43 // trees, (http://github.com/petar/gollrb), an excellent and probably the most
44 // widely used ordered tree implementation in the Go ecosystem currently.
45 // Its functions, therefore, exactly mirror those of
46 // llrb.LLRB where possible. Unlike gollrb, though, we currently don't
47 // support storing multiple equivalent values.
48 package btree
49
50 import (
51 "fmt"
52 "io"
53 "sort"
54 "strings"
55 )
56
57 // Item represents a single object in the tree.
58 type Item interface {
59 // Less tests whether the current item is less than the given argument.
60 //
61 // This must provide a strict weak ordering.
62 // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only
63 // hold one of either a or b in the tree).
64 Less(than Item) bool
65 }
66
67 const (
68 DefaultFreeListSize = 32
69 )
70
71 var (
72 nilItems = make(items, 16)
73 nilChildren = make(children, 16)
74 )
75
76 // FreeList represents a free list of btree nodes. By default each
77 // BTree has its own FreeList, but multiple BTrees can share the same
78 // FreeList.
79 // Two Btrees using the same freelist are not safe for concurrent write access.
80 type FreeList struct {
81 freelist []*node
82 }
83
84 // NewFreeList creates a new free list.
85 // size is the maximum size of the returned free list.
86 func NewFreeList(size int) *FreeList {
87 return &FreeList{freelist: make([]*node, 0, size)}
88 }
89
90 func (f *FreeList) newNode() (n *node) {
91 index := len(f.freelist) - 1
92 if index < 0 {
93 return new(node)
94 }
95 n = f.freelist[index]
96 f.freelist[index] = nil
97 f.freelist = f.freelist[:index]
98 return
99 }
100
101 func (f *FreeList) freeNode(n *node) {
102 if len(f.freelist) < cap(f.freelist) {
103 f.freelist = append(f.freelist, n)
104 }
105 }
106
107 // ItemIterator allows callers of Ascend* to iterate in-order over portions of
108 // the tree. When this function returns false, iteration will stop and the
109 // associated Ascend* function will immediately return.
110 type ItemIterator func(i Item) bool
111
112 // New creates a new B-Tree with the given degree.
113 //
114 // New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items
115 // and 2-4 children).
116 func New(degree int) *BTree {
117 return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize))
118 }
119
120 // NewWithFreeList creates a new B-Tree that uses the given node free list.
121 func NewWithFreeList(degree int, f *FreeList) *BTree {
122 if degree <= 1 {
123 panic("bad degree")
124 }
125 return &BTree{
126 degree: degree,
127 freelist: f,
128 }
129 }
130
131 // items stores items in a node.
132 type items []Item
133
134 // insertAt inserts a value into the given index, pushing all subsequent values
135 // forward.
136 func (s *items) insertAt(index int, item Item) {
137 *s = append(*s, nil)
138 if index < len(*s) {
139 copy((*s)[index+1:], (*s)[index:])
140 }
141 (*s)[index] = item
142 }
143
144 // removeAt removes a value at a given index, pulling all subsequent values
145 // back.
146 func (s *items) removeAt(index int) Item {
147 item := (*s)[index]
148 copy((*s)[index:], (*s)[index+1:])
149 (*s)[len(*s)-1] = nil
150 *s = (*s)[:len(*s)-1]
151 return item
152 }
153
154 // pop removes and returns the last element in the list.
155 func (s *items) pop() (out Item) {
156 index := len(*s) - 1
157 out = (*s)[index]
158 (*s)[index] = nil
159 *s = (*s)[:index]
160 return
161 }
162
163 // truncate truncates this instance at index so that it contains only the
164 // first index items. index must be less than or equal to length.
165 func (s *items) truncate(index int) {
166 var toClear items
167 *s, toClear = (*s)[:index], (*s)[index:]
168 for len(toClear) > 0 {
169 toClear = toClear[copy(toClear, nilItems):]
170 }
171 }
172
173 // find returns the index where the given item should be inserted into this
174 // list. 'found' is true if the item already exists in the list at the given
175 // index.
176 func (s items) find(item Item) (index int, found bool) {
177 i := sort.Search(len(s), func(i int) bool {
178 return item.Less(s[i])
179 })
180 if i > 0 && !s[i-1].Less(item) {
181 return i - 1, true
182 }
183 return i, false
184 }
185
186 // children stores child nodes in a node.
187 type children []*node
188
189 // insertAt inserts a value into the given index, pushing all subsequent values
190 // forward.
191 func (s *children) insertAt(index int, n *node) {
192 *s = append(*s, nil)
193 if index < len(*s) {
194 copy((*s)[index+1:], (*s)[index:])
195 }
196 (*s)[index] = n
197 }
198
199 // removeAt removes a value at a given index, pulling all subsequent values
200 // back.
201 func (s *children) removeAt(index int) *node {
202 n := (*s)[index]
203 copy((*s)[index:], (*s)[index+1:])
204 (*s)[len(*s)-1] = nil
205 *s = (*s)[:len(*s)-1]
206 return n
207 }
208
209 // pop removes and returns the last element in the list.
210 func (s *children) pop() (out *node) {
211 index := len(*s) - 1
212 out = (*s)[index]
213 (*s)[index] = nil
214 *s = (*s)[:index]
215 return
216 }
217
218 // truncate truncates this instance at index so that it contains only the
219 // first index children. index must be less than or equal to length.
220 func (s *children) truncate(index int) {
221 var toClear children
222 *s, toClear = (*s)[:index], (*s)[index:]
223 for len(toClear) > 0 {
224 toClear = toClear[copy(toClear, nilChildren):]
225 }
226 }
227
228 // node is an internal node in a tree.
229 //
230 // It must at all times maintain the invariant that either
231 // * len(children) == 0, len(items) unconstrained
232 // * len(children) == len(items) + 1
233 type node struct {
234 items items
235 children children
236 t *BTree
237 }
238
239 // split splits the given node at the given index. The current node shrinks,
240 // and this function returns the item that existed at that index and a new node
241 // containing all items/children after it.
242 func (n *node) split(i int) (Item, *node) {
243 item := n.items[i]
244 next := n.t.newNode()
245 next.items = append(next.items, n.items[i+1:]...)
246 n.items.truncate(i)
247 if len(n.children) > 0 {
248 next.children = append(next.children, n.children[i+1:]...)
249 n.children.truncate(i + 1)
250 }
251 return item, next
252 }
253
254 // maybeSplitChild checks if a child should be split, and if so splits it.
255 // Returns whether or not a split occurred.
256 func (n *node) maybeSplitChild(i, maxItems int) bool {
257 if len(n.children[i].items) < maxItems {
258 return false
259 }
260 first := n.children[i]
261 item, second := first.split(maxItems / 2)
262 n.items.insertAt(i, item)
263 n.children.insertAt(i+1, second)
264 return true
265 }
266
267 // insert inserts an item into the subtree rooted at this node, making sure
268 // no nodes in the subtree exceed maxItems items. Should an equivalent item be
269 // be found/replaced by insert, it will be returned.
270 func (n *node) insert(item Item, maxItems int) Item {
271 i, found := n.items.find(item)
272 if found {
273 out := n.items[i]
274 n.items[i] = item
275 return out
276 }
277 if len(n.children) == 0 {
278 n.items.insertAt(i, item)
279 return nil
280 }
281 if n.maybeSplitChild(i, maxItems) {
282 inTree := n.items[i]
283 switch {
284 case item.Less(inTree):
285 // no change, we want first split node
286 case inTree.Less(item):
287 i++ // we want second split node
288 default:
289 out := n.items[i]
290 n.items[i] = item
291 return out
292 }
293 }
294 return n.children[i].insert(item, maxItems)
295 }
296
297 // get finds the given key in the subtree and returns it.
298 func (n *node) get(key Item) Item {
299 i, found := n.items.find(key)
300 if found {
301 return n.items[i]
302 } else if len(n.children) > 0 {
303 return n.children[i].get(key)
304 }
305 return nil
306 }
307
308 // min returns the first item in the subtree.
309 func min(n *node) Item {
310 if n == nil {
311 return nil
312 }
313 for len(n.children) > 0 {
314 n = n.children[0]
315 }
316 if len(n.items) == 0 {
317 return nil
318 }
319 return n.items[0]
320 }
321
322 // max returns the last item in the subtree.
323 func max(n *node) Item {
324 if n == nil {
325 return nil
326 }
327 for len(n.children) > 0 {
328 n = n.children[len(n.children)-1]
329 }
330 if len(n.items) == 0 {
331 return nil
332 }
333 return n.items[len(n.items)-1]
334 }
335
336 // toRemove details what item to remove in a node.remove call.
337 type toRemove int
338
339 const (
340 removeItem toRemove = iota // removes the given item
341 removeMin // removes smallest item in the subtree
342 removeMax // removes largest item in the subtree
343 )
344
345 // remove removes an item from the subtree rooted at this node.
346 func (n *node) remove(item Item, minItems int, typ toRemove) Item {
347 var i int
348 var found bool
349 switch typ {
350 case removeMax:
351 if len(n.children) == 0 {
352 return n.items.pop()
353 }
354 i = len(n.items)
355 case removeMin:
356 if len(n.children) == 0 {
357 return n.items.removeAt(0)
358 }
359 i = 0
360 case removeItem:
361 i, found = n.items.find(item)
362 if len(n.children) == 0 {
363 if found {
364 return n.items.removeAt(i)
365 }
366 return nil
367 }
368 default:
369 panic("invalid type")
370 }
371 // If we get to here, we have children.
372 child := n.children[i]
373 if len(child.items) <= minItems {
374 return n.growChildAndRemove(i, item, minItems, typ)
375 }
376 // Either we had enough items to begin with, or we've done some
377 // merging/stealing, because we've got enough now and we're ready to return
378 // stuff.
379 if found {
380 // The item exists at index 'i', and the child we've selected can give us a
381 // predecessor, since if we've gotten here it's got > minItems items in it.
382 out := n.items[i]
383 // We use our special-case 'remove' call with typ=maxItem to pull the
384 // predecessor of item i (the rightmost leaf of our immediate left child)
385 // and set it into where we pulled the item from.
386 n.items[i] = child.remove(nil, minItems, removeMax)
387 return out
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 // In both cases, we need to handle the two subcases:
402 // A) node has enough values that it can spare one
403 // B) node doesn't have enough values
404 // For the latter, we have to check:
405 // a) left sibling has node to spare
406 // b) right sibling has node to spare
407 // c) we must merge
408 // To simplify our code here, we handle cases #1 and #2 the same:
409 // If a node doesn't have enough items, we make sure it does (using a,b,c).
410 // We then simply redo our remove call, and the second time (regardless of
411 // whether we're in case 1 or 2), we'll have enough items and can guarantee
412 // that we hit case A.
413 func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item {
414 child := n.children[i]
415 if i > 0 && len(n.children[i-1].items) > minItems {
416 // Steal from left child
417 stealFrom := n.children[i-1]
418 stolenItem := stealFrom.items.pop()
419 child.items.insertAt(0, n.items[i-1])
420 n.items[i-1] = stolenItem
421 if len(stealFrom.children) > 0 {
422 child.children.insertAt(0, stealFrom.children.pop())
423 }
424 } else if i < len(n.items) && len(n.children[i+1].items) > minItems {
425 // steal from right child
426 stealFrom := n.children[i+1]
427 stolenItem := stealFrom.items.removeAt(0)
428 child.items = append(child.items, n.items[i])
429 n.items[i] = stolenItem
430 if len(stealFrom.children) > 0 {
431 child.children = append(child.children, stealFrom.children.removeAt(0))
432 }
433 } else {
434 if i >= len(n.items) {
435 i--
436 child = n.children[i]
437 }
438 // merge with right child
439 mergeItem := n.items.removeAt(i)
440 mergeChild := n.children.removeAt(i + 1)
441 child.items = append(child.items, mergeItem)
442 child.items = append(child.items, mergeChild.items...)
443 child.children = append(child.children, mergeChild.children...)
444 n.t.freeNode(mergeChild)
445 }
446 return n.remove(item, minItems, typ)
447 }
448
449 type direction int
450
451 const (
452 descend = direction(-1)
453 ascend = direction(+1)
454 )
455
456 // iterate provides a simple method for iterating over elements in the tree.
457 //
458 // When ascending, the 'start' should be less than 'stop' and when descending,
459 // the 'start' should be greater than 'stop'. Setting 'includeStart' to true
460 // will force the iterator to include the first item when it equals 'start',
461 // thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a
462 // "greaterThan" or "lessThan" queries.
463 func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) {
464 var ok bool
465 switch dir {
466 case ascend:
467 for i := 0; i < len(n.items); i++ {
468 if start != nil && n.items[i].Less(start) {
469 continue
470 }
471 if len(n.children) > 0 {
472 if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok {
473 return hit, false
474 }
475 }
476 if !includeStart && !hit && start != nil && !start.Less(n.items[i]) {
477 hit = true
478 continue
479 }
480 hit = true
481 if stop != nil && !n.items[i].Less(stop) {
482 return hit, false
483 }
484 if !iter(n.items[i]) {
485 return hit, false
486 }
487 }
488 if len(n.children) > 0 {
489 if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
490 return hit, false
491 }
492 }
493 case descend:
494 for i := len(n.items) - 1; i >= 0; i-- {
495 if start != nil && !n.items[i].Less(start) {
496 if !includeStart || hit || start.Less(n.items[i]) {
497 continue
498 }
499 }
500 if len(n.children) > 0 {
501 if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
502 return hit, false
503 }
504 }
505 if stop != nil && !stop.Less(n.items[i]) {
506 return hit, false // continue
507 }
508 hit = true
509 if !iter(n.items[i]) {
510 return hit, false
511 }
512 }
513 if len(n.children) > 0 {
514 if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok {
515 return hit, false
516 }
517 }
518 }
519 return hit, true
520 }
521
522 // Used for testing/debugging purposes.
523 func (n *node) print(w io.Writer, level int) {
524 fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items)
525 for _, c := range n.children {
526 c.print(w, level+1)
527 }
528 }
529
530 // BTree is an implementation of a B-Tree.
531 //
532 // BTree stores Item instances in an ordered structure, allowing easy insertion,
533 // removal, and iteration.
534 //
535 // Write operations are not safe for concurrent mutation by multiple
536 // goroutines, but Read operations are.
537 type BTree struct {
538 degree int
539 length int
540 root *node
541 freelist *FreeList
542 }
543
544 // maxItems returns the max number of items to allow per node.
545 func (t *BTree) maxItems() int {
546 return t.degree*2 - 1
547 }
548
549 // minItems returns the min number of items to allow per node (ignored for the
550 // root node).
551 func (t *BTree) minItems() int {
552 return t.degree - 1
553 }
554
555 func (t *BTree) newNode() (n *node) {
556 n = t.freelist.newNode()
557 n.t = t
558 return
559 }
560
561 func (t *BTree) freeNode(n *node) {
562 // clear to allow GC
563 n.items.truncate(0)
564 n.children.truncate(0)
565 n.t = nil // clear to allow GC
566 t.freelist.freeNode(n)
567 }
568
569 // ReplaceOrInsert adds the given item to the tree. If an item in the tree
570 // already equals the given one, it is removed from the tree and returned.
571 // Otherwise, nil is returned.
572 //
573 // nil cannot be added to the tree (will panic).
574 func (t *BTree) ReplaceOrInsert(item Item) Item {
575 if item == nil {
576 panic("nil item being added to BTree")
577 }
578 if t.root == nil {
579 t.root = t.newNode()
580 t.root.items = append(t.root.items, item)
581 t.length++
582 return nil
583 } else if len(t.root.items) >= t.maxItems() {
584 item2, second := t.root.split(t.maxItems() / 2)
585 oldroot := t.root
586 t.root = t.newNode()
587 t.root.items = append(t.root.items, item2)
588 t.root.children = append(t.root.children, oldroot, second)
589 }
590 out := t.root.insert(item, t.maxItems())
591 if out == nil {
592 t.length++
593 }
594 return out
595 }
596
597 // Delete removes an item equal to the passed in item from the tree, returning
598 // it. If no such item exists, returns nil.
599 func (t *BTree) Delete(item Item) Item {
600 return t.deleteItem(item, removeItem)
601 }
602
603 // DeleteMin removes the smallest item in the tree and returns it.
604 // If no such item exists, returns nil.
605 func (t *BTree) DeleteMin() Item {
606 return t.deleteItem(nil, removeMin)
607 }
608
609 // DeleteMax removes the largest item in the tree and returns it.
610 // If no such item exists, returns nil.
611 func (t *BTree) DeleteMax() Item {
612 return t.deleteItem(nil, removeMax)
613 }
614
615 func (t *BTree) deleteItem(item Item, typ toRemove) Item {
616 if t.root == nil || len(t.root.items) == 0 {
617 return nil
618 }
619 out := t.root.remove(item, t.minItems(), typ)
620 if len(t.root.items) == 0 && len(t.root.children) > 0 {
621 oldroot := t.root
622 t.root = t.root.children[0]
623 t.freeNode(oldroot)
624 }
625 if out != nil {
626 t.length--
627 }
628 return out
629 }
630
631 // AscendRange calls the iterator for every value in the tree within the range
632 // [greaterOrEqual, lessThan), until iterator returns false.
633 func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
634 if t.root == nil {
635 return
636 }
637 t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator)
638 }
639
640 // AscendLessThan calls the iterator for every value in the tree within the range
641 // [first, pivot), until iterator returns false.
642 func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) {
643 if t.root == nil {
644 return
645 }
646 t.root.iterate(ascend, nil, pivot, false, false, iterator)
647 }
648
649 // AscendGreaterOrEqual calls the iterator for every value in the tree within
650 // the range [pivot, last], until iterator returns false.
651 func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
652 if t.root == nil {
653 return
654 }
655 t.root.iterate(ascend, pivot, nil, true, false, iterator)
656 }
657
658 // Ascend calls the iterator for every value in the tree within the range
659 // [first, last], until iterator returns false.
660 func (t *BTree) Ascend(iterator ItemIterator) {
661 if t.root == nil {
662 return
663 }
664 t.root.iterate(ascend, nil, nil, false, false, iterator)
665 }
666
667 // DescendRange calls the iterator for every value in the tree within the range
668 // [lessOrEqual, greaterThan), until iterator returns false.
669 func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) {
670 if t.root == nil {
671 return
672 }
673 t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator)
674 }
675
676 // DescendLessOrEqual calls the iterator for every value in the tree within the range
677 // [pivot, first], until iterator returns false.
678 func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
679 if t.root == nil {
680 return
681 }
682 t.root.iterate(descend, pivot, nil, true, false, iterator)
683 }
684
685 // DescendGreaterThan calls the iterator for every value in the tree within
686 // the range (pivot, last], until iterator returns false.
687 func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) {
688 if t.root == nil {
689 return
690 }
691 t.root.iterate(descend, nil, pivot, false, false, iterator)
692 }
693
694 // Descend calls the iterator for every value in the tree within the range
695 // [last, first], until iterator returns false.
696 func (t *BTree) Descend(iterator ItemIterator) {
697 if t.root == nil {
698 return
699 }
700 t.root.iterate(descend, nil, nil, false, false, iterator)
701 }
702
703 // Get looks for the key item in the tree, returning it. It returns nil if
704 // unable to find that item.
705 func (t *BTree) Get(key Item) Item {
706 if t.root == nil {
707 return nil
708 }
709 return t.root.get(key)
710 }
711
712 // Min returns the smallest item in the tree, or nil if the tree is empty.
713 func (t *BTree) Min() Item {
714 return min(t.root)
715 }
716
717 // Max returns the largest item in the tree, or nil if the tree is empty.
718 func (t *BTree) Max() Item {
719 return max(t.root)
720 }
721
722 // Has returns true if the given key is in the tree.
723 func (t *BTree) Has(key Item) bool {
724 return t.Get(key) != nil
725 }
726
727 // Len returns the number of items currently in the tree.
728 func (t *BTree) Len() int {
729 return t.length
730 }
731
732 // Int implements the Item interface for integers.
733 type Int int
734
735 // Less returns true if int(a) < int(b).
736 func (a Int) Less(b Item) bool {
737 return a < b.(Int)
738 }