From dd44e73a1b520b7c8235b31744907fa74e82c290 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 1 May 2026 15:58:40 -0700 Subject: [PATCH] [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 --- Sources/SortedCollections/BTree/_BTree.swift | 1 + .../SortedCollectionsTests/BTree/BTree Tests.swift | 14 ++++++++++++++ .../SortedSet/SortedSet Tests.swift | 13 +++++++++++++ 3 files changed, 28 insertions(+) diff --git a/Sources/SortedCollections/BTree/_BTree.swift b/Sources/SortedCollections/BTree/_BTree.swift index 9bfef4d5..84d732e5 100644 --- a/Sources/SortedCollections/BTree/_BTree.swift +++ b/Sources/SortedCollections/BTree/_BTree.swift @@ -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 }) } diff --git a/Tests/SortedCollectionsTests/BTree/BTree Tests.swift b/Tests/SortedCollectionsTests/BTree/BTree Tests.swift index a2d0a4c2..0074daa1 100644 --- a/Tests/SortedCollectionsTests/BTree/BTree Tests.swift +++ b/Tests/SortedCollectionsTests/BTree/BTree Tests.swift @@ -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.. 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