Commit Graph
464 Commits
Author SHA1 Message Date
David Nadoba 3a07388528 Add TemporaryArray: a stack-seeded, heap-spilling scratch array
TemporaryArray is a ~Copyable and ~Escapable dynamic array whose initial
storage is a borrowed buffer (most usefully a stack allocation vended by
withTemporaryArray(of:capacity:_:)) and which transparently spills over
into freshly allocated heap storage once it outgrows that seed buffer. As
long as the element count stays within a seed buffer that fit on the stack,
the array incurs no heap traffic at all.

Because it can hold a dependency on borrowed (stack) memory, the type is
non-escapable: instances cannot outlive the scope that provides their
initial buffer. Contents are lifted out into an owning container with
take(), which transfers the heap buffer in O(1) if the array has already
spilled, or moves the elements into a fresh UniqueArray otherwise.

The API mirrors UniqueArray (SE-0527), minus the pieces that don't apply
to a non-escapable scratch type (DynamicContainer, MutableContainer, and
RangeReplaceableContainer conformances plus the Drain-based consumer),
plus members unique to its borrow-then-spill design: take(), clone(), and
append(repeating:count:). The seed-buffer initializer is kept internal for
now, with withTemporaryArray as the sole entry point. Equatable/Hashable
and CustomStringConvertible/CustomDebugStringConvertible are implemented
as methods with FIXMEs to add the conformances once those protocols
support ~Copyable/~Escapable types.

The Collection/RangeReplaceable surface and container-protocol conformances
are gated behind the UnstableContainersPreview trait, mirroring UniqueArray;
the core API builds in the default configuration. DocC coverage is added for
the type and the withTemporaryArray entry point.
2026-07-09 15:16:13 -07:00
Karoy Lorentey 957813c2f4 Merge pull request #668 from inju2403/perf/orderedset-reverse-in-place
[OrderedCollections] OrderedSet.reverse(): update the hash table in place
2026-07-07 14:44:03 -07:00
Karoy Lorentey 3d68fc1107 Clean up the UniqueBox/Ref/MutableRef situation
- UniqueBox is public API, so we cannot remove it in favor of the stdlib’s
- Remove Ref and MutableRef. Keep an internal _MutableRef to work around stdlib limitations.
2026-06-17 18:29:41 -07:00
Karoy Lorentey 85cdb77d25 Fix build issues 2026-06-17 16:17:36 -07:00
Nate Cook c039a18a0e Switch to using stdlib Ref and UniqueBox 2026-06-17 14:27:29 -07:00
Nate Cook dca015d7e8 Align Iterable with proposal
Adds throwing and ~Escapable elements
2026-06-17 14:27:29 -07:00
Nate Cook 4bda43f4a9 Renaming BorrowingSequence_ to Iterable_ 2026-06-17 14:27:29 -07:00
Karoy Lorentey 9aca86f36b Update to reflect new name of expect{Rigid,Unique}ArrayContents 2026-06-17 13:58:54 -07:00
Karoy Lorentey 28e9d98a7e Fix deprecation warnings 2026-06-17 13:48:54 -07:00
Alejandro Alonso 6da58357a3 Rename reallocate to setCapacity for Rigid and UniqueArray
Update UniqueArray.swift

Update UniqueArray.swift
2026-06-17 13:48:53 -07:00
inju2403 86ddbd9705 [OrderedCollections] OrderedSet.reverse(): update the hash table in place
Reversing an ordered set is a deterministic permutation: the element at offset `i` moves to offset `count - 1 - i`. Hash values are unaffected, so every element stays in its current bucket and only the stored offset needs to be flipped. `reverse()` was instead regenerating the whole hash table from scratch, rehashing every element -- exactly what the existing `// FIXME: Update hash table contents in place.` called out.

