Commit Graph
1355 Commits
Author SHA1 Message Date
Sandeep Vijayarao 1f4913eb96 [BitCollections] Don't trap on BitSet[members:] closed ranges ending at Int.max
`BitSet[members:]` resolved range expressions against
`Int.min ..< Int.max`. A closed range ending at `Int.max`
(`bits[members: ...Int.max]`, `bits[members: 0 ... Int.max]`) needs the
index after `Int.max`, so it trapped with "Index out of bounds", while
`..<Int.max` and `0...` worked.

Resolve against a small internal collection of all `Int` values whose
`index(after:)` saturates at `Int.max`. `Int.max` can never be a bit set
member, so `lower ... Int.max` resolving to `lower ..< Int.max` doesn't
change which members are selected. `BitSet.Counted[members:]` forwards
to `BitSet`, so it's fixed too.
2026-11-11 00:19:39 -08:00
Karoy Lorentey 88754449ab Merge pull request #845 from aashish254/codex/812-container-iterator-boundary
Fix ContainerIterator skip bounds
2026-11-10 11:16:20 -08:00
Karoy Lorentey 78be6a1820 Merge pull request #844 from SwastikTripathi/undeprecate-withkeys
[BasicContainers] Un-deprecate withKeys while keys is miscompiled
2026-11-10 11:15:53 -08:00
Karoy Lorentey 827fef0660 Merge pull request #817 from Joseph-Cursio/drainable-container-check
Add checkDrainableContainer and fix RigidArray's consumeLast recursion
2026-11-10 11:01:51 -08:00
Aashish fc11462e69 Fix ContainerIterator skip bounds 2026-11-09 21:42:36 +05:45
Swastik TripathiandClaude Opus 5.5 b0d9a5ebbb [BasicContainers] Un-deprecate withKeys while keys is miscompiled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 09:12:34 +05:30
Karoy Lorentey 8d0a2dfceb Deque: Make the empty singleton immortal 2026-11-06 16:06:08 -08:00
Sandeep Vijayarao 9a699a1952 [BasicContainers] Don't resolve the hole before shrinking in UniqueDictionary
Resolves the FIXME added in #836: when removing an entry through
`updateValue(forKey:with:)` triggers shrinking, there is no need to
restore the hash table's invariants first, since resizing rehashes every
item anyway.

Factor the part of `RigidDictionary._punchHole(at:)` that doesn't touch
the value slot into `_punchHole(withMovedValueAt:)`, and use it on the
shrink path of `UniqueDictionary._removeEntry(withMovedValueAt:)`, which
now mirrors `_removeValue(at:)`.
2026-11-05 18:54:31 -08:00
Karoy Lorentey 3f5e6e427b Merge branch 'main' into fix-unique-dictionary-closure-removal 2026-11-05 18:32:45 -08:00
Karoy Lorentey 1518b4eb3c Merge pull request #835 from sandeepvijayarao09/fix-memoized-value-bucket
[BasicContainers] Fix memoizedValue returning another key's value
2026-11-05 18:30:14 -08:00
Karoy Lorentey dbc1c194de Add performance FIXME 2026-11-05 18:29:11 -08:00
Sandeep Vijayarao 1735b98380 [BasicContainers] Fix double destroy in UniqueDictionary.updateValue(forKey:with:)
When the updater closure removes an existing entry (sets the value to
nil), `UniqueDictionary.updateValue(forKey:with:)` called
`_removeValue(at:)`. But the value had already been moved out of its
slot before calling the updater, and `_removeValue(at:)` moves it out
again and discards the result, destroying uninitialized memory. This
leads to crashes or memory corruption.

`RigidDictionary.updateValue(forKey:with:)` already handles this case
correctly, by deinitializing just the key and resolving the hole.

