61 Commits
Author SHA1 Message Date
Yuvraj TiwaryandClaude Fable 5.2 09d8daf0b5 [BitCollections] Don't trap in BitArray shifts when the amount is Int.min
`maskingShiftLeft(by:)`, `maskingShiftRight(by:)` and
`resizingShiftLeft(by:)` handle a negative amount by negating it and
shifting the other way, so `Int.min` trapped with an arithmetic
overflow. All three have a defined result for it: an amount of at least
`count` clears or removes every value, which is what `Int.min + 1`
already did.

Clamp the magnitude of a negative amount to `Int.max` in these three.
`resizingShiftRight(by:)` is left alone: a negative amount inserts
values there, and no array can hold as many as `Int.min` asks for.

The masking shifts had no tests. Add tests for both of them over
word-crossing counts and amounts on either side of `count`, for their
doc examples, and for the extreme amounts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 12:00:05 +05:30
SandeepVijayarao 86da5fc128 Merge pull request #846 from sandeepvijayarao09/fix-bitset-bitpattern-negative
[BitCollections] Don't keep sign extension bits in BitSet(bitPattern:)
2026-11-16 14:27:24 -08:00
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
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
Karoy Lorentey c266fe92b1 Fix typo; remove unnecessary usages of &-/&+ 2026-10-22 16:03:46 -07:00
Karoy Lorentey 701d2a9051 Fix tests to use withEvery for iteration
This gives us the necessary context data to diagnose test failures.
2026-10-22 11:09:30 -07:00
Aashish 297ffa296b [BitCollections] Fix BitArray.resizingShiftRight leaving stale bits
_resizingShiftRight(by:) copied the surviving suffix down to index 0 and
then removed `count &- amount` trailing bits instead of `amount`, so it
truncated the result to `amount` stale bits rather than keeping
`count - amount` valid ones. resizingShiftLeft(by: -n) was affected via
the same path, and the API had no test coverage at all.

Also fix the doc examples, which demonstrated the resizing shifts with
the masking shift function names (and, in one case, a result whose bit
count contradicted the documented growth by `amount`).

Add regression tests asserting parity with the documented semantics
(dropFirst / prepending false values) across word-boundary counts,
negative amounts, boundary `amount` values, and the doc examples
verbatim.
2026-10-22 15:27:56 +05:45
Karoy Lorentey d6d73d786c Merge pull request #767 from Joseph-Cursio/bitset-counted-check-bidirectional
[BitCollections] Check BitSet.Counted's BidirectionalCollection conformance
2026-10-21 15:42:41 -07:00
Joseph CursioandClaude Opus 5.5 a727e193c7 Check BitSet.Counted's BidirectionalCollection conformance
BitSet.Counted keeps its own count and forwards its index operations to
BitSet, but no test ran it through a collection checker. Run
checkBidirectionalCollection on it with the same inputs as BitSet's
test_collection_strides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 05:59:44 -05:00
Joseph CursioandClaude Opus 5.5 13c9b46f1d Check BitSet.Counted's SetAlgebra conformance
BitSet.Counted's tests declare SetAPIExtras, but it was never run
through checkSetAlgebra. Use the same models as BitSet's test. With the
isEqualSet check from the previous commit, this fails if #749's fix is
reverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:10:12 -05:00
kwy404 ea599358e6 [BitCollections] Fix BitSet.Counted.isEqualSet(to:) rejecting sequences with duplicates
The generic `isEqualSet(to: some Sequence<Int>)` overload returned false
whenever `other.underestimatedCount` exceeded `count`. A sequence with
duplicate items can be longer than the set it equals, so
`([1, 2, 3, 4] as BitSet.Counted).isEqualSet(to: [4, 1, 1, 2, 3, 3, 4] as [Int])`
returned false, contradicting the documented behavior.

Forward straight to `BitSet.isEqualSet(to:)`, which already handles
duplicates and keeps the count shortcut for unique collections.
2026-10-02 17:54:38 -03:00
Karoy Lorentey 0ec72a9532 Stop using @_spi attribute and @testable import 2026-09-29 18:32:55 -07:00
Nikhil Gupta 84e65e8b5a [BitCollections] Fix BitSet.Counted.update(with:) not maintaining the cached count
BitSet.Counted caches its size in `_count` so that `count` is O(1).
Every mutating operation is responsible for keeping that cache in sync
with the underlying bit set.

`update(with:)` forwarded straight to `BitSet.update(with:)` without
adjusting `_count`. That method inserts the member when it isn't already
present (it is defined as `insert(newMember).inserted ? nil : newMember`),
so inserting a new member this way left the cached count one too low.

The stale count is observable in a few ways:

- `count` under-reports the number of members.
- `isEmpty` is `_count == 0`, so a set that still contains members can
  report itself as empty.
- The `Collection` conformance promises `count` elements but iteration
  yields more, which breaks the standard library. `Array(set)` traps with
  "Fatal error: invalid Collection: more than 'count' elements in
  collection".

