btree.go 21 KB

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