Files
swift-collections/Sources/BitCollections
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
..
2026-03-05 19:39:24 -08:00