In builds with COLLECTIONS_INTERNAL_CHECKS this also violates
`_checkInvariants()`, which asserts `_count == _bits.count`.

Mirror what `insert(_:)` already does and bump `_count` when a new member
was inserted. `update(with:)` returns nil exactly in that case.

`BitSet` has had a `test_update` for this all along; `BitSet.Counted` did
not, which is how this went unnoticed. Add the matching test, following
the same combinatorial style and using `Set<Int>` as the oracle.
2026-09-25 13:02:10 +05:30
Joseph CursioandClaude Opus 5 c99e944570 Add checkSetAlgebra, a law checker for set-like types
SetAPIChecker verifies that a set-like type has the right shape: it is
a protocol with no assertions, so conforming makes the compiler check
that the API surface exists. This adds the other half — that the
operations behave as documented.

Constrained on SetAPIChecker rather than SetAlgebra, because
OrderedSet deliberately does not conform to SetAlgebra (only its
UnorderedView does, for documented reasons about order-sensitive
equality). Constraining on the stdlib protocol would exclude the type
that needs this most.

Follows the house pattern of validating the specification before the
implementation. A Set<Element> model is only as sound as Element's
Hashable conformance, so _checkSetAlgebraModels runs _checkHashable
over the model elements and verifies each model survives a round trip
through Array before any instance is judged; it returns false and the
caller stops rather than reporting defects in the wrong artefact. A
broken model and a broken implementation can agree with each other,
which fails quietly in a way a wrong implementation does not.

Per-instance: contents and count against the model, isEmpty against
count independently of it, the empty set's identity and absorption
cases, the reflexive containment predicates, and filter at both
extremes and in between.

Per-pair: the four operations against the model and again through the
Sequence-taking overloads, which are separate entry points and can
diverge from the Self-taking ones; commutativity, both absorption
laws, and symmetricDifference against its definition in terms of the
other three; and the containment predicates against the model and
against each other. A type can implement each predicate plausibly and
still have them disagree.

Contents and count are asserted separately throughout: a type that
maintains a stored count can return the right elements alongside a
stale one.

Call sites for BitSet, OrderedSet and TreeSet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 10:45:24 -05:00
Dylan Pulver 85342a6a49 [BitSet] isEqualSet(to: Range<Int>) is wrong for an empty range
`_toUInt()` returns nil whenever a bound is negative, and the guard maps that
straight to `false`. That is right for a nonempty range -- a bit set can never
hold a negative value -- but an empty range equals the empty set regardless of
where its bounds sit, so `BitSet().isEqualSet(to: -5 ..< -5)` answered false.

Five of the six `Range<Int>` predicates already handle this: isSubset and
isDisjoint clamp, isStrictSubset composes those two, and isSuperset and
isStrictSuperset test `other.isEmpty` before converting. isEqualSet was the
one that did not, which let a bit set be both a subset and a superset of a
range while reporting that it was not equal to it.
2026-09-03 02:59:42 +03: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 084be39d7e [BitSet] Add makeIterator(from:)
This enables faster iteration over subranges of a BitSet than the `Slice` type’s default indexing iterator. (Depending on the fill factor, the speedup can be as high as 4x — not insignificant.)
2026-04-21 16:28:14 -07:00
Karoy Lorentey 1c69635852 Add SPDX-License-Identifier tags 2026-03-05 19:39:24 -08:00
Karoy Lorentey d9b09ecde8 Update copyright dates 2026-03-05 19:39:20 -08:00
Ben Rimmington e2e2d00881 [BitSet] Amend return value of update(with:) method 2025-10-14 09:26:56 +01:00
Karoy Lorentey 54c65310f4 Adopt #filePath in test assertions 2025-08-17 13:23:00 -07:00
Karoy Lorentey ffa4a58bc1 Update remaining copyright notices 2024-02-02 16:20:22 -08:00
Karoy Lorentey a0da2df799 [BitArray] Update LosslessStringConvertible initializer to accept new description format 2024-01-31 19:34:36 -08:00
Karoy Lorentey ae641c3d5d [BitArray] Fix description implementation; update tests 2024-01-31 19:34:36 -08:00
Karoy Lorentey e01391e562 [BitArray] Fix logic error in toggleAll()
D’oh — lucky the test coverage caught this; unlucky that the test wasn’t deterministic, and the chances of this occurring were quite low.
2024-01-31 19:34:36 -08:00
Karoy Lorentey de8ba5d7ad [BitArray] Disable bitwise operators for now
The current family of operations is far too restrictive, and the generalization is a topic of ongoing investigation. In particular, the operator syntax seems unlikely to survive when we want to support operations over slices.

