From 8f2e0c79c35300daa2737348fb7550dc3b5e586a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=CC=81roly=20Lo=CC=8Brentey?= Date: Mon, 10 Jan 2022 17:19:16 -0800 Subject: [PATCH] Review & update BitSet This is a work in progress; in particular, it adds a cached `count` to BitSet, which may turn out to be a bad idea. (It generates extra work for bulk operations even if the count is never needed.) I think replacing this with a cached `startIndex` might be more useful in practice. The `_UnsafeBitset` type from the OrderedCollections module is brought over as `BitSet._UnsafeHandle`. This implements an (internal-only) fixed-size bitset. `BitSet` now conforms to `SetAlgebra`. We decided against this in the initial implementation, but on reflection, it seems like the right move. (The somewhat nonsensical `insert` and `update` methods are unfortunate, but consistency is valuable.) --- .../BitCollections/BitArray/BitArray.swift | 4 +- .../BitSet/BItSet+Invariants.swift | 27 + .../BitSet+BidirectionalCollection.swift | 122 ++ .../BitSet/BitSet+Equatable.swift | 16 + .../BitSet+ExpressibleByArrayLiteral.swift | 16 + .../BitSet/BitSet+Hashable.swift | 16 + .../BitSet/BitSet+Initializers.swift | 139 +++ .../BitSet/BitSet+SetAlgebra basics.swift | 77 ++ .../BitSet+SetAlgebra conformance.swift | 12 + .../BitSet+SetAlgebra formIntersection.swift | 57 + ...t+SetAlgebra formSymmetricDifference.swift | 52 + .../BitSet/BitSet+SetAlgebra formUnion.swift | 58 + .../BitSet+SetAlgebra intersection.swift | 47 + .../BitSet/BitSet+SetAlgebra isDisjoint.swift | 51 + .../BitSet+SetAlgebra isStrictSubset.swift | 75 ++ .../BitSet+SetAlgebra isStrictSuperset.swift | 54 + .../BitSet/BitSet+SetAlgebra isSubset.swift | 61 + .../BitSet/BitSet+SetAlgebra isSuperset.swift | 46 + .../BitSet/BitSet+SetAlgebra subtract.swift | 70 ++ .../BitSet+SetAlgebra subtracting.swift | 43 + ...itSet+SetAlgebra symmetricDifference.swift | 44 + .../BitSet/BitSet+SetAlgebra union.swift | 46 + .../BitCollections/BitSet/BitSet.Index.swift | 50 + .../BitSet/BitSet._UnsafeHandle.swift | 660 ++++++++++ Sources/BitCollections/BitSet/BitSet.swift | 141 ++- .../BitSet/BitSetConformances.swift | 105 -- .../BitSet/BitSetOperations.swift | 32 - .../BitSet/BitSetSetAlgebra.swift | 217 ---- .../BitSet/Range+Utilities.swift | 36 + ...UnsafeMutableBufferPointer+Utilities.swift | 45 + Sources/BitCollections/BitSet/_Word.swift | 241 ++++ Tests/BitCollectionsTests/BitArrayTests.swift | 2 +- Tests/BitCollectionsTests/BitSetTests.swift | 1067 ++++++++++------- 33 files changed, 2863 insertions(+), 866 deletions(-) create mode 100644 Sources/BitCollections/BitSet/BItSet+Invariants.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+Equatable.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+ExpressibleByArrayLiteral.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+Hashable.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+Initializers.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra conformance.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift create mode 100644 Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift create mode 100644 Sources/BitCollections/BitSet/BitSet.Index.swift create mode 100644 Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift delete mode 100644 Sources/BitCollections/BitSet/BitSetConformances.swift delete mode 100644 Sources/BitCollections/BitSet/BitSetOperations.swift delete mode 100644 Sources/BitCollections/BitSet/BitSetSetAlgebra.swift create mode 100644 Sources/BitCollections/BitSet/Range+Utilities.swift create mode 100644 Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift create mode 100644 Sources/BitCollections/BitSet/_Word.swift diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift index 0b1a7dc7..6d4141c4 100644 --- a/Sources/BitCollections/BitArray/BitArray.swift +++ b/Sources/BitCollections/BitArray/BitArray.swift @@ -66,6 +66,8 @@ public struct BitArray: ExpressibleByArrayLiteral, Codable { excess = WORD(count%(WORD.bitWidth)) } } + + #if false /// Creates a new BitArray using a BitSet, where the indices in the BitSet become the true values in the BitArray. The resulting BitArray often contains many padded false values at the end from empty bits that fill up the word /// /// The following example creates a BitArray initialized by a BitSet @@ -82,7 +84,7 @@ public struct BitArray: ExpressibleByArrayLiteral, Codable { storage = bitSet.storage.storage excess = bitSet.storage.excess } - + #endif } diff --git a/Sources/BitCollections/BitSet/BItSet+Invariants.swift b/Sources/BitCollections/BitSet/BItSet+Invariants.swift new file mode 100644 index 00000000..fa77f054 --- /dev/null +++ b/Sources/BitCollections/BitSet/BItSet+Invariants.swift @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { +#if COLLECTIONS_INTERNAL_CHECKS + @inline(never) + @_effects(releasenone) + public func _checkInvariants() { + let actualCount = _storage.reduce(into: 0) { $0 += $1.count } + precondition(_count == actualCount, "Invalid count") + + precondition(_storage.isEmpty || !_storage.last!.isEmpty, + "Extraneous tail slot") + } +#else + @inline(__always) @inlinable + public func _checkInvariants() {} +#endif // COLLECTIONS_INTERNAL_CHECKS +} diff --git a/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift b/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift new file mode 100644 index 00000000..98522b6f --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift @@ -0,0 +1,122 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet: Sequence { + public typealias Element = Int + + @inlinable + @inline(__always) + public var underestimatedCount: Int { + return count + } + + @inlinable + public func makeIterator() -> Iterator { + return Iterator(self) + } + + public func _customContainsEquatableElement( + _ element: Element + ) -> Bool? { + guard let element = UInt(exactly: element) else { return false } + return _read { $0.contains(element) } + } + + public struct Iterator: IteratorProtocol { + internal typealias _UnsafeHandle = BitSet._UnsafeHandle + + internal let bitset: BitSet + internal var index: Int + internal var word: _Word + + @usableFromInline + internal init(_ bitset: BitSet) { + self.bitset = bitset + self.index = 0 + self.word = bitset._read { handle in + guard handle.wordCount > 0 else { return .empty } + return handle._words[0] + } + } + + @_effects(releasenone) + public mutating func next() -> Int? { + if let bit = word.next() { + let i = _UnsafeHandle.Index(word: index, bit: bit) + return Int(truncatingIfNeeded: i.value) + } + return bitset._read { handle in + while (index + 1) < handle.wordCount { + index += 1 + word = handle._words[index] + if let bit = word.next() { + let i = _UnsafeHandle.Index(word: index, bit: bit) + return Int(truncatingIfNeeded: i.value) + } + } + return nil + } + } + } +} + +extension BitSet: Collection, BidirectionalCollection { + public var isEmpty: Bool { _count == 0 } + public var count: Int { _count } + + public var startIndex: Index { + // Note: This is O(n) + Index(_position: _read { $0.startIndex }) + } + + public var endIndex: Index { + Index(_position: .init(word: _storage.count, bit: 0)) + } + + public subscript(position: Index) -> Int { + Int(position._position.value) + } + + public func index(after index: Index) -> Index { + Index(_position: _read { $0.index(after: index._position) }) + } + + public func index(before index: Index) -> Index { + Index(_position: _read { $0.index(before: index._position) }) + } + + #if false // TODO: Specialize these + public func distance(from start: Index, to end: Index) -> Int { + fatalError("Unimplemented") + } + + public func index(_ index: Index, offsetBy distance: Int) -> Index { + fatalError("Unimplemented") + } + + public func index( + _ i: Index, offsetBy distance: Int, limitedBy limit: Index + ) -> Index? { + fatalError("Unimplemented") + } + #endif + + public func _customIndexOfEquatableElement(_ element: Element) -> Index?? { + guard contains(element) else { return .some(nil) } + return Index(_value: UInt(element)) + } + + public func _customLastIndexOfEquatableElement( + _ element: Element + ) -> Index?? { + _customIndexOfEquatableElement(element) + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+Equatable.swift b/Sources/BitCollections/BitSet/BitSet+Equatable.swift new file mode 100644 index 00000000..7f1d95cc --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+Equatable.swift @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet: Equatable { + public static func ==(left: Self, right: Self) -> Bool { + left._storage == right._storage + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+ExpressibleByArrayLiteral.swift b/Sources/BitCollections/BitSet/BitSet+ExpressibleByArrayLiteral.swift new file mode 100644 index 00000000..b1d66517 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+ExpressibleByArrayLiteral.swift @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: Int...) { + self.init(elements) + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+Hashable.swift b/Sources/BitCollections/BitSet/BitSet+Hashable.swift new file mode 100644 index 00000000..16d7bee3 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+Hashable.swift @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(_storage) + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+Initializers.swift b/Sources/BitCollections/BitSet/BitSet+Initializers.swift new file mode 100644 index 00000000..01008421 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+Initializers.swift @@ -0,0 +1,139 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public init() { + self.init(_storage: [], count: 0) + } + + @inlinable + public init( + _ elements: __owned S + ) where S.Element: FixedWidthInteger { + if S.self == BitSet.self { + self = (elements as! BitSet) + return + } + self.init() + for value in elements { + self.insert(value) + } + } + + @inlinable + internal init( + _validMembersOf elements: __owned S + ) where S.Element: FixedWidthInteger { + if S.self == BitSet.self { + self = (elements as! BitSet) + return + } + if S.self == Range.self { + let r = (elements as! Range) + self.init(r._clampedToUInt()) + return + } + self.init() + for value in elements { + guard let value = UInt(exactly: value) else { continue } + _ = self._insert(value) + } + } +} + +extension BitSet { + @inlinable + public init(_ range: Range) { + guard + let lower = UInt(exactly: range.lowerBound), + let upper = UInt(exactly: range.upperBound) + else { + preconditionFailure("BitSet can only hold nonnegative integers") + } + let range = Range(uncheckedBounds: (lower, upper)) + self.init(_range: range) + } + + @usableFromInline + internal init(_range range: Range) { + _count = range.count + _storage = [] + let lower = _UnsafeHandle.Index(range.lowerBound) + let upper = _UnsafeHandle.Index(range.upperBound) + if lower.word > 0 { + _storage.append(contentsOf: repeatElement(.empty, count: lower.word)) + } + if lower.word == upper.word { + _storage.append(_Word(from: lower.bit, to: upper.bit)) + } else { + _storage.append(_Word(upTo: lower.bit).complement()) + let filledWords = upper.word &- lower.word + if filledWords > 0 { + _storage.append( + contentsOf: repeatElement(.allBits, count: filledWords &- 1)) + } + _storage.append(_Word(upTo: upper.bit)) + } + _shrink() + _checkInvariants() + } +} + +extension BitSet { + @inlinable + public init(bitPattern: I) { + let words = bitPattern.words.map { _Word($0) } + let count = words.reduce(into: 0) { $0 += $1.count } + self.init(_storage: words, count: count) + } +} + +extension BitSet { + internal init( + _combining handles: (_UnsafeHandle, _UnsafeHandle), + includingTail: Bool, + using function: (_Word, _Word) -> _Word + ) { + let w1 = handles.0._words + let w2 = handles.1._words + let capacity = ( + includingTail + ? Swift.max(w1.count, w2.count) + : Swift.min(w1.count, w2.count)) + var c = 0 + _storage = Array(unsafeUninitializedCapacity: capacity) { buffer, count in + let sharedCount = Swift.min(w1.count, w2.count) + for w in 0 ..< sharedCount { + buffer._initialize(at: w, to: function(w1[w], w2[w])) + } + if includingTail { + if w1.count < w2.count { + for w in w1.count ..< w2.count { + buffer._initialize(at: w, to: function(_Word.empty, w2[w])) + } + } else { + for w in w2.count ..< w1.count { + buffer._initialize(at: w, to: function(w1[w], _Word.empty)) + } + } + } + // Adjust the word count based on results. + count = capacity + while count > 0, buffer[count - 1].isEmpty { + count -= 1 + } + // Set the number of set bits. + c = buffer.reduce(into: 0) { $0 += $1.count } + } + _count = c + _checkInvariants() + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift new file mode 100644 index 00000000..af423fce --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public func contains(_ member: Int) -> Bool { + // Note: the generic overload over `FixedWidthInteger` below does not shadow + // the default `contains` implementation from Sequence, so we provide this + // overload that's dedicated to `Int`, the element type. + // + // `BitSet` does customize `_customContainsEquatableElement` so we'd get + // an efficient implementation even without this, but it seems like a good + // idea to make things explicit. + guard let value = UInt(exactly: member) else { return false } + return _contains(value) + } + + @inlinable + public func contains(_ member: I) -> Bool { + guard let value = UInt(exactly: member) else { return false } + return _contains(value) + } + + @usableFromInline + internal func _contains(_ member: UInt) -> Bool { + _read { $0.contains(member) } + } + + @inlinable + @discardableResult + public mutating func insert( + _ newMember: I + ) -> (inserted: Bool, memberAfterInsert: I) { + guard let i = UInt(exactly: newMember) else { + preconditionFailure("BitSet can only hold nonnegative integers") + } + return (_insert(i), newMember) + } + + @usableFromInline + internal mutating func _insert( + _ newMember: UInt + ) -> Bool { + _ensureCapacity(forValue: newMember) + return _update { $0.insert(newMember) } + } + + @discardableResult + public mutating func update( + with newMember: I + ) -> I? { + insert(newMember).inserted ? newMember : nil + } + + @discardableResult + public mutating func remove( + _ member: I + ) -> I? { + guard let m = UInt(exactly: member) else { return nil } + return _remove(m) ? member : nil + } + + @usableFromInline + internal mutating func _remove(_ member: UInt) -> Bool { + _updateThenShrink { handle, shrink in + shrink = handle.remove(member) + return shrink + } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra conformance.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra conformance.swift new file mode 100644 index 00000000..80e6a627 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra conformance.swift @@ -0,0 +1,12 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet: SetAlgebra {} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift new file mode 100644 index 00000000..535960b8 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift @@ -0,0 +1,57 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public mutating func formIntersection(_ other: Self) { + other._read { source in + if source.wordCount < _storage.count { + self._storage.removeLast(_storage.count - source.wordCount) + } + _updateThenShrink { target, shrink in + target.combineSharedPrefix( + with: source, using: { $0.formIntersection($1) }) + } + } + } + + @inlinable + public mutating func formIntersection( + _ other: __owned S + ) where S.Element: FixedWidthInteger { + if S.self == Range.self { + formIntersection(other as! Range) + return + } + formIntersection(BitSet(_validMembersOf: other)) + } + + @inlinable + public mutating func formIntersection( + _ other: Range + ) { + _formIntersection(other._clampedToUInt()) + } + + @usableFromInline + internal mutating func _formIntersection(_ other: Range) { + guard let last = other.last else { + self = [] + return + } + let lastWord = _UnsafeHandle.Index(last).word + if _storage.count - lastWord - 1 > 0 { + _storage.removeLast(_storage.count - lastWord - 1) + } + _updateThenShrink { handle, shrink in + handle.formIntersection(other) + } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift new file mode 100644 index 00000000..9efdbab6 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift @@ -0,0 +1,52 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public mutating func formSymmetricDifference(_ other: __owned Self) { + _ensureCapacity(limit: other._capacity) + _updateThenShrink { target, shrink in + other._read { source in + target.combineSharedPrefix( + with: source, using: { $0.formSymmetricDifference($1) }) + } + } + } + + @inlinable + public mutating func formSymmetricDifference( + _ other: __owned S + ) where S.Element: FixedWidthInteger { + if S.self == Range.self { + formSymmetricDifference(other as! Range) + return + } + formSymmetricDifference(BitSet(other)) + } + + @inlinable + public mutating func formSymmetricDifference( + _ other: Range + ) { + guard let other = other._toUInt() else { + preconditionFailure("BitSet can only hold nonnegative integers") + } + _formSymmetricDifference(other) + } + + @usableFromInline + internal mutating func _formSymmetricDifference(_ other: Range) { + guard !other.isEmpty else { return } + _ensureCapacity(limit: other.upperBound) + _updateThenShrink { handle, shrink in + handle.formSymmetricDifference(other) + } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift new file mode 100644 index 00000000..b6c4904a --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public mutating func formUnion(_ other: __owned Self) { + _ensureCapacity(limit: other._capacity) + _update { target in + other._read { source in + target.combineSharedPrefix(with: source) { $0.formUnion($1) } + } + } + } + + @inlinable + public mutating func formUnion( + _ other: __owned S + ) where S.Element: FixedWidthInteger { + if S.self == BitSet.self { + formUnion(other as! BitSet) + return + } + if S.self == Range.self { + formUnion(other as! Range) + return + } + for value in other { + self.insert(value) + } + } + + @inlinable + public mutating func formUnion( + _ other: Range + ) { + guard let other = other._toUInt() else { + preconditionFailure("BitSet can only hold nonnegative integers") + } + _formUnion(other) + } + + + @usableFromInline + internal mutating func _formUnion(_ other: Range) { + guard !other.isEmpty else { return } + _ensureCapacity(limit: other.upperBound) + _update { handle in + handle.formUnion(other) + } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift new file mode 100644 index 00000000..bf5e4e1a --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift @@ -0,0 +1,47 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public __consuming func intersection(_ other: Self) -> Self { + self._read { first in + other._read { second in + Self( + _combining: (first, second), + includingTail: false, + using: { $0.intersection($1) }) + } + } + } + + @inlinable + public __consuming func intersection( + _ other: __owned S + ) -> Self + where S.Element: FixedWidthInteger + { + if S.self == BitSet.self { + return intersection(other as! BitSet) + } + if S.self == Range.self { + return intersection(other as! Range) + } + return intersection(BitSet(_validMembersOf: other)) + } + + @inlinable + public __consuming func intersection( + _ other: Range + ) -> Self { + var result = self + result.formIntersection(other) + return result + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift new file mode 100644 index 00000000..9a44e073 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift @@ -0,0 +1,51 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public func isDisjoint(with other: Self) -> Bool { + self._read { first in + other._read { second in + let w1 = first._words + let w2 = second._words + for i in 0 ..< Swift.min(w1.count, w2.count) { + if !w1[i].intersection(w2[i]).isEmpty { return false } + } + return true + } + } + } + + @inlinable + public func isDisjoint(with other: S) -> Bool + where S.Element: FixedWidthInteger + { + if S.self == BitSet.self { + return self.isDisjoint(with: other as! BitSet) + } + if S.self == Range.self { + return self.isDisjoint(with: other as! Range) + } + for value in other { + guard !contains(value) else { return false } + } + return true + } + + @inlinable + public func isDisjoint(with other: Range) -> Bool { + _isDisjoint(with: other._clampedToUInt()) + } + + @usableFromInline + internal func _isDisjoint(with other: Range) -> Bool { + _read { $0.isDisjoint(with: other) } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift new file mode 100644 index 00000000..a88982ac --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift @@ -0,0 +1,75 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public func isStrictSubset(of other: Self) -> Bool { + self._read { first in + other._read { second in + let w1 = first._words + let w2 = second._words + if first.count >= second.count || w1.count > w2.count { + return false + } + var strict = w1.count < w2.count + for i in 0 ..< w1.count { + if !w1[i].subtracting(w2[i]).isEmpty { + return false + } + strict = strict || w1[i] != w2[i] + } + return strict + } + } + } + + @inlinable + public func isStrictSubset(of other: S) -> Bool + where S.Element: FixedWidthInteger + { + if S.self == BitSet.self { + return isStrictSubset(of: other as! BitSet) + } + if S.self == Range.self { + return isStrictSubset(of: other as! Range) + } + + if isEmpty { + var it = other.makeIterator() + return it.next() != nil + } + + return _UnsafeHandle.withTemporaryBitset( + wordCount: _storage.count + ) { seen in + var strict = false + var it = other.makeIterator() + while let i = it.next() { + guard self.contains(i) else { + strict = true + continue + } + if seen.insert(UInt(i)), seen._count == self._count { + while !strict, let i = it.next() { + strict = !self.contains(i) + } + return strict + } + } + assert(seen._count < self._count) + return false + } + } + + @inlinable + public func isStrictSubset(of other: Range) -> Bool { + isSubset(of: other) && !isSuperset(of: other) + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift new file mode 100644 index 00000000..cab04d56 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public func isStrictSuperset(of other: Self) -> Bool { + other.isStrictSubset(of: self) + } + + @inlinable + public func isStrictSuperset(of other: S) -> Bool + where S.Element: FixedWidthInteger + { + guard !isEmpty else { return false } + if S.self == BitSet.self { + return isStrictSuperset(of: other as! BitSet) + } + if S.self == Range.self { + return isStrictSuperset(of: other as! Range) + } + return _UnsafeHandle.withTemporaryBitset( + wordCount: _storage.count + ) { seen in + for i in other { + guard let i = UInt(exactly: i) else { return false } + if !contains(i) { return false } + seen.insert(i) + } + return seen._count < self._count + } + } + + @inlinable + public func isStrictSuperset( + of other: Range + ) -> Bool { + if other.isEmpty { return !isEmpty } + if isEmpty { return false } + guard let r = other._toUInt() else { return false } + return _isStrictSuperset(of: r) + } + + @usableFromInline + internal func _isStrictSuperset(of other: Range) -> Bool { + _read { $0.isSuperset(of: other) && !$0.isSubset(of: other) } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift new file mode 100644 index 00000000..f7c552aa --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public func isSubset(of other: Self) -> Bool { + self._read { first in + other._read { second in + let w1 = first._words + let w2 = second._words + if first.count > second.count || w1.count > w2.count { + return false + } + for i in 0 ..< w1.count { + if !w1[i].subtracting(w2[i]).isEmpty { + return false + } + } + return true + } + } + } + + @inlinable + public func isSubset(of other: S) -> Bool + where S.Element: FixedWidthInteger + { + if S.self == BitSet.self { + return self.isSubset(of: other as! BitSet) + } + if S.self == Range.self { + return self.isSubset(of: other as! Range) + } + guard !isEmpty else { return true } + var t = self + for i in other { + guard let i = UInt(exactly: i) else { continue } + if t.remove(i) != nil, t.isEmpty { return true } + } + assert(!t.isEmpty) + return false + } + + @inlinable + public func isSubset(of other: Range) -> Bool { + guard !isEmpty else { return true } + return _isSubset(of: other._clampedToUInt()) + } + + @usableFromInline + internal func _isSubset(of other: Range) -> Bool { + _read { $0.isSubset(of: other) } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift new file mode 100644 index 00000000..55512b41 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public func isSuperset(of other: Self) -> Bool { + other.isSubset(of: self) + } + + @inlinable + public func isSuperset(of other: S) -> Bool + where S.Element: FixedWidthInteger + { + if S.self == BitSet.self { + return self.isSuperset(of: other as! BitSet) + } + if S.self == Range.self { + return self.isSuperset(of: other as! Range) + } + for i in other { + guard let i = UInt(exactly: i) else { return false } + if !contains(i) { return false } + } + return true + } + + @inlinable + public func isSuperset(of other: Range) -> Bool { + if other.isEmpty { return true } + if isEmpty { return false } + guard let r = other._toUInt() else { return false } + return _isSuperset(of: r) + } + + @usableFromInline + internal func _isSuperset(of other: Range) -> Bool { + _read { $0.isSuperset(of: other) } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift new file mode 100644 index 00000000..f5de56e3 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift @@ -0,0 +1,70 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public mutating func subtract(_ other: Self) { + _updateThenShrink { target, shrink in + other._read { source in + target.combineSharedPrefix( + with: source, + using: { $0.subtract($1) } + ) + } + } + } + + @inlinable + public mutating func subtract( + _ other: __owned S + ) where S.Element: FixedWidthInteger { + if S.self == BitSet.self { + self.subtract(other as! BitSet) + return + } + if S.self == Range.self { + self.subtract(other as! Range) + return + } + var it = other.makeIterator() + _subtract { + while let value = it.next() { + if let value = UInt(exactly: value) { + return value + } + } + return nil + } + } + + @usableFromInline + internal mutating func _subtract(_ next: () -> UInt?) { + _updateThenShrink { handle, shrink in + while let value = next() { + handle.remove(value) + } + } + } + + @inlinable + public mutating func subtract( + _ other: Range + ) { + _subtract(other._clampedToUInt()) + } + + @usableFromInline + internal mutating func _subtract(_ other: Range) { + guard !other.isEmpty else { return } + _updateThenShrink { handle, shrink in + handle.subtract(other) + } + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift new file mode 100644 index 00000000..54292235 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift @@ -0,0 +1,43 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public __consuming func subtracting(_ other: Self) -> Self { + self._read { first in + other._read { second in + Self( + _combining: (first, second), + includingTail: true, + using: { $0.subtracting($1) }) + } + } + } + + @inlinable + public __consuming func subtracting( + _ other: __owned S + ) -> Self + where S.Element: FixedWidthInteger + { + var result = self + result.subtract(other) + return result + } + + @inlinable + public __consuming func subtracting( + _ other: Range + ) -> Self { + var result = self + result.subtract(other) + return result + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift new file mode 100644 index 00000000..05bb8cb8 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift @@ -0,0 +1,44 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public __consuming func symmetricDifference(_ other: __owned Self) -> Self { + self._read { first in + other._read { second in + Self( + _combining: (first, second), + includingTail: true, + using: { $0.symmetricDifference($1) }) + } + } + } + + @inlinable + public __consuming func symmetricDifference( + _ other: __owned S + ) -> Self + where S.Element: FixedWidthInteger + { + if S.self == Range.self { + return symmetricDifference(other as! Range) + } + return symmetricDifference(BitSet(other)) + } + + @inlinable + public __consuming func symmetricDifference( + _ other: Range + ) -> Self { + var result = self + result.formSymmetricDifference(other) + return result + } +} diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift new file mode 100644 index 00000000..0a0e29be --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + public __consuming func union(_ other: __owned Self) -> Self { + self._read { first in + other._read { second in + Self( + _combining: (first, second), + includingTail: true, + using: { $0.union($1) }) + } + } + } + + @inlinable + public __consuming func union( + _ other: __owned S + ) -> Self + where S.Element: FixedWidthInteger + { + if S.self == BitSet.self { + return union(other as! BitSet) + } + var result = self + result.formUnion(other) + return result + } + + @inlinable + public __consuming func union( + _ other: Range + ) -> Self { + var result = self + result.formUnion(other) + return result + } +} diff --git a/Sources/BitCollections/BitSet/BitSet.Index.swift b/Sources/BitCollections/BitSet/BitSet.Index.swift new file mode 100644 index 00000000..76c3701c --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet.Index.swift @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + @frozen + public struct Index { + @usableFromInline + var _value: UInt + + @inlinable + internal init(_value: UInt) { + self._value = _value + } + + @inlinable + internal init(_position: _UnsafeHandle.Index) { + self._value = _position.value + } + + @inline(__always) + internal var _position: _UnsafeHandle.Index { + _UnsafeHandle.Index(_value) + } + } +} + +extension BitSet.Index: Comparable, Hashable { + @inlinable + public static func ==(left: Self, right: Self) -> Bool { + left._value == right._value + } + + @inlinable + public static func < (left: Self, right: Self) -> Bool { + left._value < right._value + } + + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(_value) + } +} diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift new file mode 100644 index 00000000..cf750f87 --- /dev/null +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -0,0 +1,660 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension BitSet { + /// An unsafe-unowned bitset view over `UInt` storage, providing bit set + /// primitives. + @usableFromInline + @frozen + internal struct _UnsafeHandle { + /// An unsafe-unowned storage view. + @usableFromInline + internal let _words: UnsafeBufferPointer<_Word> + + /// The number of integers in this bit set. + @usableFromInline + internal var _count: Int + +#if DEBUG + /// True when this handle does not support table mutations. + /// (This is only checked in debug builds.) + @usableFromInline + internal let _mutable: Bool +#endif + + internal var _mutableWords: UnsafeMutableBufferPointer<_Word> { +#if DEBUG + assert(_mutable) +#endif + return UnsafeMutableBufferPointer(mutating: _words) + } + + @inlinable + @inline(__always) + internal init( + words: UnsafeBufferPointer<_Word>, + count: Int, + mutable: Bool + ) { + assert(words.baseAddress != nil) + self._words = words + self._count = count +#if DEBUG + self._mutable = mutable +#endif + } + + @inlinable + @inline(__always) + internal init( + words: UnsafeMutableBufferPointer<_Word>, + count: Int, + mutable: Bool + ) { + assert(words.baseAddress != nil) + self._words = UnsafeBufferPointer(words) + self._count = count +#if DEBUG + self._mutable = mutable +#endif + } + + @inlinable + @inline(__always) + internal init( + words: UnsafePointer<_Word>, + wordCount: Int, + count: Int, + mutable: Bool + ) { + self.init( + words: UnsafeBufferPointer(start: words, count: wordCount), + count: count, + mutable: mutable) + } + + @inlinable + @inline(__always) + internal init( + words: UnsafeMutablePointer<_Word>, + wordCount: Int, + count: Int, + mutable: Bool + ) { + self.init( + words: UnsafeBufferPointer(start: words, count: wordCount), + count: count, + mutable: mutable) + } + } +} + +extension BitSet._UnsafeHandle { + @inlinable + @inline(__always) + internal var wordCount: Int { + _words.count + } + + @_spi(Testing) + @usableFromInline + internal var _actualCount: Int { + return _words.reduce(0) { $0 + $1.count } + } +} + +extension BitSet._UnsafeHandle { + @inlinable + @inline(__always) + static func withTemporaryBitset( + capacity: UInt, + run body: (inout Self) throws -> R + ) rethrows -> R { + let wordCount = Self.wordCount(forCapacity: capacity) + return try withTemporaryBitset(wordCount: wordCount, run: body) + } + + @inlinable + @inline(__always) + static func withTemporaryBitset( + wordCount: Int, + run body: (inout Self) throws -> R + ) rethrows -> R { + var result: R? + try _withTemporaryBitset(wordCount: wordCount) { bitset in + result = try body(&bitset) + } + return result! + } + + @usableFromInline + @inline(never) + static func _withTemporaryBitset( + wordCount: Int, + run body: (inout Self) throws -> Void + ) rethrows { + try _withTemporaryUninitializedBitset(wordCount: wordCount) { handle in + handle._mutableWords.initialize(repeating: .empty) + try body(&handle) + } + } + + internal static func _withTemporaryUninitializedBitset( + wordCount: Int, + run body: (inout Self) throws -> Void + ) rethrows { + assert(wordCount >= 0) + if wordCount <= 2 { + var buffer: (_Word, _Word) = (.empty, .empty) + return try withUnsafeMutablePointer(to: &buffer) { p in + // Homogeneous tuples are layout-compatible with their component type. + let words = UnsafeMutableRawPointer(p).assumingMemoryBound(to: _Word.self) + var bitset = Self( + words: words, wordCount: wordCount, count: 0, mutable: true) + return try body(&bitset) + } + } + let words = UnsafeMutableBufferPointer<_Word>.allocate(capacity: wordCount) + defer { words.deallocate() } + var bitset = Self(words: words, count: 0, mutable: true) + return try body(&bitset) + } +} + +extension BitSet._UnsafeHandle { + @usableFromInline + @_effects(readnone) + @inline(__always) + internal static func wordCount(forCapacity capacity: UInt) -> Int { + Index(capacity + UInt(_Word.capacity) - 1).word + } + + internal var capacity: UInt { + @inline(__always) + get { + UInt(wordCount &* _Word.capacity) + } + } + + @inline(__always) + internal func isValid(_ element: UInt) -> Bool { + element < capacity + } + + @inline(__always) + internal func contains(_ element: UInt) -> Bool { + let (word, bit) = Index(element).split + guard word < wordCount else { return false } + return _words[word].contains(bit) + } + + internal mutating func updateCount() { +#if DEBUG + assert(_mutable) +#endif + _count = _words.reduce(into: 0) { $0 += $1.count } + } + + internal func emptySuffix() -> Int { + var i = wordCount - 1 + while i >= 0, _words[i].isEmpty { + i -= 1 + } + return wordCount - 1 - i + } + + @usableFromInline + @_effects(releasenone) + @discardableResult + internal mutating func insert(_ element: UInt) -> Bool { + assert(isValid(element)) + let index = Index(element) + let inserted = _mutableWords[index.word].insert(index.bit) + if inserted { _count += 1 } + return inserted + } + + @discardableResult + internal mutating func remove(_ element: UInt) -> Bool { + let index = Index(element) + if index.word >= _words.count { return false } + let removed = _mutableWords[index.word].remove(index.bit) + if removed { _count -= 1 } + return removed + } + + @usableFromInline + @_effects(releasenone) + internal mutating func clear() { + guard wordCount > 0 else { return } + _mutableWords.baseAddress?.assign( + repeating: .empty, count: wordCount) + _count = 0 + } + + @usableFromInline + @_effects(releasenone) + internal mutating func insertAll(upTo max: UInt) { + assert(max <= capacity) + guard max > 0 else { return } + let (w, b) = Index(max).split + for i in 0 ..< w { + _count += _Word.capacity - _words[i].count + _mutableWords[i] = .allBits + } + if b > 0 { + _count += _mutableWords[w].insertAll(upTo: b) + } + } + + @usableFromInline + @_effects(releasenone) + internal mutating func removeAll(upTo max: UInt) { + assert(max <= capacity) + guard max > 0 else { return } + let (w, b) = Index(max).split + for i in 0 ..< w { + _count -= _words[i].count + _mutableWords[i] = .empty + } + if b > 0 { + _count -= _mutableWords[w].removeAll(upTo: b) + } + } +} + +extension BitSet._UnsafeHandle: Sequence { + @usableFromInline + internal typealias Element = UInt + + @inlinable + @inline(__always) + internal var underestimatedCount: Int { + return count + } + + @inlinable + @inline(__always) + func makeIterator() -> Iterator { + return Iterator(self) + } + + @usableFromInline + @frozen + internal struct Iterator: IteratorProtocol { + @usableFromInline + internal typealias _UnsafeHandle = BitSet._UnsafeHandle + + @usableFromInline + internal let bitset: BitSet._UnsafeHandle + + @usableFromInline + internal var index: Int + + @usableFromInline + internal var word: _Word + + @inlinable + internal init(_ bitset: _UnsafeHandle) { + self.bitset = bitset + self.index = 0 + self.word = bitset.wordCount > 0 ? bitset._words[0] : .empty + } + + @usableFromInline + @_effects(releasenone) + internal mutating func next() -> UInt? { + if let bit = word.next() { + return Index(word: index, bit: bit).value + } + while (index + 1) < bitset.wordCount { + index += 1 + word = bitset._words[index] + if let bit = word.next() { + return Index(word: index, bit: bit).value + } + } + return nil + } + } +} + +extension BitSet._UnsafeHandle: BidirectionalCollection { + @usableFromInline + @frozen + internal struct Index: Comparable, Hashable { + @usableFromInline + internal var value: UInt + + @inlinable + internal init(_ value: UInt) { + self.value = value + } + + @inlinable + internal init(word: Int, bit: UInt) { + assert(word >= 0 && word <= Int.max / _Word.capacity) + assert(bit < _Word.capacity) + self.value = UInt(word &* _Word.capacity) &+ bit + } + + @inlinable + internal var word: Int { + // Note: We perform on UInts to get faster unsigned math (shifts). + Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity)) + } + + @inlinable + internal var bit: UInt { + // Note: We perform on UInts to get faster unsigned math (masking). + value % UInt(bitPattern: _Word.capacity) + } + + @inlinable + internal var split: (word: Int, bit: UInt) { + (word, bit) + } + + @inlinable + static func ==(left: Self, right: Self) -> Bool { + left.value == right.value + } + + @inlinable + static func <(left: Self, right: Self) -> Bool { + left.value < right.value + } + + @inlinable + func hash(into hasher: inout Hasher) { + hasher.combine(value) + } + } + + @inlinable + @inline(__always) + internal var count: Int { + _count + } + + @inlinable + @inline(__always) + internal var isEmpty: Bool { + _count == 0 + } + + @inlinable + internal var startIndex: Index { + let word = _words.firstIndex { !$0.isEmpty } + guard let word = word else { return endIndex } + return Index(word: word, bit: _words[word].firstSetBit) + } + + @inlinable + internal var endIndex: Index { + Index(word: wordCount, bit: 0) + } + + @usableFromInline + internal func index(after index: Index) -> Index { + precondition(index < endIndex, "Index out of bounds") + var word = index.word + var w = _words[word] + w.removeAll(through: index.bit) + while w.isEmpty { + word += 1 + guard word < wordCount else { + return Index(word: wordCount, bit: 0) + } + w = _words[word] + } + return Index(word: word, bit: w.firstSetBit) + } + + @usableFromInline + internal func index(before index: Index) -> Index { + precondition(index <= endIndex, "Index out of bounds") + var word = index.word + var w: _Word + if index.bit > 0 { + w = _words[word] + w.removeAll(from: index.bit) + } else { + w = .empty + } + while w.isEmpty { + word -= 1 + precondition(word >= 0, "Can't advance below startIndex") + w = _words[word] + } + return Index(word: word, bit: w.lastSetBit) + } + + @inlinable + internal subscript(position: Index) -> UInt { + position.value + } +} + +extension BitSet._UnsafeHandle { + internal mutating func combineSharedPrefix( + with other: Self, + using function: (inout _Word, _Word) -> Void + ) { + let c = Swift.min(self.wordCount, other.wordCount) + for w in 0 ..< c { + function(&self._mutableWords[w], other._words[w]) + } + updateCount() + } +} + + +extension BitSet._UnsafeHandle { + internal func count(in range: Range) -> Int { + let l = Index(Swift.min(range.lowerBound, capacity)) + let u = Index(Swift.min(range.upperBound, capacity)) + if l.word == u.word { + guard l.word < wordCount else { return 0 } + let w = _Word(from: l.bit, to: u.bit) + return _words[l.word].intersection(w).count + } + var c = 0 + c += _words[l.word] + .intersection(_Word(upTo: l.bit).complement()) + .count + for i in l.word + 1 ..< u.word { + c += _words[i].count + } + if u.word < _words.count { + c += _words[u.word] + .intersection(_Word(upTo: u.bit)) + .count + } + return c + } + + internal mutating func formUnion(_ range: Range) { +#if DEBUG + assert(_mutable) +#endif + let l = Index(range.lowerBound) + let u = Index(range.upperBound) + assert(u.value <= capacity) + + _count += Int(u.value - l.value) - count(in: range) + if l.word == u.word { + guard l.word < wordCount else { return } + let w = _Word(from: l.bit, to: u.bit) + _mutableWords[l.word].formUnion(w) + return + } + _mutableWords[l.word].formUnion(_Word(upTo: l.bit).complement()) + for w in l.word + 1 ..< u.word { + _mutableWords[w] = .allBits + } + if u.word < wordCount { + _mutableWords[u.word].formUnion(_Word(upTo: u.bit)) + } + } + + internal mutating func formIntersection(_ range: Range) { +#if DEBUG + assert(_mutable) +#endif + let l = Index(Swift.min(range.lowerBound, capacity)) + let u = Index(Swift.min(range.upperBound, capacity)) + + _count = count(in: range) + + for w in 0 ..< l.word { + _mutableWords[w] = .empty + } + + if l.word == u.word { + guard l.word < wordCount else { return } + + let w = _Word(from: l.bit, to: u.bit) + _mutableWords[l.word].formIntersection(w) + return + } + + _mutableWords[l.word].formIntersection(_Word(upTo: l.bit).complement()) + if u.word < wordCount { + _mutableWords[u.word].formIntersection(_Word(upTo: u.bit)) + _mutableWords[(u.word + 1)...] + ._rebased() + .assign(repeating: .empty) + } + } + + internal mutating func formSymmetricDifference(_ range: Range) { +#if DEBUG + assert(_mutable) +#endif + let l = Index(range.lowerBound) + let u = Index(range.upperBound) + assert(u.value <= capacity) + + _count += Int(u.value - l.value) - 2 * count(in: range) + if l.word == u.word { + guard l.word < wordCount else { return } + let w = _Word(from: l.bit, to: u.bit) + _mutableWords[l.word].formSymmetricDifference(w) + return + } + _mutableWords[l.word] + .formSymmetricDifference(_Word(upTo: l.bit).complement()) + for w in l.word + 1 ..< u.word { + _mutableWords[w].formComplement() + } + if u.word < wordCount { + _mutableWords[u.word].formSymmetricDifference(_Word(upTo: u.bit)) + } + } + + internal mutating func subtract(_ range: Range) { +#if DEBUG + assert(_mutable) +#endif + let l = Index(Swift.min(range.lowerBound, capacity)) + let u = Index(Swift.min(range.upperBound, capacity)) + + _count -= count(in: range) + if l.word == u.word { + guard l.word < wordCount else { return } + let w = _Word(from: l.bit, to: u.bit) + _mutableWords[l.word].subtract(w) + return + } + + _mutableWords[l.word].subtract(_Word(upTo: l.bit).complement()) + _mutableWords[(l.word + 1) ..< u.word] + ._rebased() + .assign(repeating: .empty) + if u.word < wordCount { + _mutableWords[u.word].subtract(_Word(upTo: u.bit)) + } + } + + internal func isDisjoint(with range: Range) -> Bool { + if self.isEmpty { return true } + let lower = Index(Swift.min(range.lowerBound, capacity)) + let upper = Index(Swift.min(range.upperBound, capacity)) + if lower == upper { return true } + + if lower.word == upper.word { + guard lower.word < wordCount else { return true } + let w = _Word(from: lower.bit, to: upper.bit) + return _words[lower.word].intersection(w).isEmpty + } + + let lw = _Word(upTo: lower.bit).complement() + guard _words[lower.word].intersection(lw).isEmpty else { return false } + + for i in lower.word + 1 ..< upper.word { + guard _words[i].isEmpty else { return false } + } + if upper.word < wordCount { + let uw = _Word(upTo: upper.bit) + guard _words[upper.word].intersection(uw).isEmpty else { return false } + } + return true + } + + internal func isSubset(of range: Range) -> Bool { + guard !range.isEmpty else { return isEmpty } + let r = range.clamped(to: 0 ..< UInt(capacity)) + guard _count <= r.count else { return false } + + let lower = Index(range.lowerBound) + let upper = Index(range.upperBound) + + for w in 0 ..< lower.word { + guard _words[w].isEmpty else { return false } + } + + let lw = _Word(upTo: lower.bit) + guard _words[lower.word].intersection(lw).isEmpty else { return false } + + guard upper.word < wordCount else { return true } + + let hw = _Word(upTo: upper.bit).complement() + guard _words[upper.word].intersection(hw).isEmpty else { return false } + + return true + } + + internal func isSuperset(of range: Range) -> Bool { + guard !range.isEmpty else { return true } + let r = range.clamped(to: 0 ..< UInt(capacity)) + guard r == range else { return false } + guard _count >= r.count else { return false } + + let lower = Index(range.lowerBound) + let upper = Index(range.upperBound) + + if lower.word == upper.word { + let w = _Word(from: lower.bit, to: upper.bit) + return _words[lower.word].intersection(w) == w + } + let lw = _Word(upTo: lower.bit).complement() + guard _words[lower.word].intersection(lw) == lw else { return false } + + for w in lower.word + 1 ..< upper.word { + guard _words[w].isFull else { return false } + } + + guard upper.word < wordCount else { return true } + let uw = _Word(upTo: upper.bit) + return _words[upper.word].intersection(uw) == uw + } +} diff --git a/Sources/BitCollections/BitSet/BitSet.swift b/Sources/BitCollections/BitSet/BitSet.swift index 24ab3ac2..11f625e5 100644 --- a/Sources/BitCollections/BitSet/BitSet.swift +++ b/Sources/BitCollections/BitSet/BitSet.swift @@ -2,65 +2,104 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// -public struct BitSet: ExpressibleByArrayLiteral, Codable { - - var storage = BitArray() - - public init() { } - - public init(_ sequence: __owned S) where S : Sequence, Int == S.Element { - for value in sequence { - while (value >= storage.count) { - storage.storage.append(0) - } - storage[value] = true - } - - storage.excess = 0 +/// A sorted collection of small nonnegative integers, implemented as an +/// uncompressed bitmap of as many bits as the value of the largest member. +/// +/// Bit sets implement `SetAlgebra` and provide efficient implementations +/// for set operations based on standard binary logic operations. +public struct BitSet { + @usableFromInline + internal var _storage: [_Word] + + @usableFromInline + internal var _count: Int + + @usableFromInline + init(_storage: [_Word], count: Int) { + self._storage = _storage + self._count = count } - - public init(arrayLiteral elements: Int...) { - for value in elements { - while (value >= storage.count) { - storage.storage.append(0) - } - storage[value] = true - } - - storage.excess = 0 - } - - public init(_ bitArray: BitArray) { - storage = bitArray - - // clean up overly excess false values - while(storage.storage.count != 0 && storage.storage[storage.storage.endIndex-1] == 0) { - storage.storage.removeLast() - } - - storage.excess = 0 - } - - public struct Index { - var bitArrayIndex: Int - internal init(bitArrayIndex: Int) { - self.bitArrayIndex = bitArrayIndex - } - } - } -extension BitSet.Index: Comparable, Hashable { - - public static func < (lhs: BitSet.Index, rhs: BitSet.Index) -> Bool { - return (lhs.bitArrayIndex < rhs.bitArrayIndex) +extension BitSet { + @inline(__always) + internal func _read( + _ body: (_UnsafeHandle) throws -> R + ) rethrows -> R { + try _storage.withUnsafeBufferPointer { words in + let handle = _UnsafeHandle(words: words, count: _count, mutable: false) + return try body(handle) + } } - + + @usableFromInline + internal var _capacity: UInt { + UInt(_storage.count) &* UInt(_Word.capacity) + } + + internal mutating func _ensureCapacity(limit capacity: UInt) { + let desired = _UnsafeHandle.wordCount(forCapacity: capacity) + guard _storage.count < desired else { return } + _storage.append( + contentsOf: repeatElement(.empty, count: desired - _storage.count)) + } + + internal mutating func _ensureCapacity(forValue value: UInt) { + let desiredWord = _UnsafeHandle.Index(value).word + guard desiredWord >= _storage.count else { return } + _storage.append( + contentsOf: + repeatElement(.empty, count: desiredWord - _storage.count + 1)) + } + + internal mutating func _shrink() { + let suffix = _read { $0.emptySuffix() } + if suffix > 0 { _storage.removeLast(suffix) } + } + + @inline(__always) + internal mutating func _update( + _ body: (inout _UnsafeHandle) throws -> R + ) rethrows -> R { + var c = _count + defer { + _count = c + _checkInvariants() + } + return try _storage.withUnsafeMutableBufferPointer { words in + var handle = _UnsafeHandle(words: words, count: c, mutable: true) + defer { + assert(c <= words.count * _Word.capacity) + c = handle.count + } + return try body(&handle) + } + } + + @inline(__always) + internal mutating func _updateThenShrink( + _ body: (_ handle: inout _UnsafeHandle, _ shrink: inout Bool) throws -> R + ) rethrows -> R { + var shrink = true + defer { + if shrink { _shrink() } + _checkInvariants() + } + return try _storage.withUnsafeMutableBufferPointer { words in + var handle = _UnsafeHandle( + words: words, count: _count, mutable: true) + defer { + _count = handle.count + } + return try body(&handle, &shrink) + } + } + } diff --git a/Sources/BitCollections/BitSet/BitSetConformances.swift b/Sources/BitCollections/BitSet/BitSetConformances.swift deleted file mode 100644 index 5d228f03..00000000 --- a/Sources/BitCollections/BitSet/BitSetConformances.swift +++ /dev/null @@ -1,105 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -extension BitSet: Collection, BidirectionalCollection { - - - public var isEmpty: Bool { return count == 0 } - - public var startIndex: Index { return _getStartIndex() } - // leaving it like this might be correct if firstTrueIndex was fast enough -- BENCHMARKS - - private func _getStartIndex() -> Index { - guard let index = storage.firstTrue() else { - return Index(bitArrayIndex: storage.endIndex) - } - - return Index(bitArrayIndex: index) - } - - public var endIndex: Index { return Index(bitArrayIndex: storage.endIndex) } - - public var count: Int { - var count = 0 - for byte in storage.storage { - count += byte.nonzeroBitCount - } - return count - } - - public subscript(position: Index) -> Int { - get { - precondition((startIndex.bitArrayIndex <= position.bitArrayIndex) && (endIndex.bitArrayIndex > position.bitArrayIndex), "Given Index is out of range") - precondition((storage[position.bitArrayIndex]), "Index passed in is invalid: does not exist in the set") - return position.bitArrayIndex - } - } - - public func index(after: Index) -> Index { - precondition((startIndex.bitArrayIndex <= after.bitArrayIndex) && (endIndex.bitArrayIndex > after.bitArrayIndex), "Given Index is out of range") - precondition((storage[after.bitArrayIndex]), "Index passed in is invalid: does not exist in the set") - precondition(after.bitArrayIndex != endIndex.bitArrayIndex, "Passed in Index is already the endIndex, and has no existing Indexes after it") - // Potentially optimizeable using leadingZeroCount/trailingZeroCount - for i in (after.bitArrayIndex+1).. Index { - precondition(before.bitArrayIndex != startIndex.bitArrayIndex, "Passed in Index is already the startIndex, and has no existing Indexes before it") - precondition((startIndex.bitArrayIndex < before.bitArrayIndex) && (endIndex.bitArrayIndex >= before.bitArrayIndex), "Given Index is out of range") - precondition( ((before == endIndex) || (storage[before.bitArrayIndex])), "Index passed in is invalid: does not exist in the set") - // Potentially optimizeable using leadingZeroCount/trailingZeroCount - - for i in stride(from: (before.bitArrayIndex-1), through: 0, by: -1) { - if (storage[i]) { - return Index(bitArrayIndex: i) - } - } - fatalError("Before not found :(") - } - - public func index(_ index: Index, offsetBy distance: Int) -> Index { - precondition((startIndex.bitArrayIndex <= index.bitArrayIndex) && (endIndex.bitArrayIndex >= index.bitArrayIndex), "Given Index is out of range") - precondition((index == endIndex) || (storage[index.bitArrayIndex]), "Index passed in is invalid: does not exist in the set") - precondition(self.count != 0, "Set is empty and has no indexes to iterate through") - // Potentially optimizeable using leadingZeroCount/trailingZeroCount - var counter = 0 - if (distance == 0) { - return index - } else if (distance > 0) { - for i in (index.bitArrayIndex+1).. Bool { - - precondition(member >= 0, "Input must be a positive number") - if (member >= storage.count) { - return false - } - return storage[member] - } - -} diff --git a/Sources/BitCollections/BitSet/BitSetSetAlgebra.swift b/Sources/BitCollections/BitSet/BitSetSetAlgebra.swift deleted file mode 100644 index fb49cde9..00000000 --- a/Sources/BitCollections/BitSet/BitSetSetAlgebra.swift +++ /dev/null @@ -1,217 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -extension BitSet: Equatable { - /// Inserts a new member into the set - /// The following examples insert a 2 into a set that already has a 2 and a set that doesn't, respectively - /// var bitSetWithTwo: BitSet = [0, 2, 4, 5] - /// var didInsert: Bool = bitSetWithTwo.insert(2) - /// print(didInsert) - /// // Prints "false" - /// print(Array(bitSetWithTwo)) - /// // Prints "[0, 2, 4, 5]" - /// - /// var bitSetWithoutTwo: BitSet = [0, 3, 4, 6] - /// didInsert = bitSetWithoutTwo.insert(2) - /// print(didInsert) - /// // Prints "true" - /// print(Array(bitSetWithoutTwo)) - /// // Prints "[0, 2, 3, 4, 6]" - /// - /// - Parameter newMember: An element to insert into the set - /// - Returns: `true` if `newMember` was not contained in the - /// set. If an element equal to `newMember` was already contained in the - /// set, the method returns `false`. Returned value is discarded without giving a warning if unused - @discardableResult - public mutating func insert(_ newMember: Int) -> Bool { - precondition(newMember >= 0, "Inserts can only be executed with a positive number. Bit sets do not hold negative values.") - if (newMember >= storage.count) { - // can also try ceil() - let padding: Double = (Double(newMember - storage.count + 1)/Double(BitArray.WORD.bitWidth)).rounded(.up) - storage.storage += Array(repeating: 0, count: Int(padding)) - } - - let returnVal = !storage[newMember] - storage[newMember] = true - return returnVal - - } - - internal mutating func _forceInsert(_ newMember: Int) { - precondition(newMember >= 0, "Inserts can only be executed with a positive number. Bit sets do not hold negative values.") - while (storage.count-1 < newMember) { - storage.storage.append(0) - } - storage[newMember] = true - } - /// Removes a member from the set - /// The following examples remove a 2 from a set that has a 2 and a set that doesn't, respectively - /// var bitSetWithTwo: BitSet = [0, 2, 4, 5] - /// var didRemove: Bool = bitSetWithTwo.remove(2) - /// print(didRemove) - /// // Prints "true" - /// print(Array(bitSetWithTwo)) - /// // Prints "[0, 4, 5]" - /// - /// var bitSetWithoutTwo: BitSet = [0, 3, 4, 6] - /// didRemove = bitSetWithoutTwo.remove(2) - /// print(didRemove) - /// // Prints "false" - /// print(Array(bitSetWithoutTwo)) - /// // Prints "[0, 3, 4, 6]" - /// - /// - Parameter member: An element to remove from the set. - /// - Returns: `true` if `member` was contained in the - /// set. If an element equal to `member` was not already contained in the - /// set, the method returns `false`. Returned value is discarded without giving a warning if unused - @discardableResult - public mutating func remove(_ member: Int) -> Bool { - precondition(member >= 0, "Removals can only be executed with a positive number. Bit sets do not hold negative values.") - if (member >= storage.endIndex) { - return false - } - - let returnVal = storage[member] - storage[member] = false - return returnVal - } - /// creates a new BitSet that is the resulting union of itself and another set - /// The union is the set of values that exist in either or both sets - /// - /// The following example creates a set that is the union of two sets - /// let firstBitSet: BitSet = [0, 2, 3, 5] - /// let secondBitSet: BitSet = [2, 4, 5, 6] - /// let resultSet = firstBitSet.union(secondBitSet) - /// print(Array(resultSet)) // prints "[0, 2, 3, 4, 5, 6]" - /// - /// - Parameter other: Another BitSet - /// - Returns: A new BitSet with the elements that are in this set or `other` or both. - public func union(_ other: BitSet) -> BitSet { - var newBitSet = self - newBitSet.formUnion(other) - return newBitSet - } - /// creates a new BitSet that is the resulting intersection of itself and another set - /// The intersection is the set of values that exist both sets - /// - /// The following example creates a set that is the union of two sets - /// let firstBitSet: BitSet = [0, 2, 3, 5] - /// let secondBitSet: BitSet = [2, 4, 5, 6] - /// let resultSet = firstBitSet.intersection(secondBitSet) - /// print(Array(resultSet)) // prints "[2, 5]" - /// - /// - Parameter other: Another BitSet - /// - Returns: A new BitSet with the elements that are both in this set and `other`. - public func intersection(_ other: BitSet) -> BitSet { - var newBitSet = self - newBitSet.formIntersection(other) - return newBitSet - } - /// creates a new BitSet that is the resulting symmetric difference of itself and another set - /// The symmetric difference is the set of values that exist one set or the other, but not both - /// - /// The following example creates a set that is the symmetric difference of two sets - /// let firstBitSet: BitSet = [0, 2, 3, 5] - /// let secondBitSet: BitSet = [2, 4, 5, 6] - /// let resultSet = firstBitSet.symmetricDifference(secondBitSet) - /// print(Array(resultSet)) // prints "[0, 3, 4, 6]" - /// - /// - Parameter other: Another BitSet - /// - Returns: A new BitSet with the elements that are in either this set or the other set, but not both - public func symmetricDifference(_ other: BitSet) -> BitSet { - var newBitSet = self - newBitSet.formSymmetricDifference(other) - return newBitSet - } - - /// mutates self to be the resulting union of itself and another set - /// The union is the set of values that exist in either or both sets - /// - /// The following example takes a set and transforms it into the union of itself and another set - /// var firstBitSet: BitSet = [0, 2, 3, 5] - /// let secondBitSet: BitSet = [2, 4, 5, 6] - /// firstBitSet.formUnion(secondBitSet) - /// print(Array(firstBitSet)) // prints "[0, 2, 3, 4, 5, 6]" - /// - /// - Parameter other: Another BitSet. `other` must be finite - public mutating func formUnion(_ other: BitSet) { - - if (other.storage.count < self.storage.count) { - for i in 0..= other.storage.storage.count) ? other.storage.storage.count : self.storage.storage.count // take the set with the smaller BitArray - - for i in 0.. self.storage.storage.count) { - for i in 0.. Bool { - return (lhs.storage == rhs.storage) - } - -} diff --git a/Sources/BitCollections/BitSet/Range+Utilities.swift b/Sources/BitCollections/BitSet/Range+Utilities.swift new file mode 100644 index 00000000..d25ea4e5 --- /dev/null +++ b/Sources/BitCollections/BitSet/Range+Utilities.swift @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Range where Bound: FixedWidthInteger { + @inlinable + internal func _clampedToUInt() -> Range { + if upperBound <= 0 { + return Range(uncheckedBounds: (0, 0)) + } + if lowerBound >= UInt.max { + return Range(uncheckedBounds: (UInt.max, UInt.max)) + } + let lower = lowerBound < 0 ? 0 : UInt(lowerBound) + let upper = upperBound > UInt.max ? UInt.max : UInt(upperBound) + return Range(uncheckedBounds: (lower, upper)) + } + + @inlinable + internal func _toUInt() -> Range? { + guard + let lower = UInt(exactly: lowerBound), + let upper = UInt(exactly: upperBound) + else { + return nil + } + return Range(uncheckedBounds: (lower: lower, upper: upper)) + } +} diff --git a/Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift b/Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift new file mode 100644 index 00000000..8c19603a --- /dev/null +++ b/Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift @@ -0,0 +1,45 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Collection { + @inlinable + @inline(__always) + internal func _rebased() -> UnsafeBufferPointer + where Self == UnsafeBufferPointer.SubSequence { + .init(rebasing: self) + } +} + +extension Collection { + @inlinable + @inline(__always) + internal func _rebased() -> UnsafeMutableBufferPointer + where Self == UnsafeMutableBufferPointer.SubSequence { + .init(rebasing: self) + } +} + +extension UnsafeMutableBufferPointer { + @inlinable + @inline(__always) + internal func _assign(from source: Self) { + assert(source.count == self.count) + if count > 0 { + baseAddress!.assign(from: source.baseAddress!, count: count) + } + } + + @inlinable + @inline(__always) + internal func _initialize(at index: Int, to value: Element) { + (baseAddress.unsafelyUnwrapped + index).initialize(to: value) + } +} diff --git a/Sources/BitCollections/BitSet/_Word.swift b/Sources/BitCollections/BitSet/_Word.swift new file mode 100644 index 00000000..7ce8d3dc --- /dev/null +++ b/Sources/BitCollections/BitSet/_Word.swift @@ -0,0 +1,241 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +@usableFromInline +@frozen +internal struct _Word { + @usableFromInline + internal var value: UInt + + @inlinable + @inline(__always) + internal init(_ value: UInt) { + self.value = value + } + + @inline(__always) + internal init(upTo bit: UInt) { + assert(bit <= _Word.capacity) + self.init((1 << bit) &- 1) + } + + @inline(__always) + internal init(from start: UInt, to end: UInt) { + assert(start <= end && end <= _Word.capacity) + self = Self(upTo: end).subtracting(Self(upTo: start)) + } +} + +extension _Word { + @inlinable + @inline(__always) + internal static var capacity: Int { + return UInt.bitWidth + } + + @inlinable + @inline(__always) + internal var count: Int { + value.nonzeroBitCount + } + + @inlinable + @inline(__always) + internal var isEmpty: Bool { + value == 0 + } + + @inlinable + @inline(__always) + internal var isFull: Bool { + value == UInt.max + } + + @inlinable + @inline(__always) + internal func contains(_ bit: UInt) -> Bool { + assert(bit >= 0 && bit < UInt.bitWidth) + return value & (1 &<< bit) != 0 + } + + @inlinable + @inline(__always) + internal var firstSetBit: UInt { + UInt(truncatingIfNeeded: value.trailingZeroBitCount) + } + + @inlinable + @inline(__always) + internal var lastSetBit: UInt { + UInt(truncatingIfNeeded: UInt.bitWidth &- 1 &- value.leadingZeroBitCount) + } + + @inlinable + @inline(__always) + @discardableResult + internal mutating func insert(_ bit: UInt) -> Bool { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + let inserted = value & mask == 0 + value |= mask + return inserted + } + + @inlinable + @inline(__always) + @discardableResult + internal mutating func remove(_ bit: UInt) -> Bool { + assert(bit < UInt.bitWidth) + let mask: UInt = 1 &<< bit + let removed = (value & mask) != 0 + value &= ~mask + return removed + } +} + +extension _Word { + @inlinable + @inline(__always) + internal mutating func insertAll(upTo bit: UInt) -> Int { + assert(bit >= 0 && bit < Self.capacity) + let mask: UInt = (1 as UInt &<< bit) &- 1 + let oldCount = (value & mask).nonzeroBitCount + value |= mask + return Int(truncatingIfNeeded: bit) - oldCount + } + + @inlinable + @inline(__always) + internal mutating func removeAll(upTo bit: UInt) -> Int { + assert(bit >= 0 && bit < Self.capacity) + let mask = UInt.max &<< bit + let removed = (value & ~mask).nonzeroBitCount + value &= mask + return removed + } + + @inlinable + @inline(__always) + internal mutating func removeAll(through bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + var mask = UInt.max &<< bit + mask &= mask &- 1 // Clear lowest nonzero bit. + value &= mask + } + + @inlinable + @inline(__always) + internal mutating func removeAll(from bit: UInt) { + assert(bit >= 0 && bit < Self.capacity) + let mask: UInt = (1 as UInt &<< bit) &- 1 + value &= mask + } +} + +extension _Word { + @inlinable + @inline(__always) + internal static var empty: Self { + Self(0) + } + + @inline(__always) + internal static var allBits: Self { + Self(UInt.max) + } +} + +// Word implements Sequence by using a copy of itself as its Iterator. +// Iteration with `next()` destroys the word's value; however, this won't cause +// problems in normal use, because `next()` is usually called on a separate +// iterator, not the original word. +extension _Word: Sequence, IteratorProtocol { + @inlinable + internal var underestimatedCount: Int { + count + } + + /// Return the index of the lowest set bit in this word, + /// and also destructively clear it. + @inlinable + internal mutating func next() -> UInt? { + guard value != 0 else { return nil } + let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount) + value &= value &- 1 // Clear lowest nonzero bit. + return bit + } +} + +extension _Word: Equatable { + @inlinable + internal static func ==(left: Self, right: Self) -> Bool { + left.value == right.value + } +} + +extension _Word: Hashable { + @inlinable + internal func hash(into hasher: inout Hasher) { + hasher.combine(value) + } +} + +extension _Word { + @inline(__always) + internal func complement() -> Self { + _Word(~self.value) + } + + @inline(__always) + internal mutating func formComplement() { + self.value = ~self.value + } + + @inline(__always) + internal func union(_ other: Self) -> Self { + _Word(self.value | other.value) + } + + @inline(__always) + internal mutating func formUnion(_ other: Self) { + self.value |= other.value + } + + @inline(__always) + internal func intersection(_ other: Self) -> Self { + _Word(self.value & other.value) + } + + @inline(__always) + internal mutating func formIntersection(_ other: Self) { + self.value &= other.value + } + + @inline(__always) + internal func symmetricDifference(_ other: Self) -> Self { + _Word(self.value ^ other.value) + } + + @inline(__always) + internal mutating func formSymmetricDifference(_ other: Self) { + self.value ^= other.value + } + + @inline(__always) + internal func subtracting(_ other: Self) -> Self { + _Word(self.value & ~other.value) + } + + @inline(__always) + internal mutating func subtract(_ other: Self) { + self.value &= ~other.value + } +} diff --git a/Tests/BitCollectionsTests/BitArrayTests.swift b/Tests/BitCollectionsTests/BitArrayTests.swift index 9179aa24..77883038 100644 --- a/Tests/BitCollectionsTests/BitArrayTests.swift +++ b/Tests/BitCollectionsTests/BitArrayTests.swift @@ -5,11 +5,11 @@ // Created by Mahanaz Atiqullah on 7/27/21. // +#if false import XCTest import _CollectionsTestSupport @testable import BitCollections -#if false final class BitArrayTest: CollectionTestCase { typealias WORD = BitArray.WORD diff --git a/Tests/BitCollectionsTests/BitSetTests.swift b/Tests/BitCollectionsTests/BitSetTests.swift index 99ae2dbd..e5a6f3f2 100644 --- a/Tests/BitCollectionsTests/BitSetTests.swift +++ b/Tests/BitCollectionsTests/BitSetTests.swift @@ -11,7 +11,7 @@ import XCTest import _CollectionsTestSupport -@testable import BitCollections +import BitCollections final class BitSetTest: CollectionTestCase { func test_empty_initializer() { @@ -53,6 +53,23 @@ final class BitSetTest: CollectionTestCase { } } + func test_bitPattern_initializer() { + let s1 = BitSet(bitPattern: 0 as UInt) + expectEqualElements(s1, []) + + let s2 = BitSet(bitPattern: 1 as UInt) + expectEqualElements(s2, [0]) + + let s3 = BitSet(bitPattern: 2 as UInt) + expectEqualElements(s3, [1]) + + let s4 = BitSet(bitPattern: 23) + expectEqualElements(s4, [0, 1, 2, 4]) + + let s5 = BitSet(bitPattern: -1) + expectEqualElements(s5, 0 ..< UInt.bitWidth) + } + func test_collection_strides() { withEvery("stride", in: [1, 2, 3, 5, 7, 8, 11, 13, 63, 79, 300]) { stride in withEvery("count", in: [0, 1, 2, 5, 10, 20, 25]) { count in @@ -141,12 +158,13 @@ final class BitSetTest: CollectionTestCase { checkHashable(equivalenceClasses: classes) } - func test_contains() { + func test_contains_Int() { withInterestingSets("input", maximum: 1000) { input in let bitset = BitSet(input) withEvery("value", in: 0 ..< 1000) { value in expectEqual(bitset.contains(value), input.contains(value)) } + expectFalse(bitset.contains(-1)) expectFalse(bitset.contains(5000)) } } @@ -157,10 +175,29 @@ final class BitSetTest: CollectionTestCase { withEvery("value", in: 0 ..< 1000) { value in expectEqual(bitset.contains(Int32(value)), input.contains(value)) } + expectFalse(bitset.contains(-1 as Int32)) expectFalse(bitset.contains(5000 as Int32)) } } + func test_contains_Sequence() { + // This exercises the `_customContainsEquatableElement` + // implementation in `BitSet`'s `Sequence` conformance. + withInterestingSets("input", maximum: 1000) { input in + func check(_ seq: S) + where S.Element == Int + { + withEvery("value", in: 0 ..< 1000) { value in + expectEqual(seq.contains(value), input.contains(value)) + } + expectFalse(seq.contains(-1)) + expectFalse(seq.contains(5000)) + } + let bitset = BitSet(input) + check(bitset) + } + } + func checkInsert(for type: F.Type, count: Int) { withEvery("seed", in: 0 ..< 10) { seed in var rng = RepeatableRandomNumberGenerator(seed: seed) @@ -230,6 +267,11 @@ final class BitSetTest: CollectionTestCase { var actual = BitSet(0 ..< count) var expected = Set(0 ..< count) let input = (0 ..< count).shuffled(using: &rng) + + if F.isSigned { + expectNil(actual.remove(F(-1))) + } + withEvery("i", in: input.indices) { i in let v = input[i] let old = actual.remove(F(v)) @@ -262,17 +304,47 @@ final class BitSetTest: CollectionTestCase { } } - func test_union_Set() { + func test_union_Sequence() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.union(b).sorted() let c = BitSet(a) let actual = c.union(b) expectEqualElements(actual, expected) + + func union(_ first: BitSet, _ second: S) -> BitSet + where S.Element: FixedWidthInteger { + first.union(second) + } + expectEqualElements(union(c, BitSet(b)), expected) } } } + func test_union_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + let a = BitSet() + + let b = a.union(0 ..< 5*step) + expectEqualElements(b, 0 ..< 5*step) + + let c = b.union(0 ..< 10*step) + expectEqualElements(c, 0 ..< 10*step) + + let d = c.union(50*step ..< 50*step) + expectEqualElements(d, 0 ..< 10*step) + + let e = d.union(20*step ..< 30*step) + expectEqualElements(e, Array(0 ..< 10*step) + Array(20*step ..< 30*step)) + + let f = e.union(5*step ..< 25*step) + expectEqualElements(f, 0 ..< 30*step) + + let g = f.union(30*step ..< 30*step) + expectEqualElements(g, 0 ..< 30*step) + } + } + func test_formUnion_Self() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in @@ -285,17 +357,51 @@ final class BitSetTest: CollectionTestCase { } } - func test_formUnion_Set() { + func test_formUnion_Sequence() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.union(b).sorted() var c = BitSet(a) c.formUnion(b) expectEqualElements(c, expected) + + func union(_ first: inout BitSet, _ second: S) + where S.Element: FixedWidthInteger { + first.formUnion(second) + } + var d = BitSet(a) + union(&d, BitSet(b)) + expectEqualElements(d, expected) + union(&d, 0 ..< 200) + expectEqualElements(d, 0 ..< 200) } } } + func test_formUnion_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + var a = BitSet() + + a.formUnion(0 ..< 5*step) + expectEqualElements(a, 0 ..< 5*step) + + a.formUnion(0 ..< 10*step) + expectEqualElements(a, 0 ..< 10*step) + + a.formUnion(50*step ..< 50*step) + expectEqualElements(a, 0 ..< 10*step) + + a.formUnion(20*step ..< 30*step) + expectEqualElements(a, Array(0 ..< 10*step) + Array(20*step ..< 30*step)) + + a.formUnion(5*step ..< 25*step) + expectEqualElements(a, 0 ..< 30*step) + + a.formUnion(30*step ..< 30*step) + expectEqualElements(a, 0 ..< 30*step) + } + } + func test_intersection_Self() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in @@ -308,17 +414,52 @@ final class BitSetTest: CollectionTestCase { } } - func test_intersection_Set() { + func test_intersection_Sequence() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.intersection(b).sorted() let c = BitSet(a) let actual = c.intersection(b) expectEqualElements(actual, expected) + + expectEqualElements(c.intersection([-100]), []) + expectEqualElements(c.intersection(-100 ..< -10), []) + + func intersection(_ first: BitSet, _ second: S) -> BitSet + where S.Element: FixedWidthInteger { + first.intersection(second) + } + let d = intersection(c, BitSet(b)) + expectEqualElements(d, expected) + let e = intersection(d, 40 ..< 60) + expectEqualElements(e, expected.filter { (40 ..< 60).contains($0) }) } } } + func test_intersection_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + let a = BitSet(0 ..< 10*step) + let b = a.intersection(10*step ..< 20*step) + expectEqualElements(b, []) + + let c = a.intersection(0 ..< 10*step) + expectEqualElements(c, 0 ..< 10*step) + + let d = a.intersection(0 ..< 5*step) + expectEqualElements(d, 0 ..< 5*step) + + let e = d.intersection(20*step ..< 20*step) + expectEqualElements(e, []) + + let f = a.intersection(-100*step ..< -10*step) + expectEqualElements(f, []) + + let g = a.intersection(-100*step ..< 10*step) + expectEqualElements(g, 0 ..< 10*step) + } + } + func test_formIntersection_Self() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in @@ -331,15 +472,70 @@ final class BitSetTest: CollectionTestCase { } } - func test_formIntersection_Set() { + func test_formIntersection_Sequence() { + func intersection(_ first: inout BitSet, _ second: S) + where S.Element: FixedWidthInteger { + first.formIntersection(second) + } + withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.intersection(b).sorted() var c = BitSet(a) c.formIntersection(b) expectEqualElements(c, expected) + + var d = BitSet(a) + intersection(&d, BitSet(b)) + expectEqualElements(d, expected) + + intersection(&d, 40 ..< 60) + expectEqualElements(d, expected.filter { (40 ..< 60).contains($0) }) } } + + var s = BitSet(0 ..< 100) + intersection(&s, [-100, -10, 0, 1, 2]) + expectEqualElements(s, [0, 1, 2]) + + intersection(&s, -100 ..< -10) + expectEqualElements(s, []) + + s = BitSet(0 ..< 100) + intersection(&s, -100 ..< 10) + expectEqualElements(s, 0 ..< 10) + } + + func test_formIntersection_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + var a = BitSet(0 ..< 10*step) + a.formIntersection(10*step ..< 20*step) + expectEqualElements(a, []) + + var b = BitSet(0 ..< 10*step) + b.formIntersection(0 ..< 10*step) + expectEqualElements(b, 0 ..< 10*step) + + var c = BitSet(0 ..< 10*step) + c.formIntersection(0 ..< 5*step) + expectEqualElements(c, 0 ..< 5*step) + + var d = BitSet(0 ..< 10*step) + d.formIntersection(20*step ..< 20*step) + expectEqualElements(d, []) + + var e = BitSet(0 ..< 100*step) + e.formIntersection(50*step ..< 100*step) + expectEqualElements(e, 50*step ..< 100*step) + + var f = BitSet(0 ..< 100*step) + f.formIntersection(-100*step ..< -10*step) + expectEqualElements(f, []) + + var g = BitSet(0 ..< 100*step) + g.formIntersection(-100*step ..< 10*step) + expectEqualElements(g, 0 ..< 10 * step) + } } func test_symmetricDifference_Self() { @@ -354,17 +550,54 @@ final class BitSetTest: CollectionTestCase { } } - func test_symmetricDifference_Set() { + func test_symmetricDifference_Sequence() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.symmetricDifference(b).sorted() let c = BitSet(a) let actual = c.symmetricDifference(b) expectEqualElements(actual, expected) + + func symmetricDifference( + _ first: BitSet, + _ second: S + ) -> BitSet + where S.Element: FixedWidthInteger { + first.symmetricDifference(second) + } + let d = symmetricDifference(c, BitSet(b)) + expectEqualElements(d, expected) + let e = symmetricDifference(d, 40 ..< 60) + let expected2 = a + .symmetricDifference(b) + .symmetricDifference(40 ..< 60) + .sorted() + expectEqualElements(e, expected2) } } } + func test_symmetricDifference_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + let a = BitSet() + + let b = a.symmetricDifference(0 ..< 10*step) + expectEqualElements(b, 0 ..< 10*step) + + let c = b.symmetricDifference(5*step ..< 10*step) + expectEqualElements(c, 0 ..< 5*step) + + let d = b.symmetricDifference(0 ..< 5*step) + expectEqualElements(d, 5*step ..< 10*step) + + let e = b.symmetricDifference(3*step ..< 7*step) + expectEqualElements(e, Array(0 ..< 3*step) + Array(7*step ..< 10*step)) + + let f = e.symmetricDifference(20*step ..< 20*step) + expectEqualElements(f, e) + } + } + func test_formSymmetricDifference_Self() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in @@ -377,17 +610,55 @@ final class BitSetTest: CollectionTestCase { } } - func test_formSymmetricDifference_Set() { + func test_formSymmetricDifference_Sequence() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.symmetricDifference(b).sorted() var c = BitSet(a) c.formSymmetricDifference(b) expectEqualElements(c, expected) + + func symmetricDifference( + _ first: inout BitSet, + _ second: S + ) where S.Element: FixedWidthInteger { + first.formSymmetricDifference(second) + } + var d = BitSet(a) + symmetricDifference(&d, BitSet(b)) + expectEqualElements(d, expected) + symmetricDifference(&d, 40 ..< 60) + let expected2 = a + .symmetricDifference(b) + .symmetricDifference(40 ..< 60) + .sorted() + expectEqualElements(d, expected2) } } } + func test_formSymmetricDifference_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + var a = BitSet() + + a.formSymmetricDifference(0 ..< 10*step) + expectEqualElements(a, 0 ..< 10*step) + + a.formSymmetricDifference(5*step ..< 10*step) + expectEqualElements(a, 0 ..< 5*step) + + a.formSymmetricDifference(0 ..< 5*step) + expectEqualElements(a, []) + + a = BitSet(0 ..< 10*step) + a.formSymmetricDifference(3*step ..< 7*step) + expectEqualElements(a, Array(0 ..< 3*step) + Array(7*step ..< 10*step)) + + a.formSymmetricDifference(20*step ..< 20*step) + expectEqualElements(a, Array(0 ..< 3*step) + Array(7*step ..< 10*step)) + } + } + func test_subtracting_Self() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in @@ -400,17 +671,56 @@ final class BitSetTest: CollectionTestCase { } } - func test_subtracting_Set() { + func test_subtracting_Sequence() { + func subtracting( + _ first: BitSet, + _ second: S + ) -> BitSet + where S.Element: FixedWidthInteger { + first.subtracting(second) + } + withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.subtracting(b).sorted() let c = BitSet(a) let actual = c.subtracting(b) expectEqualElements(actual, expected) + + expectEqual(c.subtracting([-100]), c) + expectEqual(subtracting(c, -100 ..< -10), c) + + let d = subtracting(c, BitSet(b)) + expectEqualElements(d, expected) + let e = subtracting(d, 40 ..< 60) + expectEqualElements( + e, expected.filter { !(40 ..< 60).contains($0)}) } } } + func test_subtracting_Range() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + let a = BitSet(0 ..< 10*step) + + let b = a.subtracting(9*step ..< 11*step) + expectEqualElements(b, 0 ..< 9*step) + + let c = b.subtracting(-1*step ..< 1*step) + expectEqualElements(c, 1*step ..< 9*step) + + let expected = Array(1*step ..< 4*step) + Array(6*step ..< 9*step) + let d = c.subtracting(4*step ..< 6*step) + expectEqualElements(d, expected) + + let e = d.subtracting(10*step ..< 100*step) + expectEqualElements(e, expected) + + let f = e.subtracting(-10*step ..< -1*step) + expectEqualElements(f, expected) + } + } + func test_subtract_Self() { withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in @@ -423,466 +733,305 @@ final class BitSetTest: CollectionTestCase { } } - func test_subtract_Set() { + func test_subtract_Sequence() { + func subtract( + _ first: inout BitSet, + _ second: S + ) + where S.Element: FixedWidthInteger { + first.subtract(second) + } + withInterestingSets("a", maximum: 200) { a in withInterestingSets("b", maximum: 200) { b in let expected = a.subtracting(b).sorted() var c = BitSet(a) c.subtract(b) expectEqualElements(c, expected) + + subtract(&c, [-100]) + expectEqualElements(c, expected) + + subtract(&c, -100 ..< -10) + expectEqualElements(c, expected) + + var d = BitSet(a) + subtract(&d, BitSet(b)) + expectEqualElements(d, expected) + + subtract(&d, 40 ..< 60) + expectEqualElements( + d, expected.filter { !(40 ..< 60).contains($0)}) } } } - #if false - typealias WORD = BitArray.WORD - let sizes = _getSizes(WORD.bitWidth) - - func testBitArrayInit() { - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { layout in - let bitArray = BitArray(layout) - let modifiedBitArrayAsBitSetWouldModify = _dropExcessFalses(forArr: bitArray) - let bitSet = BitSet(bitArray) - var expectedResult: [Int] = [] - - for index in 0.. BitArray{ - // remove excess bytes - var modifiedBitArray = forArr - while(modifiedBitArray.storage.count != 0 && modifiedBitArray.storage[modifiedBitArray.storage.endIndex-1] == 0) { - modifiedBitArray.storage.removeLast() - } - - modifiedBitArray.excess = 0 - - return modifiedBitArray - } - - func testExpressibleByArrayLiteralAndArrayLiteralInit() { - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { layout in - withTheirBitSetLayout("bitSetIntArray", ofLayout: layout) { bitSetIntArray in - let bitArray = BitArray(layout) - let bitSetFromBitArray = BitSet(bitArray) - let bitSetFromIntArray = BitSet(bitSetIntArray) - - XCTAssertEqual(bitSetFromBitArray, bitSetFromIntArray) // used instead of expectEqual because expectEqual was requesting more context - expectEqual(Array(bitSetFromBitArray), bitSetIntArray) - expectEqual(Array(bitSetFromIntArray), bitSetIntArray) - XCTAssertTrue(bitArray.startIndex <= bitArray.endIndex) - } - } - - // manual tests - let testBitSet1: BitSet = [] - expectEqual(Array(testBitSet1), []) - expectEqual(testBitSet1.storage.storage, []) - expectEqual(testBitSet1.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet1.count, 0) - expectEqual(testBitSet1.startIndex, BitSet.Index(bitArrayIndex: 0)) - expectEqual(testBitSet1.endIndex, BitSet.Index(bitArrayIndex: 0)) - XCTAssertTrue(testBitSet1.startIndex <= testBitSet1.endIndex) - - let testBitSet2: BitSet = [0] - expectEqual(Array(testBitSet2), [0]) - expectEqual(testBitSet2.storage.storage, [1]) - expectEqual(testBitSet2.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet2.count, 1) - expectEqual(testBitSet2.startIndex, BitSet.Index(bitArrayIndex: 0)) - expectEqual(testBitSet2.endIndex, BitSet.Index(bitArrayIndex: testBitSet2._getExpectedEndIndex())) - XCTAssertTrue(testBitSet2.startIndex < testBitSet2.endIndex) - - let testBitSet3: BitSet = [0, 1, 2, 3] - expectEqual(Array(testBitSet3), [0, 1, 2, 3]) - expectEqual(testBitSet3.storage.storage, [15]) - expectEqual(testBitSet3.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet3.count, 4) - expectEqual(testBitSet3.startIndex, BitSet.Index(bitArrayIndex: 0)) - expectEqual(testBitSet3.endIndex, BitSet.Index(bitArrayIndex: testBitSet3._getExpectedEndIndex())) - XCTAssertTrue(testBitSet3.startIndex < testBitSet3.endIndex) - - let testBitSet4: BitSet = [0, 1, 3, 5, 11] - expectEqual(Array(testBitSet4), [0, 1, 3, 5, 11]) - // expectEqual(testBitSet4.storage.storage, [43, 8]) // only for BitArray.WORD = UInt8 - expectEqual(testBitSet4.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet4.count, 5) - expectEqual(testBitSet4.startIndex, BitSet.Index(bitArrayIndex: 0)) - expectEqual(testBitSet4.endIndex, BitSet.Index(bitArrayIndex: testBitSet4._getExpectedEndIndex())) - XCTAssertTrue(testBitSet4.startIndex < testBitSet4.endIndex) - - let testBitSet5: BitSet = [1, 11, 99] - expectEqual(Array(testBitSet5), [1, 11, 99]) - // expectEqual(testBitSet5.storage.storage, [2, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]) // only for BitArray.WORD = UInt8 - expectEqual(testBitSet5.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet5.count, 3) - expectEqual(testBitSet5.startIndex, BitSet.Index(bitArrayIndex: 1)) - expectEqual(testBitSet5.endIndex, BitSet.Index(bitArrayIndex: testBitSet5._getExpectedEndIndex())) - XCTAssertTrue(testBitSet5.startIndex < testBitSet5.endIndex) - - // testing duplicate, unordered values, as well as major gaps between set elements - let testBitSet6: BitSet = [9, 11, 12, 15, 17, 32, 45, 46, 45, 47, 14, 10, 99] - expectEqual(Array(testBitSet6), [9, 10, 11, 12, 14, 15, 17, 32, 45, 46, 47, 99]) - // expectEqual(testBitSet6.storage.storage, [0, 222, 2, 0, 1, 224, 0, 0, 0, 0, 0, 0, 8]) // only for BitArray.WORD = UInt8 - expectEqual(testBitSet6.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet6.count, 12) - expectEqual(testBitSet6.startIndex, BitSet.Index(bitArrayIndex: 9)) - expectEqual(testBitSet6.endIndex, BitSet.Index(bitArrayIndex: testBitSet6._getExpectedEndIndex())) - XCTAssertTrue(testBitSet6.startIndex < testBitSet6.endIndex) - - // only for BitArray.WORD = UInt8 - /*var expectedArrayFor7: [WORD] = [8, 220, 2, 0, 1, 224, 0, 0, 0, 0, 0, 0, 8] - expectedArrayFor7 += Array(repeating: 0, count: 402) - expectedArrayFor7.append(16)*/ - - let testBitSet7: BitSet = [3, 11, 12, 12, 15, 17, 32, 45, 46, 45, 47, 14, 10, 99, 3324] - expectEqual(Array(testBitSet7), [3, 10, 11, 12, 14, 15, 17, 32, 45, 46, 47, 99, 3324]) - // expectEqual(testBitSet7.storage.storage, expectedArrayFor7) // only for BitArray.WORD = UInt8 - expectEqual(testBitSet7.storage.excess, WORD(testBitSet1.count%(WORD.bitWidth))) - expectEqual(testBitSet7.count, 13) - expectEqual(testBitSet7.startIndex, BitSet.Index(bitArrayIndex: 3)) - expectEqual(testBitSet7.endIndex, BitSet.Index(bitArrayIndex: testBitSet7._getExpectedEndIndex())) - XCTAssertTrue(testBitSet7.startIndex < testBitSet7.endIndex) - } - - func testInsertAndContains() { - var values: [Int] = [0] - for value in 1...2*WORD.bitWidth+13 { - values.append(value) - } - values.append(3320) - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { layout in - withTheirBitSetLayout("bitSet", ofLayout: layout) { bitSetIntArray in - var bitSet = BitSet(bitSetIntArray) - var intArrayCopy = bitSetIntArray - - for value in values { - if (!intArrayCopy.contains(value)) { - intArrayCopy.append(value) - expectFalse(bitSet.contains(value)) - } - bitSet.insert(value) - expectEqual(Array(bitSet), intArrayCopy.sorted()) - expectTrue(bitSet.contains(value)) - } - - expectFalse(bitSet.contains(999999)) - - } - } - - //test with empty initializer - var bitSet = BitSet() - var layout: [Int] = [] - - for value in values { - if (!layout.contains(value)) { - layout.append(value) - expectFalse(bitSet.contains(value)) - } - bitSet.insert(value) - expectEqual(Array(bitSet), layout.sorted()) - expectTrue(bitSet.contains(value)) - } - - expectFalse(bitSet.contains(999999)) - - } - - func testForceInsertAndContainsAndIsEmpty() { - var values: [Int] = [0] - for value in 1...2*WORD.bitWidth+13 { - values.append(value) - } - values.append(3320) - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { layout in - withTheirBitSetLayout("bitSet", ofLayout: layout) { bitSetIntArray in - var bitSet = BitSet(bitSetIntArray) - var intArrayCopy = bitSetIntArray - - if (intArrayCopy.isEmpty) { - expectTrue(bitSet.isEmpty) - } else { - expectFalse(bitSet.isEmpty) - } - - for value in values { - if (!intArrayCopy.contains(value)) { - intArrayCopy.append(value) - expectFalse(bitSet.contains(value)) - } - bitSet._forceInsert(value) - expectEqual(Array(bitSet), intArrayCopy.sorted()) - expectTrue(bitSet.contains(value)) - } - - expectFalse(bitSet.contains(999999)) - - } - } - - //test with empty initializer - var bitSet = BitSet() - var layout: [Int] = [] - - expectTrue(bitSet.isEmpty) - - for value in values { - if (!layout.contains(value)) { - layout.append(value) - expectFalse(bitSet.contains(value)) - } - bitSet._forceInsert(value) - expectEqual(Array(bitSet), layout.sorted()) - expectTrue(bitSet.contains(value)) - expectFalse(bitSet.isEmpty) - } - - expectFalse(bitSet.contains(999999)) - - } - - func testRemove() { - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { layout in - withTheirBitSetLayout("bitSetIntLayout", ofLayout: layout) { bitSetIntLayout in - var bitSet = BitSet(bitSetIntLayout) - var intArrayCopy = bitSetIntLayout - - // do some beyond the scope - for value in (4*WORD.bitWidth)...(7*WORD.bitWidth) { - expectFalse(bitSet.remove(value)) - } - - // trying removing one more than the last value - if (bitSetIntLayout.count != 0) { - expectFalse(bitSet.remove(bitSetIntLayout[bitSetIntLayout.endIndex-1]+1)) - } - - for _ in layout { - - guard let removing = intArrayCopy.randomElement() else { - continue - } - - expectTrue(bitSet.contains(removing)) - intArrayCopy.removeAll(where: {$0 == removing}) - expectTrue(bitSet.remove(removing)) - expectFalse(bitSet.contains(removing)) - expectEqual(Array(bitSet), intArrayCopy) - } - - expectTrue(bitSet.isEmpty) - } - } - } - - func testUnion() { - withSomeUsefulBoolArrays("boolArray1", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolLayout1 in - withTheirBitSetLayout("bitSetLayout1", ofLayout: boolLayout1) { bitSetLayout1 in - withSomeUsefulBoolArrays("boolArray2", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolArray2 in - withTheirBitSetLayout("bitSetLayout2", ofLayout: boolArray2) { bitSetLayout2 in - var bitSet1 = BitSet(bitSetLayout1) - let bitSet2 = BitSet(bitSetLayout2) - let intArrayCopy1 = bitSetLayout1 - let intArrayCopy2 = bitSetLayout2 - - var expectedResult = intArrayCopy1 - for value in intArrayCopy2 { - if (!intArrayCopy1.contains(value)) { - expectedResult.append(value) - } - } - - expectedResult = expectedResult.sorted() - - let nonFormUnion = bitSet1.union(bitSet2) - bitSet1.formUnion(bitSet2) - - expectEqual(bitSet1, nonFormUnion) - expectEqual(Array(bitSet1), expectedResult) - expectEqual(Array(nonFormUnion), expectedResult) - } - } - } - } - } - - func testIntersection() { - withSomeUsefulBoolArrays("boolArray1", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolLayout1 in - withTheirBitSetLayout("bitSetLayout1", ofLayout: boolLayout1) { bitSetLayout1 in - withSomeUsefulBoolArrays("boolArray2", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolArray2 in - withTheirBitSetLayout("bitSetLayout2", ofLayout: boolArray2) { bitSetLayout2 in - var bitSet1 = BitSet(bitSetLayout1) - let bitSet2 = BitSet(bitSetLayout2) - let intArrayCopy1 = bitSetLayout1 - let intArrayCopy2 = bitSetLayout2 - - var expectedResult: [Int] = [] - - for value in intArrayCopy1 { - if (intArrayCopy2.contains(value)) { - expectedResult.append(value) - } - } - - expectedResult = expectedResult.sorted() - - let nonFormIntersection = bitSet1.intersection(bitSet2) - bitSet1.formIntersection(bitSet2) - - expectEqual(bitSet1, nonFormIntersection) - expectEqual(Array(bitSet1), expectedResult) - expectEqual(Array(nonFormIntersection), expectedResult) - } - } - } - } - } - - func testSymmetricDifference() { - withSomeUsefulBoolArrays("boolArray1", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolLayout1 in - withTheirBitSetLayout("bitSetLayout1", ofLayout: boolLayout1) { bitSetLayout1 in - withSomeUsefulBoolArrays("boolArray2", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolArray2 in - withTheirBitSetLayout("bitSetLayout2", ofLayout: boolArray2) { bitSetLayout2 in - var bitSet1 = BitSet(bitSetLayout1) - let bitSet2 = BitSet(bitSetLayout2) - let intArrayCopy1 = bitSetLayout1 - let intArrayCopy2 = bitSetLayout2 - - var expectedResult: [Int] = [] - - for value in intArrayCopy1 { - if (!intArrayCopy2.contains(value)) { - expectedResult.append(value) - } - } - - for value in intArrayCopy2 { - if (!intArrayCopy1.contains(value)) { - expectedResult.append(value) - } - } - - expectedResult = expectedResult.sorted() - - let nonFormSymmetricDifference = bitSet1.symmetricDifference(bitSet2) - bitSet1.formSymmetricDifference(bitSet2) - - expectEqual(bitSet1, nonFormSymmetricDifference) - expectEqual(Array(bitSet1), expectedResult) - expectEqual(Array(nonFormSymmetricDifference), expectedResult) - } - } - } - } - } - - func testIndexBefore() { - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { bitArrayLayout in - withTheirBitSetLayout("bitSet", ofLayout: bitArrayLayout) { bitSetLayout in - let bitSet = BitSet(bitSetLayout) - var layoutCopy = bitSetLayout - layoutCopy.reverse() - - var secondValueIndex = 0 - for value in bitSet.reversed() { - expectEqual(value, layoutCopy[secondValueIndex]) - secondValueIndex += 1 - } - } - } - } - - func testInsertOffsetBy() { - withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: WORD.bitWidth) { boolLayout in - withTheirBitSetLayout("bitSetLayout", ofLayout: boolLayout) { bitSetLayout in - let bitSet = BitSet(bitSetLayout) - if (bitSetLayout.count != 0) { - let offset = Int.random(in: 0..= 3) { - let distanceFromStart = Int.random(in: 1.. Int { - self.storage.storage.count * WORD.bitWidth + a.subtract(9*step ..< 11*step) + expectEqualElements(a, 0 ..< 9*step) + + a.subtract(-1*step ..< 1*step) + expectEqualElements(a, 1*step ..< 9*step) + + let expected = Array(1*step ..< 4*step) + Array(6*step ..< 9*step) + a.subtract(4*step ..< 6*step) + expectEqualElements(a, expected) + + a.subtract(10*step ..< 100*step) + expectEqualElements(a, expected) + + a.subtract(-10*step ..< -1*step) + expectEqualElements(a, expected) + } + } + + func test_isSubset() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + + let inputs: [String: BitSet] = [ + "empty": BitSet(), + "a": BitSet(10*step ..< 20*step), + "b": BitSet(10*step ..< 20*step).subtracting(13*step ..< 14*step), + "c": BitSet(10*step ..< 20*step - 1), + ] + + let tests: [(range: Range, expected: Set)] = [ + ( 10*step ..< 12*step, ["empty"]), + ( 12*step ..< 18*step, ["empty"]), + ( 18*step ..< 20*step, ["empty"]), + ( 11*step ..< 21*step, ["empty"]), + ( 9*step ..< 19*step, step > 1 ? ["empty"] : ["empty", "c"]), + ( 10*step ..< 20*step, ["empty", "a", "b", "c"]), + ( 10*step ..< 20*step - 1, ["empty", "c"]), + (-10*step ..< 20*step, ["empty", "a", "b", "c"]), + ( 10*step ..< 21*step, ["empty", "a", "b", "c"]), + ( 15*step ..< 15*step, ["empty"]), + ] + + withEvery("input", in: inputs.keys) { input in + let set = inputs[input]! + expectTrue(set.isSubset(of: set)) + + withEvery("test", in: tests) { test in + let expected = test.expected.contains(input) + + func forceSequence(_ other: S) -> Bool + where S.Element: FixedWidthInteger { + set.isSubset(of: other) + } + + if test.range.lowerBound >= 0 { + expectEqual(set.isSubset(of: BitSet(test.range)), expected) + expectEqual(forceSequence(BitSet(test.range)), expected) + } + + expectEqual(set.isSubset(of: Array(test.range)), expected) + + expectEqual(set.isSubset(of: test.range), expected) + expectEqual(forceSequence(test.range), expected) + } + } + } + } + + func test_isStrictSubset() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + + let inputs: [String: BitSet] = [ + "empty": BitSet(), + "a": BitSet(10*step ..< 20*step), + "b": BitSet(10*step ..< 20*step).subtracting(13*step ..< 14*step), + "c": BitSet(10*step ..< 20*step - 1), + ] + + let tests: [(range: Range, expected: Set)] = [ + ( 10*step ..< 12*step, ["empty"]), + ( 12*step ..< 18*step, ["empty"]), + ( 18*step ..< 20*step, ["empty"]), + ( 11*step ..< 21*step, ["empty"]), + ( 9*step ..< 19*step, step > 1 ? ["empty"] : ["empty", "c"]), + ( 10*step ..< 20*step, ["empty", "b", "c"]), + ( 10*step ..< 20*step - 1, ["empty"]), + (-10*step ..< 20*step, ["empty", "a", "b", "c"]), + ( 10*step ..< 21*step, ["empty", "a", "b", "c"]), + ( 15*step ..< 15*step, []), + ] + + withEvery("input", in: inputs.keys) { input in + let set = inputs[input]! + expectFalse(set.isStrictSubset(of: set)) + + withEvery("test", in: tests) { test in + let expected = test.expected.contains(input) + + func forceSequence(_ other: S) -> Bool + where S.Element: FixedWidthInteger { + set.isStrictSubset(of: other) + } + + if test.range.lowerBound >= 0 { + expectEqual(set.isStrictSubset(of: BitSet(test.range)), expected) + expectEqual(forceSequence(BitSet(test.range)), expected) + } + + expectEqual(set.isStrictSubset(of: Array(test.range)), expected) + + expectEqual(set.isStrictSubset(of: test.range), expected) + expectEqual(forceSequence(test.range), expected) + } + } + } + } + + func test_isSuperset() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + + let inputs: [String: BitSet] = [ + "empty": BitSet(), + "a": BitSet(10*step ..< 20*step), + "b": BitSet(10*step ..< 20*step).subtracting(13*step ..< 14*step), + "c": BitSet(10*step ..< 20*step - 1), + ] + + let tests: [(range: Range, expected: Set)] = [ + ( 10*step ..< 12*step, ["a", "b", "c"]), + ( 12*step ..< 18*step, ["a", "c"]), + ( 18*step ..< 20*step, ["a", "b"]), + ( 11*step ..< 21*step, []), + ( 9*step ..< 19*step, []), + ( 10*step ..< 20*step, ["a"]), + ( 10*step ..< 20*step - 1, ["a", "c"]), + (-10*step ..< 20*step, []), + ( 10*step ..< 21*step, []), + ( 15*step ..< 15*step, ["empty", "a", "b", "c"]), + ] + + withEvery("input", in: inputs.keys) { input in + let set = inputs[input]! + expectTrue(set.isSuperset(of: set)) + + withEvery("test", in: tests) { test in + let expected = test.expected.contains(input) + + func forceSequence(_ other: S) -> Bool + where S.Element: FixedWidthInteger { + set.isSuperset(of: other) + } + + if test.range.lowerBound >= 0 { + expectEqual(set.isSuperset(of: BitSet(test.range)), expected) + expectEqual(forceSequence(BitSet(test.range)), expected) + } + + expectEqual(set.isSuperset(of: Array(test.range)), expected) + + expectEqual(set.isSuperset(of: test.range), expected) + expectEqual(forceSequence(test.range), expected) + } + } + } + } + + func test_isStrictSuperset() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + + let inputs: [String: BitSet] = [ + "empty": BitSet(), + "a": BitSet(10*step ..< 20*step), + "b": BitSet(10*step ..< 20*step).subtracting(13*step ..< 14*step), + "c": BitSet(10*step ..< 20*step - 1), + ] + + let tests: [(range: Range, expected: Set)] = [ + ( 10*step ..< 12*step, ["a", "b", "c"]), + ( 12*step ..< 18*step, ["a", "c"]), + ( 18*step ..< 20*step, ["a", "b"]), + ( 11*step ..< 21*step, []), + ( 9*step ..< 19*step, []), + ( 10*step ..< 20*step, []), + ( 10*step ..< 20*step - 1, ["a"]), + (-10*step ..< 20*step, []), + ( 10*step ..< 21*step, []), + ( 15*step ..< 15*step, ["a", "b", "c"]), + ] + + withEvery("input", in: inputs.keys) { input in + let set = inputs[input]! + expectFalse(set.isStrictSuperset(of: set)) + + withEvery("test", in: tests) { test in + let expected = test.expected.contains(input) + + func forceSequence(_ other: S) -> Bool + where S.Element: FixedWidthInteger { + set.isStrictSuperset(of: other) + } + + if test.range.lowerBound >= 0 { + expectEqual(set.isStrictSuperset(of: BitSet(test.range)), expected) + expectEqual(forceSequence(BitSet(test.range)), expected) + } + + expectEqual(set.isStrictSuperset(of: Array(test.range)), expected) + + expectEqual(set.isStrictSuperset(of: test.range), expected) + expectEqual(forceSequence(test.range), expected) + } + } + } + } + + func test_isDisjoint() { + withEvery("step", in: [1, 5, 16, 23, 24, UInt.bitWidth]) { step in + + let inputs: [String: BitSet] = [ + "empty": BitSet(), + "a": BitSet(10*step ..< 20*step), + "b": BitSet(10*step ..< 20*step).subtracting(13*step ..< 14*step), + "c": BitSet(10*step ..< 20*step - 1), + ] + + let tests: [(range: Range, expected: Set)] = [ + ( 10*step ..< 12*step, ["empty"]), + ( 12*step ..< 18*step, ["empty"]), + ( 18*step ..< 20*step, ["empty"]), + ( 11*step ..< 21*step, ["empty"]), + ( 9*step ..< 19*step, ["empty"]), + ( 10*step ..< 20*step, ["empty"]), + ( 10*step ..< 20*step - 1, ["empty"]), + (-10*step ..< 20*step, ["empty"]), + ( 10*step ..< 21*step, ["empty"]), + ( 15*step ..< 15*step, ["empty", "a", "b", "c"]), + ( 13*step ..< 14*step, ["empty", "b"]), + ( 20*step - 1 ..< 22*step, ["empty", "c"]), + ] + + withEvery("input", in: inputs.keys) { input in + let set = inputs[input]! + expectEqual(set.isDisjoint(with: set), set.isEmpty) + + withEvery("test", in: tests) { test in + let expected = test.expected.contains(input) + + func forceSequence(_ other: S) -> Bool + where S.Element: FixedWidthInteger { + set.isDisjoint(with: other) + } + + if test.range.lowerBound >= 0 { + expectEqual(set.isDisjoint(with: BitSet(test.range)), expected) + expectEqual(forceSequence(BitSet(test.range)), expected) + } + + expectEqual(set.isDisjoint(with: Array(test.range)), expected) + + expectEqual(set.isDisjoint(with: test.range), expected) + expectEqual(forceSequence(test.range), expected) + } + } + } } } -#endif