[SortedCollections] Collapse an empty root after removing a root key through _modify

UnsafeCursor.removeElement(hasValueHole:) only collapsed an empty root
inside the loop that walks up the cursor's path, which never runs when
the removed key is in the root. Removing such a key with d[key].take()
could leave the root as an internal node with no keys and one child.
Collapse the root after the loop so every path depth is covered.

Fixes #811
This commit is contained in:
Sandeep Vijayarao committed 2026-11-04 19:17:52 -08:00
1 parent ed857ee877
commit 3a80514ab6
2 files changed
+29 -13

No files matched your search

@@ -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
}
}
@@ -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<Int, Int>()
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