github.com/gogf/gf@v1.16.9/container/gtree/gtree_btree.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gtree 8 9 import ( 10 "bytes" 11 "fmt" 12 "github.com/gogf/gf/internal/json" 13 "strings" 14 15 "github.com/gogf/gf/util/gconv" 16 17 "github.com/gogf/gf/container/gvar" 18 "github.com/gogf/gf/internal/rwmutex" 19 ) 20 21 // BTree holds elements of the B-tree. 22 type BTree struct { 23 mu rwmutex.RWMutex 24 root *BTreeNode 25 comparator func(v1, v2 interface{}) int 26 size int // Total number of keys in the tree 27 m int // order (maximum number of children) 28 } 29 30 // BTreeNode is a single element within the tree. 31 type BTreeNode struct { 32 Parent *BTreeNode 33 Entries []*BTreeEntry // Contained keys in node 34 Children []*BTreeNode // Children nodes 35 } 36 37 // BTreeEntry represents the key-value pair contained within nodes. 38 type BTreeEntry struct { 39 Key interface{} 40 Value interface{} 41 } 42 43 // NewBTree instantiates a B-tree with <m> (maximum number of children) and a custom key comparator. 44 // The parameter <safe> is used to specify whether using tree in concurrent-safety, 45 // which is false in default. 46 // Note that the <m> must be greater or equal than 3, or else it panics. 47 func NewBTree(m int, comparator func(v1, v2 interface{}) int, safe ...bool) *BTree { 48 if m < 3 { 49 panic("Invalid order, should be at least 3") 50 } 51 return &BTree{ 52 comparator: comparator, 53 mu: rwmutex.Create(safe...), 54 m: m, 55 } 56 } 57 58 // NewBTreeFrom instantiates a B-tree with <m> (maximum number of children), a custom key comparator and data map. 59 // The parameter <safe> is used to specify whether using tree in concurrent-safety, 60 // which is false in default. 61 func NewBTreeFrom(m int, comparator func(v1, v2 interface{}) int, data map[interface{}]interface{}, safe ...bool) *BTree { 62 tree := NewBTree(m, comparator, safe...) 63 for k, v := range data { 64 tree.doSet(k, v) 65 } 66 return tree 67 } 68 69 // Clone returns a new tree with a copy of current tree. 70 func (tree *BTree) Clone() *BTree { 71 newTree := NewBTree(tree.m, tree.comparator, tree.mu.IsSafe()) 72 newTree.Sets(tree.Map()) 73 return newTree 74 } 75 76 // Set inserts key-value item into the tree. 77 func (tree *BTree) Set(key interface{}, value interface{}) { 78 tree.mu.Lock() 79 defer tree.mu.Unlock() 80 tree.doSet(key, value) 81 } 82 83 // doSet inserts key-value pair node into the tree. 84 // If key already exists, then its value is updated with the new value. 85 func (tree *BTree) doSet(key interface{}, value interface{}) { 86 entry := &BTreeEntry{Key: key, Value: value} 87 if tree.root == nil { 88 tree.root = &BTreeNode{Entries: []*BTreeEntry{entry}, Children: []*BTreeNode{}} 89 tree.size++ 90 return 91 } 92 93 if tree.insert(tree.root, entry) { 94 tree.size++ 95 } 96 } 97 98 // Sets batch sets key-values to the tree. 99 func (tree *BTree) Sets(data map[interface{}]interface{}) { 100 tree.mu.Lock() 101 defer tree.mu.Unlock() 102 for k, v := range data { 103 tree.doSet(k, v) 104 } 105 } 106 107 // Get searches the node in the tree by <key> and returns its value or nil if key is not found in tree. 108 func (tree *BTree) Get(key interface{}) (value interface{}) { 109 value, _ = tree.Search(key) 110 return 111 } 112 113 // doSetWithLockCheck checks whether value of the key exists with mutex.Lock, 114 // if not exists, set value to the map with given <key>, 115 // or else just return the existing value. 116 // 117 // When setting value, if <value> is type of <func() interface {}>, 118 // it will be executed with mutex.Lock of the hash map, 119 // and its return value will be set to the map with <key>. 120 // 121 // It returns value with given <key>. 122 func (tree *BTree) doSetWithLockCheck(key interface{}, value interface{}) interface{} { 123 tree.mu.Lock() 124 defer tree.mu.Unlock() 125 if entry := tree.doSearch(key); entry != nil { 126 return entry.Value 127 } 128 if f, ok := value.(func() interface{}); ok { 129 value = f() 130 } 131 if value != nil { 132 tree.doSet(key, value) 133 } 134 return value 135 } 136 137 // GetOrSet returns the value by key, 138 // or sets value with given <value> if it does not exist and then returns this value. 139 func (tree *BTree) GetOrSet(key interface{}, value interface{}) interface{} { 140 if v, ok := tree.Search(key); !ok { 141 return tree.doSetWithLockCheck(key, value) 142 } else { 143 return v 144 } 145 } 146 147 // GetOrSetFunc returns the value by key, 148 // or sets value with returned value of callback function <f> if it does not exist 149 // and then returns this value. 150 func (tree *BTree) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { 151 if v, ok := tree.Search(key); !ok { 152 return tree.doSetWithLockCheck(key, f()) 153 } else { 154 return v 155 } 156 } 157 158 // GetOrSetFuncLock returns the value by key, 159 // or sets value with returned value of callback function <f> if it does not exist 160 // and then returns this value. 161 // 162 // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f> 163 // with mutex.Lock of the hash map. 164 func (tree *BTree) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { 165 if v, ok := tree.Search(key); !ok { 166 return tree.doSetWithLockCheck(key, f) 167 } else { 168 return v 169 } 170 } 171 172 // GetVar returns a gvar.Var with the value by given <key>. 173 // The returned gvar.Var is un-concurrent safe. 174 func (tree *BTree) GetVar(key interface{}) *gvar.Var { 175 return gvar.New(tree.Get(key)) 176 } 177 178 // GetVarOrSet returns a gvar.Var with result from GetVarOrSet. 179 // The returned gvar.Var is un-concurrent safe. 180 func (tree *BTree) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { 181 return gvar.New(tree.GetOrSet(key, value)) 182 } 183 184 // GetVarOrSetFunc returns a gvar.Var with result from GetOrSetFunc. 185 // The returned gvar.Var is un-concurrent safe. 186 func (tree *BTree) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { 187 return gvar.New(tree.GetOrSetFunc(key, f)) 188 } 189 190 // GetVarOrSetFuncLock returns a gvar.Var with result from GetOrSetFuncLock. 191 // The returned gvar.Var is un-concurrent safe. 192 func (tree *BTree) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { 193 return gvar.New(tree.GetOrSetFuncLock(key, f)) 194 } 195 196 // SetIfNotExist sets <value> to the map if the <key> does not exist, and then returns true. 197 // It returns false if <key> exists, and <value> would be ignored. 198 func (tree *BTree) SetIfNotExist(key interface{}, value interface{}) bool { 199 if !tree.Contains(key) { 200 tree.doSetWithLockCheck(key, value) 201 return true 202 } 203 return false 204 } 205 206 // SetIfNotExistFunc sets value with return value of callback function <f>, and then returns true. 207 // It returns false if <key> exists, and <value> would be ignored. 208 func (tree *BTree) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { 209 if !tree.Contains(key) { 210 tree.doSetWithLockCheck(key, f()) 211 return true 212 } 213 return false 214 } 215 216 // SetIfNotExistFuncLock sets value with return value of callback function <f>, and then returns true. 217 // It returns false if <key> exists, and <value> would be ignored. 218 // 219 // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that 220 // it executes function <f> with mutex.Lock of the hash map. 221 func (tree *BTree) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { 222 if !tree.Contains(key) { 223 tree.doSetWithLockCheck(key, f) 224 return true 225 } 226 return false 227 } 228 229 // Contains checks whether <key> exists in the tree. 230 func (tree *BTree) Contains(key interface{}) bool { 231 _, ok := tree.Search(key) 232 return ok 233 } 234 235 // Remove remove the node from the tree by key. 236 // Key should adhere to the comparator's type assertion, otherwise method panics. 237 func (tree *BTree) doRemove(key interface{}) (value interface{}) { 238 node, index, found := tree.searchRecursively(tree.root, key) 239 if found { 240 value = node.Entries[index].Value 241 tree.delete(node, index) 242 tree.size-- 243 } 244 return 245 } 246 247 // Remove removes the node from the tree by <key>. 248 func (tree *BTree) Remove(key interface{}) (value interface{}) { 249 tree.mu.Lock() 250 defer tree.mu.Unlock() 251 return tree.doRemove(key) 252 } 253 254 // Removes batch deletes values of the tree by <keys>. 255 func (tree *BTree) Removes(keys []interface{}) { 256 tree.mu.Lock() 257 defer tree.mu.Unlock() 258 for _, key := range keys { 259 tree.doRemove(key) 260 } 261 } 262 263 // Empty returns true if tree does not contain any nodes 264 func (tree *BTree) IsEmpty() bool { 265 return tree.Size() == 0 266 } 267 268 // Size returns number of nodes in the tree. 269 func (tree *BTree) Size() int { 270 tree.mu.RLock() 271 defer tree.mu.RUnlock() 272 return tree.size 273 } 274 275 // Keys returns all keys in asc order. 276 func (tree *BTree) Keys() []interface{} { 277 keys := make([]interface{}, tree.Size()) 278 index := 0 279 tree.IteratorAsc(func(key, value interface{}) bool { 280 keys[index] = key 281 index++ 282 return true 283 }) 284 return keys 285 } 286 287 // Values returns all values in asc order based on the key. 288 func (tree *BTree) Values() []interface{} { 289 values := make([]interface{}, tree.Size()) 290 index := 0 291 tree.IteratorAsc(func(key, value interface{}) bool { 292 values[index] = value 293 index++ 294 return true 295 }) 296 return values 297 } 298 299 // Map returns all key-value items as map. 300 func (tree *BTree) Map() map[interface{}]interface{} { 301 m := make(map[interface{}]interface{}, tree.Size()) 302 tree.IteratorAsc(func(key, value interface{}) bool { 303 m[key] = value 304 return true 305 }) 306 return m 307 } 308 309 // MapStrAny returns all key-value items as map[string]interface{}. 310 func (tree *BTree) MapStrAny() map[string]interface{} { 311 m := make(map[string]interface{}, tree.Size()) 312 tree.IteratorAsc(func(key, value interface{}) bool { 313 m[gconv.String(key)] = value 314 return true 315 }) 316 return m 317 } 318 319 // Clear removes all nodes from the tree. 320 func (tree *BTree) Clear() { 321 tree.mu.Lock() 322 defer tree.mu.Unlock() 323 tree.root = nil 324 tree.size = 0 325 } 326 327 // Replace the data of the tree with given <data>. 328 func (tree *BTree) Replace(data map[interface{}]interface{}) { 329 tree.mu.Lock() 330 defer tree.mu.Unlock() 331 tree.root = nil 332 tree.size = 0 333 for k, v := range data { 334 tree.doSet(k, v) 335 } 336 } 337 338 // Height returns the height of the tree. 339 func (tree *BTree) Height() int { 340 tree.mu.RLock() 341 defer tree.mu.RUnlock() 342 return tree.root.height() 343 } 344 345 // Left returns the left-most (min) entry or nil if tree is empty. 346 func (tree *BTree) Left() *BTreeEntry { 347 tree.mu.RLock() 348 defer tree.mu.RUnlock() 349 node := tree.left(tree.root) 350 return node.Entries[0] 351 } 352 353 // Right returns the right-most (max) entry or nil if tree is empty. 354 func (tree *BTree) Right() *BTreeEntry { 355 tree.mu.RLock() 356 defer tree.mu.RUnlock() 357 node := tree.right(tree.root) 358 return node.Entries[len(node.Entries)-1] 359 } 360 361 // String returns a string representation of container (for debugging purposes) 362 func (tree *BTree) String() string { 363 tree.mu.RLock() 364 defer tree.mu.RUnlock() 365 var buffer bytes.Buffer 366 if tree.size != 0 { 367 tree.output(&buffer, tree.root, 0, true) 368 } 369 return buffer.String() 370 } 371 372 // Search searches the tree with given <key>. 373 // Second return parameter <found> is true if key was found, otherwise false. 374 func (tree *BTree) Search(key interface{}) (value interface{}, found bool) { 375 tree.mu.RLock() 376 defer tree.mu.RUnlock() 377 node, index, found := tree.searchRecursively(tree.root, key) 378 if found { 379 return node.Entries[index].Value, true 380 } 381 return nil, false 382 } 383 384 // Search searches the tree with given <key> without mutex. 385 // It returns the entry if found or otherwise nil. 386 func (tree *BTree) doSearch(key interface{}) *BTreeEntry { 387 node, index, found := tree.searchRecursively(tree.root, key) 388 if found { 389 return node.Entries[index] 390 } 391 return nil 392 } 393 394 // Print prints the tree to stdout. 395 func (tree *BTree) Print() { 396 fmt.Println(tree.String()) 397 } 398 399 // Iterator is alias of IteratorAsc. 400 func (tree *BTree) Iterator(f func(key, value interface{}) bool) { 401 tree.IteratorAsc(f) 402 } 403 404 // IteratorFrom is alias of IteratorAscFrom. 405 func (tree *BTree) IteratorFrom(key interface{}, match bool, f func(key, value interface{}) bool) { 406 tree.IteratorAscFrom(key, match, f) 407 } 408 409 // IteratorAsc iterates the tree readonly in ascending order with given callback function <f>. 410 // If <f> returns true, then it continues iterating; or false to stop. 411 func (tree *BTree) IteratorAsc(f func(key, value interface{}) bool) { 412 tree.mu.RLock() 413 defer tree.mu.RUnlock() 414 node := tree.left(tree.root) 415 if node == nil { 416 return 417 } 418 tree.doIteratorAsc(node, node.Entries[0], 0, f) 419 } 420 421 // IteratorAscFrom iterates the tree readonly in ascending order with given callback function <f>. 422 // The parameter <key> specifies the start entry for iterating. The <match> specifies whether 423 // starting iterating if the <key> is fully matched, or else using index searching iterating. 424 // If <f> returns true, then it continues iterating; or false to stop. 425 func (tree *BTree) IteratorAscFrom(key interface{}, match bool, f func(key, value interface{}) bool) { 426 tree.mu.RLock() 427 defer tree.mu.RUnlock() 428 node, index, found := tree.searchRecursively(tree.root, key) 429 if match { 430 if found { 431 tree.doIteratorAsc(node, node.Entries[index], index, f) 432 } 433 } else { 434 tree.doIteratorAsc(node, node.Entries[index], index, f) 435 } 436 } 437 438 func (tree *BTree) doIteratorAsc(node *BTreeNode, entry *BTreeEntry, index int, f func(key, value interface{}) bool) { 439 first := true 440 loop: 441 if entry == nil { 442 return 443 } 444 if !f(entry.Key, entry.Value) { 445 return 446 } 447 // Find current entry position in current node 448 if !first { 449 index, _ = tree.search(node, entry.Key) 450 } else { 451 first = false 452 } 453 // Try to go down to the child right of the current entry 454 if index+1 < len(node.Children) { 455 node = node.Children[index+1] 456 // Try to go down to the child left of the current node 457 for len(node.Children) > 0 { 458 node = node.Children[0] 459 } 460 // Return the left-most entry 461 entry = node.Entries[0] 462 goto loop 463 } 464 // Above assures that we have reached a leaf node, so return the next entry in current node (if any) 465 if index+1 < len(node.Entries) { 466 entry = node.Entries[index+1] 467 goto loop 468 } 469 // Reached leaf node and there are no entries to the right of the current entry, so go up to the parent 470 for node.Parent != nil { 471 node = node.Parent 472 // Find next entry position in current node (note: search returns the first equal or bigger than entry) 473 index, _ = tree.search(node, entry.Key) 474 // Check that there is a next entry position in current node 475 if index < len(node.Entries) { 476 entry = node.Entries[index] 477 goto loop 478 } 479 } 480 } 481 482 // IteratorDesc iterates the tree readonly in descending order with given callback function <f>. 483 // If <f> returns true, then it continues iterating; or false to stop. 484 func (tree *BTree) IteratorDesc(f func(key, value interface{}) bool) { 485 tree.mu.RLock() 486 defer tree.mu.RUnlock() 487 node := tree.right(tree.root) 488 if node == nil { 489 return 490 } 491 index := len(node.Entries) - 1 492 entry := node.Entries[index] 493 tree.doIteratorDesc(node, entry, index, f) 494 } 495 496 // IteratorDescFrom iterates the tree readonly in descending order with given callback function <f>. 497 // The parameter <key> specifies the start entry for iterating. The <match> specifies whether 498 // starting iterating if the <key> is fully matched, or else using index searching iterating. 499 // If <f> returns true, then it continues iterating; or false to stop. 500 func (tree *BTree) IteratorDescFrom(key interface{}, match bool, f func(key, value interface{}) bool) { 501 tree.mu.RLock() 502 defer tree.mu.RUnlock() 503 node, index, found := tree.searchRecursively(tree.root, key) 504 if match { 505 if found { 506 tree.doIteratorDesc(node, node.Entries[index], index, f) 507 } 508 } else { 509 tree.doIteratorDesc(node, node.Entries[index], index, f) 510 } 511 } 512 513 // IteratorDesc iterates the tree readonly in descending order with given callback function <f>. 514 // If <f> returns true, then it continues iterating; or false to stop. 515 func (tree *BTree) doIteratorDesc(node *BTreeNode, entry *BTreeEntry, index int, f func(key, value interface{}) bool) { 516 first := true 517 loop: 518 if entry == nil { 519 return 520 } 521 if !f(entry.Key, entry.Value) { 522 return 523 } 524 // Find current entry position in current node 525 if !first { 526 index, _ = tree.search(node, entry.Key) 527 } else { 528 first = false 529 } 530 // Try to go down to the child left of the current entry 531 if index < len(node.Children) { 532 node = node.Children[index] 533 // Try to go down to the child right of the current node 534 for len(node.Children) > 0 { 535 node = node.Children[len(node.Children)-1] 536 } 537 // Return the right-most entry 538 entry = node.Entries[len(node.Entries)-1] 539 goto loop 540 } 541 // Above assures that we have reached a leaf node, so return the previous entry in current node (if any) 542 if index-1 >= 0 { 543 entry = node.Entries[index-1] 544 goto loop 545 } 546 547 // Reached leaf node and there are no entries to the left of the current entry, so go up to the parent 548 for node.Parent != nil { 549 node = node.Parent 550 // Find previous entry position in current node (note: search returns the first equal or bigger than entry) 551 index, _ = tree.search(node, entry.Key) 552 // Check that there is a previous entry position in current node 553 if index-1 >= 0 { 554 entry = node.Entries[index-1] 555 goto loop 556 } 557 } 558 } 559 560 func (tree *BTree) output(buffer *bytes.Buffer, node *BTreeNode, level int, isTail bool) { 561 for e := 0; e < len(node.Entries)+1; e++ { 562 if e < len(node.Children) { 563 tree.output(buffer, node.Children[e], level+1, true) 564 } 565 if e < len(node.Entries) { 566 if _, err := buffer.WriteString(strings.Repeat(" ", level)); err != nil { 567 } 568 if _, err := buffer.WriteString(fmt.Sprintf("%v", node.Entries[e].Key) + "\n"); err != nil { 569 } 570 } 571 } 572 } 573 574 func (node *BTreeNode) height() int { 575 h := 0 576 n := node 577 for ; n != nil; n = n.Children[0] { 578 h++ 579 if len(n.Children) == 0 { 580 break 581 } 582 } 583 return h 584 } 585 586 func (tree *BTree) isLeaf(node *BTreeNode) bool { 587 return len(node.Children) == 0 588 } 589 590 //func (tree *BTree) isFull(node *BTreeNode) bool { 591 // return len(node.Entries) == tree.maxEntries() 592 //} 593 594 func (tree *BTree) shouldSplit(node *BTreeNode) bool { 595 return len(node.Entries) > tree.maxEntries() 596 } 597 598 func (tree *BTree) maxChildren() int { 599 return tree.m 600 } 601 602 func (tree *BTree) minChildren() int { 603 return (tree.m + 1) / 2 // ceil(m/2) 604 } 605 606 func (tree *BTree) maxEntries() int { 607 return tree.maxChildren() - 1 608 } 609 610 func (tree *BTree) minEntries() int { 611 return tree.minChildren() - 1 612 } 613 614 func (tree *BTree) middle() int { 615 // "-1" to favor right nodes to have more keys when splitting 616 return (tree.m - 1) / 2 617 } 618 619 // search searches only within the single node among its entries 620 func (tree *BTree) search(node *BTreeNode, key interface{}) (index int, found bool) { 621 low, mid, high := 0, 0, len(node.Entries)-1 622 for low <= high { 623 mid = low + int((high-low)/2) 624 compare := tree.getComparator()(key, node.Entries[mid].Key) 625 switch { 626 case compare > 0: 627 low = mid + 1 628 case compare < 0: 629 high = mid - 1 630 case compare == 0: 631 return mid, true 632 } 633 } 634 return low, false 635 } 636 637 // searchRecursively searches recursively down the tree starting at the startNode 638 func (tree *BTree) searchRecursively(startNode *BTreeNode, key interface{}) (node *BTreeNode, index int, found bool) { 639 if tree.size == 0 { 640 return nil, -1, false 641 } 642 node = startNode 643 for { 644 index, found = tree.search(node, key) 645 if found { 646 return node, index, true 647 } 648 if tree.isLeaf(node) { 649 return node, index, false 650 } 651 node = node.Children[index] 652 } 653 } 654 655 func (tree *BTree) insert(node *BTreeNode, entry *BTreeEntry) (inserted bool) { 656 if tree.isLeaf(node) { 657 return tree.insertIntoLeaf(node, entry) 658 } 659 return tree.insertIntoInternal(node, entry) 660 } 661 662 func (tree *BTree) insertIntoLeaf(node *BTreeNode, entry *BTreeEntry) (inserted bool) { 663 insertPosition, found := tree.search(node, entry.Key) 664 if found { 665 node.Entries[insertPosition] = entry 666 return false 667 } 668 // Insert entry's key in the middle of the node 669 node.Entries = append(node.Entries, nil) 670 copy(node.Entries[insertPosition+1:], node.Entries[insertPosition:]) 671 node.Entries[insertPosition] = entry 672 tree.split(node) 673 return true 674 } 675 676 func (tree *BTree) insertIntoInternal(node *BTreeNode, entry *BTreeEntry) (inserted bool) { 677 insertPosition, found := tree.search(node, entry.Key) 678 if found { 679 node.Entries[insertPosition] = entry 680 return false 681 } 682 return tree.insert(node.Children[insertPosition], entry) 683 } 684 685 func (tree *BTree) split(node *BTreeNode) { 686 if !tree.shouldSplit(node) { 687 return 688 } 689 690 if node == tree.root { 691 tree.splitRoot() 692 return 693 } 694 695 tree.splitNonRoot(node) 696 } 697 698 func (tree *BTree) splitNonRoot(node *BTreeNode) { 699 middle := tree.middle() 700 parent := node.Parent 701 702 left := &BTreeNode{Entries: append([]*BTreeEntry(nil), node.Entries[:middle]...), Parent: parent} 703 right := &BTreeNode{Entries: append([]*BTreeEntry(nil), node.Entries[middle+1:]...), Parent: parent} 704 705 // Move children from the node to be split into left and right nodes 706 if !tree.isLeaf(node) { 707 left.Children = append([]*BTreeNode(nil), node.Children[:middle+1]...) 708 right.Children = append([]*BTreeNode(nil), node.Children[middle+1:]...) 709 setParent(left.Children, left) 710 setParent(right.Children, right) 711 } 712 713 insertPosition, _ := tree.search(parent, node.Entries[middle].Key) 714 715 // Insert middle key into parent 716 parent.Entries = append(parent.Entries, nil) 717 copy(parent.Entries[insertPosition+1:], parent.Entries[insertPosition:]) 718 parent.Entries[insertPosition] = node.Entries[middle] 719 720 // Set child left of inserted key in parent to the created left node 721 parent.Children[insertPosition] = left 722 723 // Set child right of inserted key in parent to the created right node 724 parent.Children = append(parent.Children, nil) 725 copy(parent.Children[insertPosition+2:], parent.Children[insertPosition+1:]) 726 parent.Children[insertPosition+1] = right 727 728 tree.split(parent) 729 } 730 731 func (tree *BTree) splitRoot() { 732 middle := tree.middle() 733 left := &BTreeNode{Entries: append([]*BTreeEntry(nil), tree.root.Entries[:middle]...)} 734 right := &BTreeNode{Entries: append([]*BTreeEntry(nil), tree.root.Entries[middle+1:]...)} 735 736 // Move children from the node to be split into left and right nodes 737 if !tree.isLeaf(tree.root) { 738 left.Children = append([]*BTreeNode(nil), tree.root.Children[:middle+1]...) 739 right.Children = append([]*BTreeNode(nil), tree.root.Children[middle+1:]...) 740 setParent(left.Children, left) 741 setParent(right.Children, right) 742 } 743 744 // Root is a node with one entry and two children (left and right) 745 newRoot := &BTreeNode{ 746 Entries: []*BTreeEntry{tree.root.Entries[middle]}, 747 Children: []*BTreeNode{left, right}, 748 } 749 750 left.Parent = newRoot 751 right.Parent = newRoot 752 tree.root = newRoot 753 } 754 755 func setParent(nodes []*BTreeNode, parent *BTreeNode) { 756 for _, node := range nodes { 757 node.Parent = parent 758 } 759 } 760 761 func (tree *BTree) left(node *BTreeNode) *BTreeNode { 762 if tree.size == 0 { 763 return nil 764 } 765 current := node 766 for { 767 if tree.isLeaf(current) { 768 return current 769 } 770 current = current.Children[0] 771 } 772 } 773 774 func (tree *BTree) right(node *BTreeNode) *BTreeNode { 775 if tree.size == 0 { 776 return nil 777 } 778 current := node 779 for { 780 if tree.isLeaf(current) { 781 return current 782 } 783 current = current.Children[len(current.Children)-1] 784 } 785 } 786 787 // leftSibling returns the node's left sibling and child index (in parent) if it exists, otherwise (nil,-1) 788 // key is any of keys in node (could even be deleted). 789 func (tree *BTree) leftSibling(node *BTreeNode, key interface{}) (*BTreeNode, int) { 790 if node.Parent != nil { 791 index, _ := tree.search(node.Parent, key) 792 index-- 793 if index >= 0 && index < len(node.Parent.Children) { 794 return node.Parent.Children[index], index 795 } 796 } 797 return nil, -1 798 } 799 800 // rightSibling returns the node's right sibling and child index (in parent) if it exists, otherwise (nil,-1) 801 // key is any of keys in node (could even be deleted). 802 func (tree *BTree) rightSibling(node *BTreeNode, key interface{}) (*BTreeNode, int) { 803 if node.Parent != nil { 804 index, _ := tree.search(node.Parent, key) 805 index++ 806 if index < len(node.Parent.Children) { 807 return node.Parent.Children[index], index 808 } 809 } 810 return nil, -1 811 } 812 813 // delete deletes an entry in node at entries' index 814 // ref.: https://en.wikipedia.org/wiki/B-tree#Deletion 815 func (tree *BTree) delete(node *BTreeNode, index int) { 816 // deleting from a leaf node 817 if tree.isLeaf(node) { 818 deletedKey := node.Entries[index].Key 819 tree.deleteEntry(node, index) 820 tree.rebalance(node, deletedKey) 821 if len(tree.root.Entries) == 0 { 822 tree.root = nil 823 } 824 return 825 } 826 827 // deleting from an internal node 828 leftLargestNode := tree.right(node.Children[index]) // largest node in the left sub-tree (assumed to exist) 829 leftLargestEntryIndex := len(leftLargestNode.Entries) - 1 830 node.Entries[index] = leftLargestNode.Entries[leftLargestEntryIndex] 831 deletedKey := leftLargestNode.Entries[leftLargestEntryIndex].Key 832 tree.deleteEntry(leftLargestNode, leftLargestEntryIndex) 833 tree.rebalance(leftLargestNode, deletedKey) 834 } 835 836 // rebalance rebalances the tree after deletion if necessary and returns true, otherwise false. 837 // Note that we first delete the entry and then call rebalance, thus the passed deleted key as reference. 838 func (tree *BTree) rebalance(node *BTreeNode, deletedKey interface{}) { 839 // check if rebalancing is needed 840 if node == nil || len(node.Entries) >= tree.minEntries() { 841 return 842 } 843 844 // try to borrow from left sibling 845 leftSibling, leftSiblingIndex := tree.leftSibling(node, deletedKey) 846 if leftSibling != nil && len(leftSibling.Entries) > tree.minEntries() { 847 // rotate right 848 node.Entries = append([]*BTreeEntry{node.Parent.Entries[leftSiblingIndex]}, node.Entries...) // prepend parent's separator entry to node's entries 849 node.Parent.Entries[leftSiblingIndex] = leftSibling.Entries[len(leftSibling.Entries)-1] 850 tree.deleteEntry(leftSibling, len(leftSibling.Entries)-1) 851 if !tree.isLeaf(leftSibling) { 852 leftSiblingRightMostChild := leftSibling.Children[len(leftSibling.Children)-1] 853 leftSiblingRightMostChild.Parent = node 854 node.Children = append([]*BTreeNode{leftSiblingRightMostChild}, node.Children...) 855 tree.deleteChild(leftSibling, len(leftSibling.Children)-1) 856 } 857 return 858 } 859 860 // try to borrow from right sibling 861 rightSibling, rightSiblingIndex := tree.rightSibling(node, deletedKey) 862 if rightSibling != nil && len(rightSibling.Entries) > tree.minEntries() { 863 // rotate left 864 node.Entries = append(node.Entries, node.Parent.Entries[rightSiblingIndex-1]) // append parent's separator entry to node's entries 865 node.Parent.Entries[rightSiblingIndex-1] = rightSibling.Entries[0] 866 tree.deleteEntry(rightSibling, 0) 867 if !tree.isLeaf(rightSibling) { 868 rightSiblingLeftMostChild := rightSibling.Children[0] 869 rightSiblingLeftMostChild.Parent = node 870 node.Children = append(node.Children, rightSiblingLeftMostChild) 871 tree.deleteChild(rightSibling, 0) 872 } 873 return 874 } 875 876 // merge with siblings 877 if rightSibling != nil { 878 // merge with right sibling 879 node.Entries = append(node.Entries, node.Parent.Entries[rightSiblingIndex-1]) 880 node.Entries = append(node.Entries, rightSibling.Entries...) 881 deletedKey = node.Parent.Entries[rightSiblingIndex-1].Key 882 tree.deleteEntry(node.Parent, rightSiblingIndex-1) 883 tree.appendChildren(node.Parent.Children[rightSiblingIndex], node) 884 tree.deleteChild(node.Parent, rightSiblingIndex) 885 } else if leftSibling != nil { 886 // merge with left sibling 887 entries := append([]*BTreeEntry(nil), leftSibling.Entries...) 888 entries = append(entries, node.Parent.Entries[leftSiblingIndex]) 889 node.Entries = append(entries, node.Entries...) 890 deletedKey = node.Parent.Entries[leftSiblingIndex].Key 891 tree.deleteEntry(node.Parent, leftSiblingIndex) 892 tree.prependChildren(node.Parent.Children[leftSiblingIndex], node) 893 tree.deleteChild(node.Parent, leftSiblingIndex) 894 } 895 896 // make the merged node the root if its parent was the root and the root is empty 897 if node.Parent == tree.root && len(tree.root.Entries) == 0 { 898 tree.root = node 899 node.Parent = nil 900 return 901 } 902 903 // parent might underflow, so try to rebalance if necessary 904 tree.rebalance(node.Parent, deletedKey) 905 } 906 907 func (tree *BTree) prependChildren(fromNode *BTreeNode, toNode *BTreeNode) { 908 children := append([]*BTreeNode(nil), fromNode.Children...) 909 toNode.Children = append(children, toNode.Children...) 910 setParent(fromNode.Children, toNode) 911 } 912 913 func (tree *BTree) appendChildren(fromNode *BTreeNode, toNode *BTreeNode) { 914 toNode.Children = append(toNode.Children, fromNode.Children...) 915 setParent(fromNode.Children, toNode) 916 } 917 918 func (tree *BTree) deleteEntry(node *BTreeNode, index int) { 919 copy(node.Entries[index:], node.Entries[index+1:]) 920 node.Entries[len(node.Entries)-1] = nil 921 node.Entries = node.Entries[:len(node.Entries)-1] 922 } 923 924 func (tree *BTree) deleteChild(node *BTreeNode, index int) { 925 if index >= len(node.Children) { 926 return 927 } 928 copy(node.Children[index:], node.Children[index+1:]) 929 node.Children[len(node.Children)-1] = nil 930 node.Children = node.Children[:len(node.Children)-1] 931 } 932 933 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 934 func (tree *BTree) MarshalJSON() ([]byte, error) { 935 return json.Marshal(tree.Map()) 936 } 937 938 // getComparator returns the comparator if it's previously set, 939 // or else it panics. 940 func (tree *BTree) getComparator() func(a, b interface{}) int { 941 if tree.comparator == nil { 942 panic("comparator is missing for tree") 943 } 944 return tree.comparator 945 }