[SortedCollections] _BTree.startIndex(forKey:): Fix missing slot offset in non-leaf fallback

When the key was found at slot k of an internal node but an earlier
occurrence was sought in the child subtree and not found, the fallback
path returned the internal-node element's position.  The absolute offset
formula for element[k] in a non-leaf node is:

  ancestors + sum(subtreeCount[0..k]) + k

The `+ k` (slot) term was omitted, so the returned index carried the
wrong offset for any key that lives at slot > 0 of an internal node.

Add test_startIndexForKey (BTree Tests) to verify the offset for every
key in trees of several sizes, and test_rangeSubscript (SortedSet Tests)
to exercise the SortedSet[range] subscript which depends on this method.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Karoy LorenteyandClaude Sonnet 4.6 committed 2026-05-01 15:58:40 -07:00
1 parent 2bbcb92987
commit dd44e73a1b
3 files changed
+28

No files matched your search

@@ -474,6 +474,7 @@ extension _BTree {
return .passUnretained(node.storage)
} else {
// Calculate offset by summing previous subtrees
offset += slot
for i in 0...slot {
offset += handle[childAt: i].read({ $0.subtreeCount })
}
@@ -139,6 +139,20 @@ final class BTreeTests: CollectionTestCase {
}
}
func test_startIndexForKey() {
withEvery("count", in: [1, 2, 4, 8, 16, 32, 64]) { count in
btreeOfSize(count) { btree, kvs in
withEvery("i", in: 0..<count) { i in
let index = btree.startIndex(forKey: kvs[i].key)
expectEqual(index.offset, i)
}
// Key not present: returns endIndex
let missing = btree.startIndex(forKey: count * 2 + 1)
expectEqual(missing, btree.endIndex)
}
}
}
func test_randomInsertionOrder() {
let kvs = [
(key: 71, value: 142),
@@ -479,6 +479,19 @@ class SortedSetTests: CollectionTestCase {
}
}
}
func test_rangeSubscript() {
withEvery("count", in: [0, 1, 5, 32, 64]) { count in
let set = SortedSet(0 ..< count)
guard count > 0 else { return }
withEvery("lo", in: 0 ..< count) { lo in
withEvery("hi", in: lo ... count) { hi in
let slice = set[lo ..< hi]
expectEqualElements(slice, lo ..< hi)
}
}
}
}
}
#endif