`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.
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:)`.
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.
`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>
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.
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
- 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
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`.
`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
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>
* [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>
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.
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>
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 .
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).
* [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>
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]`.