From 85342a6a498b7acf1c2c3bf5f2df71a2b0ca8af3 Mon Sep 17 00:00:00 2001 From: Dylan Pulver Date: Thu, 3 Sep 2026 02:59:42 +0300 Subject: [PATCH] [BitSet] isEqualSet(to: Range) 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` 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. --- .../BitSet/BitSet+SetAlgebra isEqualSet.swift | 1 + Tests/BitCollectionsTests/BitSetTests.swift | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift index 9a946eb0..ea65622b 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift @@ -41,6 +41,7 @@ extension BitSet { /// - Complexity: O(min(*max*, `other.upperBound`), where *max* is the largest /// member of `self`. public func isEqualSet(to other: Range) -> Bool { + if other.isEmpty { return isEmpty } guard let other = other._toUInt() else { return false } return _read { $0.isEqualSet(to: other) } } diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index 8cd83788..44c32023 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -1135,6 +1135,21 @@ final class BitSetTest: CollectionTestCase { expectFalse(c.isEqualSet(to: i ..< (j + 1))) } } + // An empty range is equal to the empty set, whatever its bounds are. + // (Ranges with negative bounds can never round-trip through `_toUInt`.) + expectTrue(BitSet().isEqualSet(to: 0 ..< 0)) + expectTrue(BitSet().isEqualSet(to: -5 ..< -5)) + expectTrue(BitSet().isEqualSet(to: Int.min ..< Int.min)) + expectFalse(BitSet([1]).isEqualSet(to: -5 ..< -5)) + + // A nonempty range holding negative values is never equal to a bit set. + expectFalse(BitSet().isEqualSet(to: -5 ..< 0)) + expectFalse(BitSet([0, 1, 2]).isEqualSet(to: -5 ..< 3)) + expectFalse(BitSet([0, 1, 2]).isEqualSet(to: -1 ..< 3)) + + // The counted variant forwards to the same implementation. + expectTrue(BitSet.Counted().isEqualSet(to: -5 ..< -5)) + expectFalse(BitSet.Counted([0, 1, 2]).isEqualSet(to: -5 ..< 3)) } func test_isEqual_to_counted_BitSet() {