diff --git a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift index 6e549210..0f9fd4cb 100644 --- a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift +++ b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift @@ -352,25 +352,25 @@ extension _BTree { // Balance the parents var depth = unsafe path.depth - 2 while depth >= 0 { - var (newNode, _) = unsafe self.updateNode(atDepth: depth) { (handle, slot) in + (node, _) = unsafe self.updateNode(atDepth: depth) { (handle, slot) in unsafe handle.exchangeChild(atSlot: slot, with: node) unsafe handle.subtreeCount -= 1 unsafe handle.balance(atSlot: slot) } - - if unsafe depth == 0 && newNode.read({ unsafe $0.elementCount == 0 && !$0.isLeaf }) { - // If the root has no elements, we drop it and promote the child. - node = unsafe newNode.update(isUnique: true) { handle in - let newRoot = unsafe handle.moveChild(atSlot: 0) - unsafe handle.drop() - return newRoot - } - } else { - node = newNode - } depth -= 1 } - + + // `node` is now the root. Balancing may have merged its last two + // children, including when the removed element was in the root itself. + if unsafe node.read({ unsafe $0.elementCount == 0 && !$0.isLeaf }) { + // If the root has no elements, we drop it and promote the child. + node = unsafe node.update(isUnique: true) { handle in + let newRoot = unsafe handle.moveChild(atSlot: 0) + unsafe handle.drop() + return newRoot + } + } + self._root = node.storage } } diff --git a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift index 0ffc6598..487d33de 100644 --- a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift +++ b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Tests.swift @@ -292,6 +292,22 @@ final class SortedDictionaryTests: CollectionTestCase { } } + func test_modifySubscriptRemovalOfRootKey() { + // In debug builds, leaves hold up to 5 keys and internal nodes up to 4. + var d = SortedDictionary() + for i in 0 ..< 6 { d[i] = i } // root [2], leaves [0, 1] and [3, 4, 5] + d[5] = nil // both leaves now hold the minimum of 2 keys + + // Removing the root key merges the root's only two children. + let removed = d[2].take() + expectEqual(removed, 2) + expectEqual(d.count, 4) + expectEqualElements(d.map { $0.key }, [0, 1, 3, 4]) + + d[2] = 2 + expectEqualElements(d.map { $0.key }, [0, 1, 2, 3, 4]) + } + func test_modifySubscriptInsertUpdate() { func modify(_ value: inout Int?, setTo newValue: Int?) { value = newValue