mirror of
https://github.com/apple/swift-collections
synced 2026-11-24 04:27:53 +00:00
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.