Don’t ship BitArray with API that we’ll potentially regret; instead, just leave these off for now.
2024-01-29 17:01:00 -08:00
Karoy Lorentey 09c09f0f73 Fix CustomStringConvertible/CustomDebugStringConvertible conformances
- For CustomStringConvertible, `description` should print elements using `String(reflecting:)` rather than `String(describing:)`, to avoid element output from interfering with syntactically relevant punctuation within structured list displays.
- To make this work without making displays overly verbose, make `debugDescription` mostly the same as `description`, except for escaping raw string displays when and if needed.
- Avoid printing type names in `debugDescription` — it is generally not helpful, as the type is already easily accessible elsewhere. Including it makes for overly verbose displays when the type serves as an Element of a collection.
- Avoid having `debugDescription` return the empty string — it can be confusing when such a description appears in list displays.

Resolves #301.
2023-07-06 17:25:11 -07:00
Karoy Lorentey de0f594185 [BitSet] Fix a thinko in BitSet.isEqualSet 2023-05-18 18:36:29 -07:00
Karoy Lorentey 8ca5c0367f Merge pull request #263 from lorentey/bitcollections-finalization
BitArray API refinements & additions
2023-04-10 17:32:10 -07:00
Karoy Lorentey cbab9e3737 Introduce COLLECTIONS_SINGLE_MODULE condition 2023-03-21 18:42:33 -07:00
Karoy Lorentey 3e6df33472 [BitArray] Update tests 2023-01-31 18:04:41 -08:00
Karoy Lorentey 8f7d5fd505 [SetAlgebra types] isEqual(to:) → isEqualSet(to:)
The `isEqual(to:)` methods are a bit too confusing — they implement
mathematical set comparisons (ignoring element ordering and, in the
case of the Sequence variant, even element multiplicities), so it
seems better to highlight this by putting a `Set` in the name.
2022-10-31 15:05:12 -07:00
Karoy Lorentey ba7e3927e7 [BitSet] Adjust test for updated mirror display style 2022-10-28 10:40:42 -07:00
Karoy Lorentey e3cc498060 [BitSet.Counted] Review, test, fix, and document binary set operations & predicates 2022-10-21 19:49:14 -07:00
Karoy Lorentey 1355d478af [BitSet] Review, test, extend, and document binary set operations 2022-10-21 19:49:07 -07:00
Karoy Lorentey 9cd030f21e [BitSet] Add missing Custom[Debug]StringConvertable conformances, review existing ones
Add `Custom[Debug]StringConvertible` conformance on `BitSet.Index`.
2022-10-20 17:14:52 -07:00
Karoy Lorentey 001df8e325 [BitSet] Review, test, fix, and document set relation predicates
- Update documentation
- Improve performance where possible
- Add missing test coverage where needed
2022-10-19 15:20:17 -07:00
Karoy Lorentey 291623d391 [BitSet] Implement isEqual(to:) family of functions 2022-10-19 01:40:06 -07:00
Karoy Lorentey 51a1554f89 Introduce _UniqueCollection & _SortedCollection
These marker-like protocols will allow certain
generic operations to get a performance boost
if the passed-in value happens to be guaranteed
to contain unique elements or to be sorted.

Also, review API checker protocols for Sets and
sorted collections and adjust things as needed.

BitSet gains custom implementations for min()
and max() as part of these improvements.
2022-10-19 01:40:06 -07:00
Karoy Lorentey 4604c1bc38 [test] Add SetAPIChecker protocol
This is useful for validating the API surface of set-like types,
ensuring that we haven’t forgotten to implement members that
are part of users’ baseline expectations.

To ensure maximum utility, this protocol refines neither Collection
nor SetAlgebra.
2022-10-09 13:33:23 -07:00
Karoy Lorentey 78ac2eaed7 [BitSet] Add remove(at:) implementation 2022-10-09 13:20:12 -07:00
Károly Lőrentey 141ef3c706 [BitArray] Use a platform-independent Codable encoding 2022-09-04 19:26:46 -07:00
Károly Lőrentey a137a71c6f [BitSet] Use a platform-independent Codable encoding 2022-09-04 19:26:34 -07:00
Karoy Lorentey 5fe91efeba [BitArray] Add Codable conformance 2022-08-28 17:32:46 -07:00
Karoy Lorentey 72497fe212 [BitSet] Add Codable conformance 2022-08-28 17:32:33 -07:00
Karoy Lorentey c02557f717 [BitSet] Add member subscripts 2022-08-28 16:33:50 -07:00
Karoy Lorentey b5511d3711 [BitSet] Add custom implementation for filter 2022-08-26 14:21:37 -07:00
Karoy Lorentey b9ea3f0dd3 [BitSet] Add Custom[Debug]StringConvertible, CustomReflectable conformances 2022-08-26 14:21:15 -07:00
Karoy Lorentey bae950193f [BitArray] Add Custom[Debug]StringConvertible and CustomReflectable conformances 2022-08-26 14:19:56 -07:00
Karoy Lorentey fcac09d86a [BitSet, BitArray] Add random factories 2022-08-25 22:21:34 -07:00