Reworks the relocation API and extends it to `OrderedDictionary`:
* Renames the index-range move to `moveSubrange(_:to:)` (with a
`RangeExpression` overload) and the by-value move to `move(contentsOf:to:)`,
matching the conventions of `removeSubrange`/`insert(_:at:)`. Adds
`move(fromIndices:to:)`, which takes the source indices directly.
* Factors the element rearrangement into generic
`UnsafeMutableBufferPointer` operations (rotation / rotation+permutation /
scatter) so `OrderedDictionary` relocates its keys and values in lockstep
through the same code, adding only the parallel value move; the hash-table
maintenance stays entirely in `OrderedSet`.
* The hot path runs in O(*d* + *k*) and falls back to O(`count`) for large
moves; bucket maintenance chooses targeted updates or a full rebuild by the
same threshold.
* `move(contentsOf:to:)` ignores elements/keys that aren't present; duplicate
members are detected and trap.
Adds tests (exhaustive hash-table integrity, value alignment under lifetime
tracking) and move benchmarks for both types.
The defaultInternalCapacity and defaultLeafCapacity computations used
Swift.min(16, capacityInBytes / MemoryLayout<Key>.stride), which capped
the node capacity at 16 regardless of element size. This defeated the
byte-budget intent: small elements should yield larger nodes, not be
clamped to 16. Use Swift.max instead so 16 acts as a floor and the
byte budget governs the upper bound, as confirmed by the maintainer
in issue #257.
Fixes#257
Adds two overloads for relocating elements within an `OrderedSet`: one
taking a contiguous `Range<Int>`, and one taking a `Sequence<Element>`.
The moved elements occupy consecutive positions starting at the
destination, in the order they appear in the input.
The hot path runs in O(*d* + *k*) time, where *d* is the distance moved
and *k* is the number of elements moved; the implementation falls back
to O(`count`) for large moves.
The `_trim(first:)` and `_trim(last:)` helpers reassign `self` to the
remaining slice and then build the trimmed result from `self`'s now-updated
`baseAddress`/`count`, so they hand back a region that points into the wrong
place in the buffer.
`UnsafeMutableBufferPointer._trim(first:)` had this exact bug fixed earlier (it
captures `oldStart` before the reassignment), but three sibling helpers were
left untouched:
* `UnsafeBufferPointer._trim(first:)` reads `baseAddress` after advancing
`self`, so the returned prefix starts at the remainder instead of at the
original head.
* `UnsafeBufferPointer._trim(last:)` and
`UnsafeMutableBufferPointer._trim(last:)` recompute `count &- cut` after
shrinking `self`, so the returned suffix starts `cut` elements too early.
For a five-element buffer, `_trim(first: 2)` returned the bytes of `[30, 40]`
rather than `[10, 20]`, and `_trim(last: 2)` returned `[20, 30]` rather than
`[40, 50]`; trimming more than the count walked off the end of the buffer.
Capture the original start (and, for the suffix case, the post-trim count)
before mutating `self`, matching the already-correct `_trim(first:)` on the
mutable buffer. Adds direct tests covering both overloads on both buffer types.
Package traits already pass defines with their trait name when building. Instead of adding our own conditional defines based on the traits we can use the trait provided defines directly. I observed that various tooling behaves better with the trait provided defines.
These (and `@_unsafeSelfDependentResult`) are only usable on 6.4 snapshots. As 6.4 hasn’t shipped yet, we need to also make these conditional on the UnstableContainersPreview trait.
The Range<Element> subscript covers half-open intervals. Add four
concrete overloads so callers can also write set[lo...hi], set[lo...],
set[..<hi], and set[...hi] — covering every stdlib RangeExpression
type that makes sense for a sorted set.
A single generic subscript<R: RangeExpression> would have been nicer,
but RangeExpression only exposes bounds via relative(to:), which needs
a Collection with Index == Bound. Element is Comparable but not an
index of any collection we have, so the generic path doesn't work for
arbitrary Element types. Five overloads it is.
The inclusive-upper variants (ClosedRange, PartialRangeThrough) use a
private _firstTreeIndex(after:) helper that returns the first
_BTree.Index strictly greater than a given element (or endIndex) —
the same logic as the public firstIndex(after:), but returning a
_Tree.Index directly for internal use.
Tests probe every lo/hi pair using a set of even numbers, so each
query exercises both "hits a member" and "falls between members"
cases, plus bounds that extend past each end of the set.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The Range<Element> subscript covers half-open intervals, and with
partial-range support it would compose into ceiling/floor/lower (first
>= x, last <= x, last < x). The strict upper bound "first element > x"
(Java's higher(_:)) can't be expressed as a range for arbitrary
Comparable types because Comparable has no successor operation, so
expose it — together with the symmetric strict lower bound — as
first-class operations.
Both are built on _BTree.startIndex(forKey:), which already returns the
first element >= the given key:
- firstIndex(after: x) advances past that index if the element there
equals x.
- lastIndex(before: x) steps back one index, or returns nil if the
lookup landed at startIndex.
Add test_firstIndexAfter and test_lastIndexBefore, covering queries
that hit an element, queries that fall between elements, and out-of-
range queries on both ends.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two bugs in the non-leaf path, symmetric to the ones recently fixed in
_BTree.startIndex(forKey:):
1. Offset was short by 1 when recursing into child[slot+1]. After
computing the position of elem[slot] and saving it as the fallback
offset, the recursion was entered with that same offset — but
child[slot+1] starts one past elem[slot] in sorted order, so every
element found deeper got an offset that was too small by 1. Fix:
build the elem[slot] offset with an exclusive loop, save it, then
advance offset by 1 before descending.
2. When endSlot returns 0 (every element at this node is > key), the
function returned nil instead of descending into child[0], which may
still contain elements <= key. This mirrors the rightmost-child
descent case we added to startIndex(forKey:).
lastIndex(forKey:) currently has no callers, but is @inlinable internal
and clearly intended for use; leaving the latent bugs in place would
just burn the next caller.
Add test_lastIndexForKey to BTree Tests, verifying the offset returned
for every key in trees of various sizes, plus the "key smaller than
every element" edge case which exercises the leftmost-descent path.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When two same-depth internal nodes plus a separator fit in a single
node, `concatenateWith` takes the simple-merge branch. The non-leaf
subbranch was calling `moveInitializeElements` to move children, but
that method operates on the keys/values buffers, not the children
buffer. The consequences:
- The re-read from `rightHandle.keys[0..<childCount]` hits slots that
were already moved-out by the preceding `moveInitializeElements`
call, which is UB.
- Writes land on top of keys just written by that same prior call,
corrupting them.
- `self.children` is left with its original (too few) children plus
uninitialized slots; subsequent traversal dereferences garbage.
- `rightHandle.drop()` deallocates the children buffer without
transferring ownership, leaking the `_Node.Storage` references.
Fix: call `moveInitializeChildren` instead, matching the splinter
branch just above.
Add `test_join_nonLeafSimpleMerge`, which builds two depth-1 internal
nodes whose combined element count fits in capacity 4 and joins them
via `_Node.join`. Without the fix the resulting tree's children are
undefined, so iteration either crashes or yields garbage.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two bugs in the non-leaf path:
1. The loop used `for i in 0...slot` (inclusive), which added child[slot]'s
subtreeCount to `offset` *before* recursing into child[slot]. This made
the recursion start from elem[slot]'s position rather than child[slot]'s
start, so every element found inside child[slot] carried an offset that
was too large by subtreeCount[slot]. Fix: use `0..<slot` for the pre-
recursion accumulation and read child[slot]'s subtreeCount separately only
when computing the fallback `elemOffset`.
2. When startSlot returns elementCount (key is greater than every element in
the node), the old code returned nil, silently failing to find any element
>= key that lives in the rightmost child subtree. Fix: descend into
child[elementCount] in that case, mirroring how findAnyIndex handles it.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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>
The guard `slot > 0` incorrectly excluded `slot == 0`, causing the function
to return `endIndex` whenever the matching element was at position 0 of any
node. Changed to `slot >= 0`.
The non-leaf fallback was also missing `offset += slot`, matching the same
bug that exists symmetrically in startIndex(forKey:). The absolute offset
of element[k] in a non-leaf node is ancestors + sum(subtreeCount[0..k]) + k;
the `+k` term was absent.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>