Add `UniqueDictionary._removeEntry(withMovedValueAt:)`, which does the
same and then shrinks storage under the same condition as
`_removeValue(at:)`, and use it for the removal path.
2026-11-05 18:17:48 -08:00
Karoy Lorentey 8b5cd1bb39 Remove misleading notes in docs
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2026-11-05 18:04:11 -08:00
Karoy Lorentey d804d39ca6 Work around optimizer bug in Swift 6.2 even harder 2026-11-05 17:57:03 -08:00
Sandeep VijayaraoandClaude Opus 5.5 c8cc9a7d4c [BasicContainers] Fix memoizedValue returning another key's value
`RigidDictionary._insertNew` (and `RigidSet._insertNew`) returned the
bucket reported by the hash table's `insertNew_Small`/`insertNew_Large`.
That is where the *last displaced* item ends up, not the new item: small
tables swap the new item into the middle and move the old middle item to
the end, and hashed tables do Robin Hood swaps along the probe sequence.
Whenever a swap happened, the returned bucket held some other entry.

`memoizedValue(forKey:_:)` on `RigidDictionary` and `UniqueDictionary`
returns a reference to the value at that bucket, so inserting a new key
often returned the value of a different key.

Track the first bucket the swapper writes the new item into, and return
that (or the final bucket if nothing was swapped). The hash table's own
return value is still used to initialize the displaced item, and its
other user (rehashing in `migrateItems_Large`) is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 17:51:08 -08:00
Karoy Lorentey daeac4ebb8 Stop catering to toolchains older than Swift 6.2 2026-11-05 17:40:50 -08:00
Karoy Lorentey a99833003c Work around optimizer bug in Swift 6.2 (memory leaks due to miscompiled bulk deinitialization) 2026-11-05 17:40:46 -08:00
Karoy Lorentey c4562ee2c1 Work around miscompilation issue with Ref to non-@addressable borrows 2026-11-05 16:49:20 -08:00
Karoy Lorentey f17980c2c5 Stop using @_addressableForDependencies 2026-11-05 16:29:46 -08:00
Karoy Lorentey 71893e4144 Resolve strict memory safety warnings with UnstableHashedContainers trait 2026-11-05 14:23:27 -08:00
Karoy Lorentey f7952f9e34 Merge pull request #830 from unaltolga/fix-unique-deque-iterable
[DequeModule] Make UniqueDeque Iterable without ContainersPreview
2026-11-05 14:13:21 -08:00
Karoy Lorentey 54086ee4f2 Merge pull request #829 from sandeepvijayarao09/fix-sorted-dictionary-modify-root
[SortedCollections] Collapse an empty root after removing a root key through _modify
2026-11-05 13:57:07 -08:00
Karoy Lorentey 13045ef84c Merge pull request #825 from sainadth/fix-heap-check-invariants-access
[Heap] Make _checkInvariants() public in internal checks builds
2026-11-05 13:40:49 -08:00
Karoy Lorentey 24b919a5ba Merge pull request #828 from lorentey/fix-permutable-container-algorithms
Fix some container algorithms
2026-11-05 13:40:23 -08:00
Tolga Unal 68fd4f2cc8 [DequeModule] Make UniqueDeque Iterable without ContainersPreview
842f125c removed the trait conditions around the Iterable APIs, but
UniqueDeque only got its conformance through Container in ContainersPreview.
RigidDeque had no underestimatedCount, so it was 0 through Iterable.
2026-11-05 09:09:48 -05:00
Sandeep Vijayarao 3a80514ab6 [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
2026-11-04 19:17:52 -08:00
Karoy Lorentey 7b578e5bfb Review and fix filter implementations
- Define a separate `filter` result on Iterable vs BorrowingIteratorProtocol
- Fix handling of delimited iterators in Container.filter
- Add fixmes for throwing
- Inlinability and other small fixes
2026-11-04 18:28:38 -08:00
Tolga Unal 9927f05e42 [BasicContainers] Make UniqueDictionary Equatable and Hashable with noncopyable contents
73ec3d341 made the other containers conform to Equatable/Hashable with
noncopyable contents, but UniqueDictionary was missed. The Hashable
extensions of RigidDictionary were also missing `Key: ~Copyable`.
2026-11-04 19:29:14 -05:00
sainadth c9286ec384 [Heap] Make _checkInvariants() public in internal checks builds
`Heap._checkInvariants()` was `internal` when COLLECTIONS_INTERNAL_CHECKS
is defined but `public` otherwise, so code outside `HeapModule` compiled
normally and then failed in an internal checks build.

Make both declarations `public`, matching `OrderedSet`,
`OrderedDictionary`, `BitSet` and `BitArray`, and add a test that calls it
through a plain `import HeapModule`.

Fixes #813
2026-11-04 13:10:43 -06:00
Joseph CursioandClaude Opus 5.5 c1ff9b9063 Build RigidArray's consumeLast drain without recursing
RigidArray's _customConsumeLast(_:) hook called consumeLast(_:), but
RigidArray has no one-argument consumeLast of its own, so the call went
to DrainableContainer.consumeLast(_:), which starts by calling the
hook. Every call to consumeLast(_:) on a RigidArray, directly or
through generic code, recursed until the stack overflowed.

Have the hook check the count and return consumeSubrange(_:) over the
last n items directly, the way consumeLast(_:consumingWith:) does.

Fixes #814.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 19:16:00 -06:00
Karoy Lorentey b14ab924a5 Fix PermutableContainer algorithms 2026-11-03 16:04:44 -08:00
e7d8cd2203 [ContainersPreview] Fix append(copying:) recursion and wrapped insert(copying:at:) (#819)
* [ContainersPreview] Fix append(copying:) recursion and wrapped insert(copying:at:)

The RangeReplaceableContainer extension's append(copying:) passed a
contiguous source's buffer back to itself and never returned.
_insertCollection copied the whole buffer on every initializer call, which
trapped when a deque's gap wrapped around the end of its storage. Copy only
what fits on each call, as replaceSubrange(_:copying:) already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Delete Tests/DequeTests/RangeReplaceableContainerCopyingTests.swift

Let's drop the tests for now; we'll need a less involved way to exercise such algorithms.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2026-11-03 14:57:43 -08:00
Karoy Lorentey 5bb5daddbb Merge pull request #807 from SwastikTripathi/docs-examples
Fix doc comment examples in OrderedDictionary, BitArray and SortedDictionary
2026-11-03 14:22:34 -08:00
Karoy Lorentey 9d026ae383 Merge pull request #808 from HuzaifaChaudary/fix/bitarray-wide-signed-conversion
[BitCollections] sign extend BitArray conversions to integers wider than a word
2026-11-03 14:22:18 -08:00
Karoy Lorentey a8b9b249a8 Merge pull request #818 from SwastikTripathi/fix/sorted-remove-at-rebalance
[SortedCollections] Balance the child after remove(at:)
2026-11-03 14:16:32 -08:00
Daiki Matsudate 16710713be Make UniqueDeque's Sendable conformance checked
UniqueDeque's only stored property is RigidDeque<Element>, which is
already Sendable when Element is, so the compiler can verify the
conformance without @unchecked. This mirrors UniqueArray over RigidArray.
2026-11-02 16:56:23 +09:00
Swastik TripathiandClaude Opus 5.5 93745231f1 [SortedCollections] Balance the child after remove(at:)
remove(at:) recursed into the child holding the offset and returned
without balancing it, so repeated removals could empty a leaf. Iterating
then read a stale slot, which returned already-removed elements and read
released references in release builds, and trapped in debug builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:43:22 +05:30
HuzaifaChaudary ed61a95cc8 [BitCollections] sign extend BitArray conversions to integers wider than a word
converting a negative bit array to `Int128` lost the sign above the first
64 bits , so `Int128(truncatingIfNeeded: "1" as BitArray)` gave
18446744073709551615 , not -1 , `Int128(exactly:)` gave nil , and
`Int128(_:)` trapped . a negative value now starts out as all ones , so the
words shifted in keep the sign .

the trap message also named `BitArray` as the type it could not convert
to , it names the integer type now .
2026-10-30 20:22:20 +05:00
Swastik TripathiandClaude Opus 5.5 8da3cafe2e Fix doc comment examples in OrderedDictionary, BitArray and SortedDictionary
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:04:13 +05:30
Karoy Lorentey e13f175180 Review RigidDeque/UniqueDeque tests; add better tests for prepends 2026-10-26 18:01:57 -07:00
Awais Rehman d45bd52372 Merge pull request #796 from awaisdev5765/fix-prepend-multi-span
Fix prepend(copying:) dropping items from multi-span sources
2026-10-26 12:40:35 -07:00
Karoy Lorentey a06a685e32 Merge pull request #801 from aashish254/hunt-doc-examples
[DequeModule] Fix RigidDeque prepend example capacity and direction-word slips
2026-10-26 12:02:22 -07:00
Karoy Lorentey 93b0a28178 [OrderedCollections] Resolve filename ambiguity with InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift
This only affects some build setups using the single-module configuration on
case-insensitive filesystems, but let’s get rid of it anyway.
2026-10-26 11:37:41 -07:00
Aashish d04fe0cd79 Fix DequeModule doc comments: capacity-overflow example and prepend/append direction wording
The prepend(copying:) examples on RigidDeque build a capacity-10 deque and then insert 11 items, which traps with 'RigidDeque capacity overflow' -- the type never grows and the docs' own fixed-capacity section says a full deque traps. Capacity 11 holds the documented result. Also fix five copy-paste direction errors in prose summaries (append described as going to the front, prepend described as going to the end).
2026-10-23 16:45:05 +05:45
844289ac45 fix: guard InputSpan methods against nil base address in debug builds (#795)
* [BorrowingMapProducer] Fix skip(by:) hanging at end of iterator

When a BorrowingMapProducer's Failure is not Never, skip(by:) drove a
loop over nextSpan calls. Once the base iterator was exhausted,
nextSpan kept returning an empty span (count == 0), so the counter
never decremented and the loop ran forever.

Add a guard that exits the loop when the span is empty, matching the
skip(by:) contract: return with the remaining count when the iterator
runs out of elements before n reaches 0.

Adds a regression test that builds a RigidArray from a
mapError+map chain. RigidArray.init(capacity:from:) calls _expectEnd,
which exercises exactly the exhausted-iterator code path.

Fixes #773

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: guard InputSpan methods against nil base address in debug builds

removeFirst(_:), prepend(repeating:count:), and consumePrefix(upTo:) each
call _unsafeRawAddressOfSlot(uncheckedOffset:) before checking whether
there is anything to do.  That helper calls _start(), which calls
_pointer.unsafelyUnwrapped and traps in debug builds when the base
address is nil — which happens for InputSpan(), for empty ranges handed
to consumeSubrange closures, and for SubrangeConsumer drains once the
range is exhausted.

Add an early return for the zero-work case in each method, the same
pattern that removeAll() and deinit already use.  Release builds were
unaffected in practice because unsafelyUnwrapped skips the nil check
under -O, but the behaviour is formally undefined; this fix makes both
build modes consistent and safe.

Fixes #788

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Resolve conflict

Co-authored-by: Karoy Lorentey <klorentey@apple.com>

* Prefer guard for succinct exit conditionals

This follows our preferred coding style, and also syncs this code with OutputSpan's implementation in the stdlib.

Co-authored-by: Karoy Lorentey <klorentey@apple.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2026-10-22 18:10:28 -07:00
Karoy Lorentey 885d9a7a7e Merge pull request #798 from aashish254/fix-bitarray-resizing-shift
[BitCollections] Fix BitArray.resizingShiftRight leaving stale bits
2026-10-22 18:09:51 -07:00
Karoy Lorentey 24b83c18c4 Merge pull request #799 from aashish254/fix-bitset-intersection-docs
[BitCollections] Fix BitSet intersection doc examples for Range inputs
2026-10-22 16:21:10 -07:00
Karoy Lorentey e6196f9c7a Merge pull request #797 from aashish254/cmake-add-rigidset-extras
[ContainersPreview] Add missing RigidSet+Extras.swift to CMake source list
2026-10-22 16:00:28 -07:00
SwastikTripathi 0b51424337 Merge pull request #794 from SwastikTripathi/fix/borrowing-map-skip-infinite-loop
[BorrowingMapProducer] Fix skip(by:) hanging at end of iterator
2026-10-22 11:02:24 -07:00
Aashish fc31ca4a29 [BitCollections] Fix BitSet intersection doc examples for Range inputs
The examples for `intersection(_ other: Range<Int>)` and
`formIntersection(_ other: Range<Int>)` (on both `BitSet` and
`BitSet.Counted`) showed the result of the corresponding `subtract`
example instead: intersecting `[1, 2, 3, 4]` with `-10 ..< 3` yields
`[1, 2]`, not `[3, 4]`.
2026-10-22 16:34:53 +05:45