Replace `_regenerateHashTable()` with an in-place offset flip (`v -> count - 1 - v`) over the table's buckets, reusing the same bucket-walk idiom as `adjustContents` and `swapBucketValues`. This drops all hash recomputation and the table reallocation.
2026-06-12 08:57:42 +09:00
Karoy Lorentey af174fe447 Merge pull request #662 from sorinc03/fix/heap-node-tests-release
Run heap node tests in release
2026-06-09 15:03:37 -07:00
Karoy Lorentey f3ede2e378 Delete unused test source 2026-06-05 18:46:12 -07:00
Karoy Lorentey 5c8d97dccb Merge pull request #660 from apple/dn/ordered-set-move
[OrderedCollections] Add move operations
2026-06-05 17:45:16 -07:00
David Nadoba 72f074a23a [OrderedCollections] Use pre-removal destination index for move APIs 2026-06-05 17:05:03 -07:00
David Nadoba 5a6af29d55 [OrderedCollections] Refine move APIs and simplify no-op check 2026-06-05 14:44:22 -07:00
David Nadoba a83773321e [OrderedCollections] Rework move APIs and extend to OrderedDictionary
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.
2026-06-04 22:33:54 -07:00
Sorin Cioban bdd6b79403 Use package access for heap test helper 2026-06-04 10:18:09 +01:00
Sorin Cioban 49887191bb Run heap node tests in release 2026-05-31 23:10:33 +01:00
David Nadoba 508f36f48d [OrderedSet] Add move(_:toOffset:)
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.
2026-05-25 23:01:28 -07:00
Aditya Singh 0a3dcfd3a8 [InternalCollectionsUtilities] Fix _trim returning the wrong buffer region
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.
2026-05-24 18:22:45 -07:00
Karoy Lorentey c3ba833517 Add basic tests for Collections module 2026-05-15 16:57:22 -07:00
Karoy Lorentey 40c730869d [ContainersPreview] Add more detailed tests for MutableRef’s API surface 2026-05-06 18:34:57 -07:00
Karoy Lorentey 16d6b8e1fe [ContainersPreview] Inout ⟹ MutableRef 2026-05-06 18:28:07 -07:00
Karoy Lorentey 05f19cf771 [ContainersPreview] Add more detailed tests for struct Ref 2026-05-06 18:00:13 -07:00
Karoy Lorentey a6fd64697a [ContainersPreview] Borrow ⟹ Ref
Also update the type’s public API surface to reflect SE-0519, leaving deprecated aliases for the old names.
2026-05-06 18:00:13 -07:00
Franz Busch 3c373b900c Use the defines from traits directly
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.
2026-05-06 07:41:02 -07:00
Karoy Lorentey 3177a4c29a [ContainersPreview] Add more detailed tests for UniqueBox 2026-05-05 17:31:09 -07:00
Karoy Lorentey 146056a641 [ContainersPreview] Box ⟹ UniqueBox
Also update the type’s public API surface to reflect SE-0517, leaving deprecated aliases for the old names.
2026-05-05 17:31:05 -07:00
Karoy Lorentey 022795168a [BasicContainers] Enable APIs scheduled to ship in 1.5.0
- `RigidArray.nextMutableSpan(after:maximumCount:)`
- `UniqueArray.nextMutableSpan(after:maximumCount:)`
- `RigidDeque.nextMutableSpan(after:maximumCount:)`
- `UniqueDeque.nextMutableSpan(after:maximumCount:)`
- `UniqueArray.init(minimumCapacity:)` (replacing `.init(capacity:)`)
- `UniqueDeque.init(minimumCapacity:)` (replacing `.init(capacity:)`)
- `RigidDeque.index(before:)`
- `UniqueDeque.index(before:)`
- `RigidDeque.formIndex(before:)`
- `UniqueDeque.formIndex(before:)`
2026-05-05 16:01:31 -07:00
Karoy LorenteyandClaude Sonnet 4.6 6498b67816 [SortedCollections] SortedSet: Add value-range subscripts for ClosedRange and partial ranges
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>
2026-05-01 18:10:22 -07:00
Karoy LorenteyandClaude Sonnet 4.6 64881e9cb4 [SortedCollections] SortedSet: Add firstIndex(after:) and lastIndex(before:)
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>
2026-05-01 17:59:18 -07:00
Karoy LorenteyandClaude Sonnet 4.6 e8b92d9f27 [SortedCollections] _BTree.lastIndex(forKey:): Fix offset and missing leftmost-child descent
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>
2026-05-01 17:30:06 -07:00
Karoy LorenteyandClaude Sonnet 4.6 8f2e4bba20 [SortedCollections] _Node.UnsafeHandle.concatenateWith: Fix children buffer corruption in simple-merge path
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>
2026-05-01 17:14:21 -07:00
Karoy LorenteyandClaude Sonnet 4.6 dd44e73a1b [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>
2026-05-01 15:58:40 -07:00
Karoy Lorentey 78361bd4ac Merge pull request #637 from lorentey/bitcollections-fixes
[BitCollections] Fix small issues
2026-05-01 15:11:42 -07:00
Karoy Lorentey dd50db4bb8 Merge pull request #635 from lorentey/assorted-fixes
[HashTreeCollections] Fix invariant violation in _HashNode._regularNode
2026-05-01 14:41:10 -07:00
Karoy Lorentey cef6301d19 [BitCollections] BitSet.isSubset(of: Range<Int>): also look at elements above the range's upper word 2026-05-01 14:33:28 -07:00
Karoy Lorentey 0ede027242 [HashTreeCollections] Fix invariant violation in some operations
The two-child variant of _HashNode._regularNode did not check bucket ordering before placing children, leading to inaccessible nodes half of the time.
2026-04-30 17:42:27 -07:00
Karoy Lorentey 215a9ac0a7 Merge pull request #632 from lorentey/assorted-fixes
[BasicContainers, DequeModule]: Assorted fixes
2026-04-30 15:53:21 -07:00
Karoy Lorentey f9a6df8a55 [_RopeModule] Fix infinite loop while hashing the UTF-8 view of a multi-chunk big substring 2026-04-30 15:29:22 -07:00
Karoy Lorentey f652543a50 [ContainersPreview] Producer.ProducerError ⟹ Producer.Failure
Reserving a unique name for Producer’s failure type seems unwise, especially if we end up Producer refining a throwing BorrowingSequence protocol.
2026-04-30 13:31:28 -07:00
Karoy Lorentey 6017342a4d Merge pull request #616 from inju2403/feature/ordered-dictionary-replace-element-at-index
[OrderedCollections] Add OrderedDictionary.replaceElement(at:withKey:…
2026-04-27 18:05:52 -07:00
Karoy Lorentey 2c86775a6b [DequeModule] UniqueDeque.replace(removing:addingCount:initializingWith:): Fix sizing issue 2026-04-27 18:01:24 -07:00
Karoy Lorentey 0be6f43972 [DequeModule] RigidDeque.nextMutableSpan(after:maximumCount:): Fix missing argument validation 2026-04-27 17:25:50 -07:00
Karoy Lorentey 654d57533f [DequeModule] RigidDeque.consume(_:consumingWith:): Close resulting gap before returning 2026-04-27 17:18:05 -07:00
Karoy Lorentey 4b8dc6d951 BasicContainers] RigidDictionary.udateValue(forKey:with:): Fix undefined behavior on removals 2026-04-27 16:42:51 -07:00
Franz Busch c12dabe1b8 Fix _trim(first:) returning wrong buffer region
After reassigning self on line 160, baseAddress on line 161 resolves to the new self's baseAddress (oldStart + cut) instead of the original start. This causes the returned buffer to point past the actual elements into uninitialized memory. Use the captured oldStart instead.
2026-04-25 00:09:23 +02:00
inju2403 8c5830ee46 [OrderedCollections] OrderedDictionary.replaceElement: allow the new key to equal the key at index
Per review feedback, relax the precondition so that the new key may compare equal to the key currently stored at index. This enables replacing an existing key with an equal-but-not-identical instance — for example, swapping a decomposed Unicode string with its precomposed equivalent — without an inefficient remove/insert workaround.

When the new key matches the one being replaced, the pair is updated in place via OrderedSet.update(_:at:) and the hash table is left untouched, preserving the expected amortized O(1) complexity.

Add a test_replaceElement_sameKey test on both OrderedDictionary and its Elements view that exercises the new path with LifetimeTracked keys carrying equal payloads but distinct instances.
2026-04-23 21:38:11 +09:00
Karoy Lorentey 5bd8ab095d [BasicContainers] UniqueArray.replace(removing:copying): Fix overallocation issue
`UniqueArray.replace(removing:copying:)` overloads overestimated the amount of memory they need, sometimes leading to unnecessary reallocations. Fix this.
2026-04-22 16:23:15 -07:00