diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/BitArrayTests.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/BitArrayTests.xcscheme
deleted file mode 100644
index 6988b222..00000000
--- a/.swiftpm/xcode/xcshareddata/xcschemes/BitArrayTests.xcscheme
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/BitCollections.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/BitCollections.xcscheme
index 9dc90655..3a513fa1 100644
--- a/.swiftpm/xcode/xcshareddata/xcschemes/BitCollections.xcscheme
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/BitCollections.xcscheme
@@ -20,6 +20,20 @@
ReferencedContainer = "container:">
+
+
+
+
-
-
-
-
-
-
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ codeCoverageEnabled = "YES">
+
+
+
+
-
-
-
-
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
index 86b9f7e6..4a377fb4 100644
--- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
@@ -48,34 +48,6 @@
ReferencedContainer = "container:">
-
-
-
-
-
-
-
-
@@ -112,9 +84,37 @@
buildForAnalyzing = "NO">
+
+
+
+
+
+
+
+
@@ -124,8 +124,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
- shouldUseLaunchSchemeArgsEnv = "YES"
- codeCoverageEnabled = "YES">
+ shouldUseLaunchSchemeArgsEnv = "YES">
diff --git a/Package.swift b/Package.swift
index 4f0dc2ba..efa49544 100644
--- a/Package.swift
+++ b/Package.swift
@@ -26,7 +26,7 @@ var settings: [SwiftSetting]? = [
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
-// .define("COLLECTIONS_INTERNAL_CHECKS"),
+ .define("COLLECTIONS_INTERNAL_CHECKS"),
// Hashing collections provided by this package usually seed their hash
// function with the address of the memory location of their storage,
diff --git a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift
new file mode 100644
index 00000000..4a8c0d7d
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift
@@ -0,0 +1,84 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+ public static func |=(left: inout Self, right: Self) {
+ precondition(left.count == right.count)
+ left._update { target in
+ right._read { source in
+ for i in 0 ..< target._words.count {
+ target._mutableWords[i].formUnion(source._words[i])
+ }
+ }
+ }
+ left._checkInvariants()
+ }
+
+ public static func |(left: Self, right: Self) -> Self {
+ precondition(left.count == right.count)
+ var result = left
+ result |= right
+ return result
+ }
+
+ public static func &=(left: inout Self, right: Self) {
+ precondition(left.count == right.count)
+ left._update { target in
+ right._read { source in
+ for i in 0 ..< target._words.count {
+ target._mutableWords[i].formIntersection(source._words[i])
+ }
+ }
+ }
+ left._checkInvariants()
+ }
+
+ public static func &(left: Self, right: Self) -> Self {
+ precondition(left.count == right.count)
+ var result = left
+ result &= right
+ return result
+ }
+
+ public static func ^=(left: inout Self, right: Self) {
+ precondition(left.count == right.count)
+ left._update { target in
+ right._read { source in
+ for i in 0 ..< target._words.count {
+ target._mutableWords[i].formSymmetricDifference(source._words[i])
+ }
+ }
+ }
+ left._checkInvariants()
+ }
+
+ public static func ^(left: Self, right: Self) -> Self {
+ precondition(left.count == right.count)
+ var result = left
+ result ^= right
+ return result
+ }
+
+ public static prefix func ~(value: Self) -> Self {
+ var result = value
+ result._update { handle in
+ for i in 0 ..< handle._words.count {
+ handle._mutableWords[i].formComplement()
+ }
+ let p = _BitPosition(handle._count)
+ if p.bit > 0 {
+ handle._mutableWords[p.word].subtract(_Word(upTo: p.bit).complement())
+ }
+ }
+ result._checkInvariants()
+ return result
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift
new file mode 100644
index 00000000..0c85aec8
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift
@@ -0,0 +1,92 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+internal struct _ChunkedBitsForwardIterator {
+ internal let words: UnsafeBufferPointer<_Word>
+ internal let end: _BitPosition
+ internal var position: _BitPosition
+
+ internal init(
+ words: UnsafeBufferPointer<_Word>,
+ range: Range
+ ) {
+ assert(range.lowerBound >= 0)
+ assert(range.upperBound <= words.count * _Word.capacity)
+ self.words = words
+ self.end = _BitPosition(range.upperBound)
+ self.position = _BitPosition(range.lowerBound)
+ }
+
+ mutating func next() -> (bits: _Word, count: UInt)? {
+ guard position < end else { return nil }
+ let (w, b) = position.split
+ if w == end.word {
+ position = end
+ return (
+ bits: words[w]
+ .intersection(_Word(upTo: end.bit))
+ .shiftedDown(by: b),
+ count: end.bit - b)
+ }
+ let c = UInt(_Word.capacity) - b
+ position.value += c
+ return (bits: words[w].shiftedDown(by: b), count: c)
+ }
+}
+
+internal struct _ChunkedBitsBackwardIterator {
+ internal let words: UnsafeBufferPointer<_Word>
+ internal let start: _BitPosition
+ internal var position: _BitPosition
+
+ internal init(
+ words: UnsafeBufferPointer<_Word>,
+ range: Range
+ ) {
+ assert(range.lowerBound >= 0)
+ assert(range.upperBound <= words.count * _Word.capacity)
+ self.words = words
+ self.start = _BitPosition(range.lowerBound)
+ self.position = _BitPosition(range.upperBound)
+ }
+
+ internal mutating func next() -> (bits: _Word, count: UInt)? {
+ guard position > start else { return nil }
+ let (w, b) = position.endSplit
+ if w == start.word {
+ position = start
+ return (
+ bits: words[w]
+ .intersection(_Word(upTo: b))
+ .shiftedDown(by: start.bit),
+ count: b - start.bit)
+ }
+ let c = b
+ position.value -= c
+ return (bits: words[w].intersection(_Word(upTo: b)), count: c)
+ }
+}
+
+extension IteratorProtocol where Element == Bool {
+ mutating func _nextChunk(
+ maximumCount: UInt = UInt(_Word.capacity)
+ ) -> (bits: _Word, count: UInt) {
+ assert(maximumCount <= _Word.capacity)
+ var bits = _Word.empty
+ var c: UInt = 0
+ while let v = next() {
+ if v { bits.insert(c) }
+ c += 1
+ if c == maximumCount { break }
+ }
+ return (bits, c)
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Collection.swift b/Sources/BitCollections/BitArray/BitArray+Collection.swift
new file mode 100644
index 00000000..39dc19ec
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Collection.swift
@@ -0,0 +1,68 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray: Sequence {
+ public typealias Element = Bool
+ public typealias Iterator = IndexingIterator
+}
+
+extension BitArray: RandomAccessCollection, MutableCollection {
+ public typealias Index = Int
+ public typealias SubSequence = Slice
+ public typealias Indices = Range
+
+ @inlinable
+ public var count: Int {
+ Int(_count)
+ }
+
+ @inlinable @inline(__always)
+ public var startIndex: Int { 0 }
+
+ @inlinable @inline(__always)
+ public var endIndex: Int { count }
+
+ @inlinable @inline(__always)
+ public func index(after i: Int) -> Int { i + 1 }
+
+ @inlinable @inline(__always)
+ public func index(before i: Int) -> Int { i - 1 }
+
+ @inlinable @inline(__always)
+ public func formIndex(after i: inout Int) {
+ i += 1
+ }
+
+ @inlinable @inline(__always)
+ public func formIndex(before i: inout Int) {
+ i -= 1
+ }
+
+ @inlinable @inline(__always)
+ public func index(_ i: Int, offsetBy distance: Int) -> Int {
+ i + distance
+ }
+
+ public subscript(position: Int) -> Bool {
+ get {
+ precondition(position >= 0 && position < _count, "Index out of bounds")
+ return _read { handle in
+ handle[position]
+ }
+ }
+ set {
+ precondition(position >= 0 && position < _count, "Index out of bounds")
+ return _update { handle in
+ handle[position] = newValue
+ }
+ }
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift
new file mode 100644
index 00000000..e592e5e6
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift
@@ -0,0 +1,172 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+ internal mutating func _copy(
+ from range: Range,
+ to target: Int
+ ) {
+ _update { handle in
+ handle.copy(from: range, to: target)
+ }
+ }
+
+ internal mutating func _copy(
+ from range: Range,
+ in source: UnsafeBufferPointer<_Word>,
+ to target: Int
+ ) {
+ _update { handle in
+ handle.copy(from: range, in: source, to: target)
+ }
+ }
+
+ internal mutating func _copy(
+ from source: BitArray,
+ to target: Int
+ ) {
+ _copy(from: source[...], to: target)
+ }
+
+ internal mutating func _copy(
+ from source: BitArray.SubSequence,
+ to target: Int
+ ) {
+ let range = source._bounds
+ source.base._storage.withUnsafeBufferPointer { words in
+ self._copy(from: range, in: words, to: target)
+ }
+ }
+
+ internal mutating func _copy(
+ from source: S,
+ to range: Range
+ ) where S.Element == Bool {
+ _update { $0.copy(from: source, to: range) }
+ }
+}
+
+extension BitArray._UnsafeHandle {
+ internal mutating func _copy(
+ bits: _Word, count: UInt, to target: _BitPosition
+ ) {
+ assert(count <= _Word.capacity)
+ assert(count == _Word.capacity || bits.shiftedDown(by: count).isEmpty)
+ assert(target.value + count <= _count)
+ let start = target.split
+ let end = _BitPosition(target.value + count).endSplit
+ let words = _mutableWords
+ if start.word == end.word {
+ let mask = _Word(from: start.bit, to: end.bit)
+ words[start.word].formIntersection(mask.complement())
+ words[start.word].formUnion(bits.shiftedUp(by: start.bit))
+ return
+ }
+ assert(start.word + 1 == end.word)
+ words[start.word].formIntersection(_Word(upTo: start.bit))
+ words[start.word].formUnion(bits.shiftedUp(by: start.bit))
+ words[end.word].formIntersection(_Word(upTo: end.bit).complement())
+ words[end.word].formUnion(
+ bits.shiftedDown(by: UInt(_Word.capacity) &- start.bit))
+ }
+
+ internal mutating func copy(
+ from range: Range,
+ to target: Int
+ ) {
+ assert(
+ range.lowerBound >= 0 && range.upperBound <= self.count,
+ "Source range out of bounds")
+ copy(from: range, in: _words, to: target)
+ }
+
+ internal mutating func copy(
+ from range: Range,
+ in source: UnsafeBufferPointer<_Word>,
+ to target: Int
+ ) {
+ ensureMutable()
+ assert(
+ range.lowerBound >= 0 && range.upperBound <= source.count * _Word.capacity,
+ "Source range out of bounds")
+ assert(
+ target >= 0 && target + range.count <= count,
+ "Target out of bounds")
+ guard !range.isEmpty else { return }
+
+ func goForward() -> Bool {
+ let target = _BitPosition(target).split
+ let lowerSource = _BitPosition(range.lowerBound).split
+ let upperSource = _BitPosition(range.upperBound).endSplit
+
+
+ let targetPtr = _words._ptr(at: target.word)
+ let lowerSourcePtr = source._ptr(at: lowerSource.word)
+ let upperSourcePtr = source._ptr(at: upperSource.word)
+
+ if targetPtr < lowerSourcePtr || targetPtr > upperSourcePtr {
+ return true
+ }
+ if targetPtr == lowerSourcePtr, target.bit < lowerSource.bit {
+ return true
+ }
+ if targetPtr == upperSourcePtr, target.bit >= upperSource.bit {
+ return true
+ }
+ return false
+ }
+
+ if goForward() {
+ // Copy forward from a disjoint or following overlapping range.
+ var src = _ChunkedBitsForwardIterator(words: source, range: range)
+ var dst = _BitPosition(target)
+ while let (bits, count) = src.next() {
+ _copy(bits: bits, count: count, to: dst)
+ dst.value += count
+ }
+ assert(dst.value == target + range.count)
+ } else {
+ // Copy backward from a non-following overlapping range.
+ var src = _ChunkedBitsBackwardIterator(words: source, range: range)
+ var dst = _BitPosition(target + range.count)
+ while let (bits, count) = src.next() {
+ dst.value -= count
+ _copy(bits: bits, count: count, to: dst)
+ }
+ assert(dst.value == target)
+ }
+ }
+}
+
+extension BitArray._UnsafeHandle {
+ internal mutating func copy(
+ from source: S,
+ to range: Range
+ ) where S.Element == Bool {
+ assert(range.lowerBound >= 0 && range.upperBound <= self.count)
+ var pos = _BitPosition(range.lowerBound)
+ var it = source.makeIterator()
+ if pos.bit > 0 {
+ let (bits, count) = it._nextChunk(
+ maximumCount: UInt(_Word.capacity) - pos.bit)
+ _copy(bits: bits, count: count, to: pos)
+ pos.value += count
+ }
+ while true {
+ let (bits, count) = it._nextChunk()
+ guard count > 0 else { break }
+ assert(pos.bit == 0)
+ _copy(bits: bits, count: count, to: pos)
+ pos.value += count
+ }
+ precondition(pos.value == range.upperBound)
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Equatable.swift b/Sources/BitCollections/BitArray/BitArray+Equatable.swift
new file mode 100644
index 00000000..c228d309
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Equatable.swift
@@ -0,0 +1,17 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray: Equatable {
+ public static func ==(left: Self, right: Self) -> Bool {
+ guard left._count == right._count else { return false }
+ return left._storage == right._storage
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift b/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift
new file mode 100644
index 00000000..d8748599
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+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 BitArray: ExpressibleByArrayLiteral {
+ public init(arrayLiteral elements: Bool...) {
+ self.init(elements)
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Fill.swift b/Sources/BitCollections/BitArray/BitArray+Fill.swift
new file mode 100644
index 00000000..419a61c4
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Fill.swift
@@ -0,0 +1,26 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+ public mutating func fill(with value: Bool = true) {
+ fill(in: Range(uncheckedBounds: (0, count)), with: value)
+ }
+
+ public mutating func fill(in range: Range, with value: Bool = true) {
+ _update { handle in
+ if value {
+ handle.fill(in: range)
+ } else {
+ handle.clear(in: range)
+ }
+ }
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Hashable.swift b/Sources/BitCollections/BitArray/BitArray+Hashable.swift
new file mode 100644
index 00000000..eaa3a8d6
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Hashable.swift
@@ -0,0 +1,19 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray: Hashable {
+ public func hash(into hasher: inout Hasher) {
+ hasher.combine(_count)
+ for word in _storage {
+ hasher.combine(word)
+ }
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift
new file mode 100644
index 00000000..d9e2a0a1
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift
@@ -0,0 +1,23 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+ public init(_ set: BitSet) {
+ guard let l = set.last else { self.init(); return }
+ self.init(_storage: set._storage, count: l + 1)
+ }
+
+ public init(bitPattern value: I) {
+ let words = value.words.map { _Word($0) }
+ let count = value.bitWidth
+ self.init(_storage: words, count: count)
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Invariants.swift b/Sources/BitCollections/BitArray/BitArray+Invariants.swift
new file mode 100644
index 00000000..561e909f
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Invariants.swift
@@ -0,0 +1,28 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+#if COLLECTIONS_INTERNAL_CHECKS
+ @inline(never)
+ @_effects(releasenone)
+ public func _checkInvariants() {
+ precondition(_count <= _storage.count * _Word.capacity)
+ precondition(_count > (_storage.count - 1) * _Word.capacity)
+ let p = _BitPosition(_count).split
+ if p.bit > 0 {
+ precondition(_storage.last!.subtracting(_Word(upTo: p.bit)) == .empty)
+ }
+ }
+#else
+ @inline(__always) @inlinable
+ public func _checkInvariants() {}
+#endif // COLLECTIONS_INTERNAL_CHECKS
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift
new file mode 100644
index 00000000..d9f977c5
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift
@@ -0,0 +1,292 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray: RangeReplaceableCollection {}
+
+extension BitArray {
+ public mutating func reserveCapacity(_ n: Int) {
+ let wordCount = _Word.wordCount(forBitCount: UInt(n))
+ _storage.reserveCapacity(wordCount)
+ }
+
+ public init() {
+ self.init(_storage: [], count: 0)
+ }
+
+ public init(repeating repeatedValue: Bool, count: Int) {
+ let wordCount = _Word.wordCount(forBitCount: UInt(count))
+ var storage: [_Word] = .init(
+ repeating: repeatedValue ? .allBits : .empty, count: wordCount)
+ if repeatedValue, _BitPosition(count).bit != 0 {
+ // Clear upper bits of last word.
+ storage[wordCount - 1] = _Word(upTo: _BitPosition(count).bit)
+ }
+ self.init(_storage: storage, count: count)
+ }
+}
+
+extension BitArray {
+ @inlinable
+ public init(_ elements: S) where S.Element == Bool {
+ defer { _checkInvariants() }
+ if S.self == BitArray.self {
+ self = elements as! BitArray
+ return
+ }
+ if S.self == BitArray.SubSequence.self {
+ self.init(elements as! BitArray.SubSequence)
+ return
+ }
+ self.init()
+ self.reserveCapacity(elements.underestimatedCount)
+ self.append(contentsOf: elements)
+ }
+
+ // Specializations
+ public init(_ values: BitArray) {
+ self = values
+ }
+
+ public init(_ values: BitArray.SubSequence) {
+ let wordCount = _Word.wordCount(forBitCount: UInt(values.count))
+ let storage = Array(repeating: _Word.empty, count: wordCount)
+ self.init(_storage: storage, count: values.count)
+ self._copy(from: values, to: 0)
+ _checkInvariants()
+ }
+}
+
+extension BitArray {
+ internal mutating func _prepareForReplaceSubrange(
+ _ range: Range, replacementCount c: Int
+ ) {
+ precondition(range.lowerBound >= 0 && range.upperBound <= self.count)
+
+ let origCount = self.count
+ if range.count < c {
+ _extend(by: c - range.count)
+ }
+
+ _copy(from: range.upperBound ..< origCount, to: range.lowerBound + c)
+
+ if c < range.count {
+ _removeLast(range.count - c)
+ }
+ }
+
+ public mutating func replaceSubrange(
+ _ range: Range,
+ with newElements: __owned C
+ ) where C.Element == Bool {
+ let c = newElements.count
+ _prepareForReplaceSubrange(range, replacementCount: c)
+ if C.self == BitArray.self {
+ _copy(from: newElements as! BitArray, to: range.lowerBound)
+ } else if C.self == BitArray.SubSequence.self {
+ _copy(from: newElements as! BitArray.SubSequence, to: range.lowerBound)
+ } else {
+ _copy(from: newElements, to: range.lowerBound ..< range.lowerBound + c)
+ }
+ _checkInvariants()
+ }
+
+ public mutating func replaceSubrange(
+ _ range: Range,
+ with newElements: __owned BitArray
+ ) {
+ replaceSubrange(range, with: newElements[...])
+ }
+
+ public mutating func replaceSubrange(
+ _ range: Range,
+ with newElements: __owned BitArray.SubSequence
+ ) {
+ _prepareForReplaceSubrange(range, replacementCount: newElements.count)
+ _copy(from: newElements, to: range.lowerBound)
+ _checkInvariants()
+ }
+}
+
+extension BitArray {
+ public mutating func append(_ newElement: Bool) {
+ let (word, bit) = _BitPosition(_count).split
+ if bit == 0 {
+ _storage.append(_Word.empty)
+ }
+ _count += 1
+ if newElement {
+ _update { handle in
+ handle._mutableWords[word].value |= 1 &<< bit
+ }
+ }
+ _checkInvariants()
+ }
+
+ public mutating func append(
+ contentsOf newElements: __owned S
+ ) where S.Element == Bool {
+ if S.self == BitArray.self {
+ self.append(contentsOf: newElements as! BitArray)
+ return
+ }
+ if S.self == BitArray.SubSequence.self {
+ self.append(contentsOf: newElements as! BitArray.SubSequence)
+ return
+ }
+ var it = newElements.makeIterator()
+ var pos = _BitPosition(_count)
+ if pos.bit > 0 {
+ let (bits, count) = it._nextChunk(
+ maximumCount: UInt(_Word.capacity) - pos.bit)
+ guard count > 0 else { return }
+ _count += count
+ _update { $0._copy(bits: bits, count: count, to: pos) }
+ pos.value += count
+ }
+ while true {
+ let (bits, count) = it._nextChunk()
+ guard count > 0 else { break }
+ assert(pos.bit == 0)
+ _storage.append(.empty)
+ _count += count
+ _update { $0._copy(bits: bits, count: count, to: pos) }
+ pos.value += count
+ }
+ _checkInvariants()
+ }
+
+ public mutating func append(contentsOf newElements: BitArray) {
+ _extend(by: newElements.count)
+ _copy(from: newElements, to: count - newElements.count)
+ _checkInvariants()
+ }
+
+ public mutating func append(contentsOf newElements: BitArray.SubSequence) {
+ _extend(by: newElements.count)
+ _copy(from: newElements, to: count - newElements.count)
+ _checkInvariants()
+ }
+}
+
+extension BitArray {
+ public mutating func insert(_ newElement: Bool, at i: Int) {
+ if _BitPosition(_count).bit == 0 {
+ _storage.append(_Word.empty)
+ }
+ let c = count
+ _count += 1
+ _update { handle in
+ handle.copy(from: i ..< c, to: i + 1)
+ handle[i] = newElement
+ }
+ _checkInvariants()
+ }
+
+ public mutating func insert(
+ contentsOf newElements: __owned C,
+ at i: Int
+ ) where C.Element == Bool {
+ precondition(i >= 0 && i <= count)
+ let c = newElements.count
+ guard c > 0 else { return }
+ _extend(by: c)
+ _copy(from: i ..< count - c, to: i + c)
+
+ if C.self == BitArray.self {
+ _copy(from: newElements as! BitArray, to: i)
+ } else if C.self == BitArray.SubSequence.self {
+ _copy(from: newElements as! BitArray.SubSequence, to: i)
+ } else {
+ _copy(from: newElements, to: i ..< i + c)
+ }
+
+ _checkInvariants()
+ }
+
+ public mutating func insert(
+ contentsOf newElements: __owned BitArray,
+ at i: Int
+ ) {
+ insert(contentsOf: newElements[...], at: i)
+ }
+
+ public mutating func insert(
+ contentsOf newElements: __owned BitArray.SubSequence,
+ at i: Int
+ ) {
+ let c = newElements.count
+ guard c > 0 else { return }
+ _extend(by: c)
+ _copy(from: i ..< count - c, to: i + c)
+ _copy(from: newElements, to: i)
+ _checkInvariants()
+ }
+}
+
+extension BitArray {
+ @discardableResult
+ public mutating func remove(at i: Int) -> Bool {
+ let result = self[i]
+ _copy(from: i + 1 ..< count, to: i)
+ _removeLast()
+ _checkInvariants()
+ return result
+ }
+
+ public mutating func removeSubrange(_ bounds: Range) {
+ precondition(
+ bounds.lowerBound >= 0 && bounds.upperBound <= count,
+ "Bounds out of range")
+ _copy(
+ from: Range(uncheckedBounds: (bounds.upperBound, count)),
+ to: bounds.lowerBound)
+ _removeLast(bounds.count)
+ _checkInvariants()
+ }
+
+ public mutating func _customRemoveLast() -> Bool? {
+ precondition(_count > 0)
+ let result = self[count - 1]
+ _removeLast()
+ _checkInvariants()
+ return result
+ }
+
+ public mutating func _customRemoveLast(_ n: Int) -> Bool {
+ precondition(n >= 0 && n <= count)
+ _removeLast(n)
+ _checkInvariants()
+ return true
+ }
+
+ @discardableResult
+ public mutating func removeFirst() -> Bool {
+ precondition(_count > 0)
+ let result = self[0]
+ _copy(from: 1 ..< count, to: 0)
+ _removeLast()
+ _checkInvariants()
+ return result
+ }
+
+ public mutating func removeFirst(_ k: Int) {
+ precondition(k >= 0 && k <= _count)
+ _copy(from: k ..< count, to: 0)
+ _removeLast(k)
+ _checkInvariants()
+ }
+
+ public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
+ _storage.removeAll(keepingCapacity: keepCapacity)
+ _count = 0
+ _checkInvariants()
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray+Testing.swift b/Sources/BitCollections/BitArray/BitArray+Testing.swift
new file mode 100644
index 00000000..3269ce30
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray+Testing.swift
@@ -0,0 +1,17 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+ @_spi(Testing)
+ public var _capacity: Int {
+ _storage.capacity * _Word.capacity
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift
new file mode 100644
index 00000000..ff069926
--- /dev/null
+++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift
@@ -0,0 +1,138 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 BitArray {
+ /// An unsafe-unowned bitarray view over `UInt` storage, providing bit array
+ /// primitives.
+ @usableFromInline
+ @frozen
+ internal struct _UnsafeHandle {
+ @usableFromInline
+ internal let _words: UnsafeBufferPointer<_Word>
+
+ @usableFromInline
+ internal var _count: UInt
+
+#if DEBUG
+ /// True when this handle does not support table mutations.
+ /// (This is only checked in debug builds.)
+ @usableFromInline
+ internal let _mutable: Bool
+#endif
+
+ @inline(__always)
+ internal func ensureMutable() {
+#if DEBUG
+ assert(_mutable)
+#endif
+ }
+
+ internal var _mutableWords: UnsafeMutableBufferPointer<_Word> {
+ ensureMutable()
+ return UnsafeMutableBufferPointer(mutating: _words)
+ }
+
+ @inlinable
+ @inline(__always)
+ internal init(
+ words: UnsafeBufferPointer<_Word>,
+ count: UInt,
+ mutable: Bool
+ ) {
+ assert(count <= words.count * _Word.capacity)
+ assert(count > (words.count - 1) * _Word.capacity)
+ self._words = words
+ self._count = count
+#if DEBUG
+ self._mutable = mutable
+#endif
+ }
+
+ @inlinable
+ @inline(__always)
+ internal init(
+ words: UnsafeMutableBufferPointer<_Word>,
+ count: UInt,
+ mutable: Bool
+ ) {
+ self.init(
+ words: UnsafeBufferPointer(words),
+ count: count,
+ mutable: mutable)
+ }
+ }
+}
+
+extension BitArray._UnsafeHandle {
+ internal var count: Int {
+ Int(_count)
+ }
+
+ internal subscript(position: Int) -> Bool {
+ get {
+ assert(position >= 0 && position < _count)
+ let (word, bit) = _BitPosition(UInt(position)).split
+ return _words[word].contains(bit)
+ }
+ set {
+ ensureMutable()
+ assert(position >= 0 && position < _count)
+ let (word, bit) = _BitPosition(UInt(position)).split
+ if newValue {
+ _mutableWords[word].insert(bit)
+ } else {
+ _mutableWords[word].remove(bit)
+ }
+ }
+ }
+}
+
+extension BitArray._UnsafeHandle {
+ internal mutating func fill(in range: Range) {
+ ensureMutable()
+ precondition(
+ range.lowerBound >= 0 && range.upperBound <= count,
+ "Range out of bounds")
+ guard range.count > 0 else { return }
+ let (lw, lb) = _BitPosition(range.lowerBound).split
+ let (uw, ub) = _BitPosition(range.upperBound).endSplit
+ let words = _mutableWords
+ guard lw != uw else {
+ words[lw].formUnion(_Word(from: lb, to: ub))
+ return
+ }
+ words[lw].formUnion(_Word(upTo: lb).complement())
+ for w in lw + 1 ..< uw {
+ words[w] = _Word.allBits
+ }
+ words[uw].formUnion(_Word(upTo: ub))
+ }
+
+ internal mutating func clear(in range: Range) {
+ ensureMutable()
+ precondition(
+ range.lowerBound >= 0 && range.upperBound <= count,
+ "Range out of bounds")
+ guard range.count > 0 else { return }
+ let (lw, lb) = _BitPosition(range.lowerBound).split
+ let (uw, ub) = _BitPosition(range.upperBound).endSplit
+ let words = _mutableWords
+ guard lw != uw else {
+ words[lw].subtract(_Word(from: lb, to: ub))
+ return
+ }
+ words[lw].subtract(_Word(upTo: lb).complement())
+ for w in lw + 1 ..< uw {
+ words[w] = _Word.empty
+ }
+ words[uw].subtract(_Word(upTo: ub))
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift
index 6d4141c4..52c4ab27 100644
--- a/Sources/BitCollections/BitArray/BitArray.swift
+++ b/Sources/BitCollections/BitArray/BitArray.swift
@@ -2,89 +2,91 @@
//
// 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 BitArray: ExpressibleByArrayLiteral, Codable {
- typealias WORD = UInt // created for experimental purposes to make it easier to test different UInts without having to change much of the code
-
- var storage : [WORD] = []
- var excess: WORD = 0
-
- public init() { }
-
- public init(_ elements: S) where S : Sequence, Bool == S.Element {
- storage.reserveCapacity(elements.underestimatedCount / WORD.bitWidth)
- for value in elements {
- self.append(value)
- }
- }
-
- public init(arrayLiteral elements: Bool...) {
- storage.reserveCapacity(elements.underestimatedCount / WORD.bitWidth)
- for value in elements {
- self.append(value)
- }
- }
- /// Creates a new collection containing the specified number of a single, repeated `Bool`
- ///
- /// The following example creates a BitArray initialized with 5 true values
- ///
- /// let fiveTrues = BitArray(repeating: true, count: 5)
- /// print(fiveTrues)
- /// // Prints "BitArray(storage: [31], excess: 5)"
- /// print(Array(fiveTrues))
- /// // Prints "[true, true, true, true, true]"
- ///
- /// - Parameters:
- /// - repeatedValue: The `Bool` to repeat.
- /// - count: The number of times to repeat the value passed in the
- /// `repeating` parameter. `count` must be zero or greater.
- public init(repeating repeatedValue: Bool, count: Int) {
- precondition(count >= 0, "Count must be greater than or equal to 0")
- if (count == 0) {
- return
- }
-
- if (repeatedValue) {
- let bytes: Int = (Int(count%(WORD.bitWidth)) > 0) ? (count/(WORD.bitWidth))+1 : count/(WORD.bitWidth)
- storage = Array(repeating: WORD.max, count: bytes)
- excess = WORD(count%(WORD.bitWidth))
-
- // flip remaining bits back to 0
- let remaining: Int = (excess == 0) ? WORD.bitWidth : Int(excess)
- for i in remaining..<(WORD.bitWidth) {
- storage[bytes-1] ^= (1< 0) ? (count/(WORD.bitWidth))+1 : count/(WORD.bitWidth)
- storage = Array(repeating: 0, count: bytes)
- excess = WORD(count%(WORD.bitWidth))
- }
+
+public struct BitArray {
+ @usableFromInline
+ internal var _storage: [_Word]
+
+ @usableFromInline
+ internal var _count: UInt
+
+ @usableFromInline
+ internal init(_storage: [_Word], count: UInt) {
+ assert(count <= _storage.count * _Word.capacity)
+ assert(count > (_storage.count - 1) * _Word.capacity)
+ self._storage = _storage
+ self._count = count
}
- #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
- /// let bitSet: BitSet = [0, 1, 3, 5]
- /// let bitArray = BitArray(bitSet)
- /// print(bitArray)
- /// // Prints "BitArray(storage: [43], excess: 0)"
- /// print(Array(bitArray))
- /// // Prints "[true, true, false, true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]"
- ///
- /// - Parameters:
- /// - bitSet: An initialized BitSet
- public init(_ bitSet: BitSet) {
- storage = bitSet.storage.storage
- excess = bitSet.storage.excess
+ @inline(__always)
+ internal init(_storage: [_Word], count: Int) {
+ self.init(_storage: _storage, count: UInt(count))
}
- #endif
}
+extension BitArray {
+ @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)
+ }
+ }
+ @inline(__always)
+ internal mutating func _update(
+ _ body: (inout _UnsafeHandle) throws -> R
+ ) rethrows -> R {
+ defer {
+ _checkInvariants()
+ }
+ return try _storage.withUnsafeMutableBufferPointer { words in
+ var handle = _UnsafeHandle(words: words, count: _count, mutable: true)
+ return try body(&handle)
+ }
+ }
+
+ internal mutating func _removeLast() {
+ assert(_count > 0)
+ _count -= 1
+ let bit = _BitPosition(_count).bit
+ if bit == 0 {
+ _storage.removeLast()
+ } else {
+ _storage[_storage.count - 1].remove(bit)
+ }
+ }
+
+ internal mutating func _removeLast(_ n: Int) {
+ assert(n >= 0 && n <= _count)
+ guard n > 0 else { return }
+ let wordCount = _Word.wordCount(forBitCount: _count - UInt(n))
+ if wordCount < _storage.count {
+ _storage.removeLast(_storage.count - wordCount)
+ }
+ _count -= UInt(n)
+ let (word, bit) = _BitPosition(_count).split
+ if bit > 0 {
+ _storage[word].formIntersection(_Word(upTo: bit))
+ }
+ }
+
+ internal mutating func _extend(by n: Int) {
+ assert(n >= 0)
+ guard n > 0 else { return }
+ let orig = _storage.count
+ let new = _Word.wordCount(forBitCount: _count + UInt(n))
+ _storage.append(
+ contentsOf: repeatElement(.empty, count: new - orig))
+ _count += UInt(n)
+ }
+}
diff --git a/Sources/BitCollections/BitArray/BitArrayBitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArrayBitwiseOperations.swift
deleted file mode 100644
index 5b85bd89..00000000
--- a/Sources/BitCollections/BitArray/BitArrayBitwiseOperations.swift
+++ /dev/null
@@ -1,283 +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 BitArray {
-
- /// mutates self by setting the value in each index to true if either self or the passed in BitArray -- or both -- have a true value in that respective index.
- ///
- /// The following example mutates a BitArray to be OR'd with another BitArray
- /// var bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// bitArray.formBitwiseOr(secondBitArray)
- /// print(Array(bitArray))
- /// Prints "[true, false, true, true]"
- ///
- /// - Parameters:
- /// - other: An initialized BitArray. `other` must have the same count as `self`
- public mutating func formBitwiseOr(_ other: BitArray) {
-
- precondition(self.storage.count == other.storage.count, "Bitwise operations on BitArrays of different length is currently not supported")
-
- for i in 0.. BitArray{
- var copy = self
- copy.formBitwiseOr(other)
- return copy
- }
- /// creates and returns a new BitArray by setting the value in each index of the new BitArray to true if both self and the passed in BitArray have a true value in that respective index.
- ///
- /// The following example creates and returns a BitArray that is the AND'd result of self and another BitArray
- /// let bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// let newBitArray = bitArray.bitwiseAnd(secondBitArray)
- /// print(Array(newBitArray))
- /// Prints "[true, false, false, false]"
- ///
- /// - Parameters:
- /// - other: An initialized BitArray. `other` must have the same count as `self`
- /// - Returns: The BitArray that is the AND'd result of `self` and `other`
- public func bitwiseAnd(_ other: BitArray) -> BitArray{
- var copy = self
- copy.formBitwiseAnd(other)
- return copy
- }
- /// creates a new BitArray by setting the value in each index of the new BitArray to true if either self or the passed in BitArray -- but not both -- have a true value in that respective index.
- ///
- /// The following example creates a new a BitArray that is the XOR'd result of self and another BitArray
- /// let bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// let newBitArray = bitArray.bitwiseOr(secondBitArray)
- /// print(Array(newBitArray))
- /// Prints "[false, false, true, true]"
- ///
- /// - Parameters:
- /// - other: An initialized BitArray. `other` must have the same count as `self`
- /// - Returns: The BitArray that is the XOR'd result of `self` and `other`
- public func bitwiseXor(_ other: BitArray) -> BitArray{
- var copy = self
- copy.formBitwiseXor(other)
- return copy
- }
- /// creates a new BitArray by setting each value in the new BitArray to the opposite value of that in self
- ///
- /// The following example creates a new a BitArray that is the inverse of self
- /// let bitArray: BitArray = [true, false, true, false]
- /// let newBitArray = bitArray.bitwiseNot()
- /// print(Array(newBitArray))
- /// Prints "[false, true, false, true]"
- ///
- /// - Returns: The BitArray that contains the inverse or opposite values of that in self
- public func bitwiseNot() -> BitArray {
- var copy = self
- copy.formBitwiseNot()
- return copy
- }
-}
-
-// Overloaded Operators
-
-extension BitArray {
- /// overloaded operator that creates and returns a new BitArray by setting the value in each index to true if either the lhs BitArray or the rhs BitArray -- or both -- have a true value in that respective index.
- ///
- /// The following example creates and returns a BitArray that is the OR'd result of the lhs and rhs
- /// let bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// let newBitArray = bitArray | secondBitArray
- /// print(Array(newBitArray))
- /// Prints "[true, false, true, true]"
- ///
- /// - Parameters:
- /// - lhs: An initialized BitArray
- /// - rhs: An initialized BitArray. `rhs` must have same count as `lhs`
- /// - Returns: The BitArray that is the XOR'd result of the lhs and rhs
- public static func | (lhs: BitArray, rhs: BitArray) -> BitArray {
- var copy = lhs
- copy.formBitwiseOr(rhs)
- return copy
- }
- /// overloaded operator that creates and returns a new BitArray by setting the value in each index of the new BitArray to true if both the lhs BitArray and the rhs BitArray have a true value in that respective index.
- ///
- /// The following example creates and returns a BitArray that is the AND'd result of self and another BitArray
- /// let bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// let newBitArray = bitArray & secondBitArray
- /// print(Array(newBitArray))
- /// Prints "[true, false, false, false]"
- ///
- /// - Parameters:
- /// - lhs: An initialized BitArray
- /// - rhs: An initialized BitArray. `rhs` must have same count as `lhs`
- /// - Returns: The BitArray that is the AND'd result of the lhs and rhs
- public static func & (lhs: BitArray, rhs: BitArray) -> BitArray {
- var copy = lhs
- copy.formBitwiseAnd(rhs)
- return copy
- }
- /// creates a new BitArray by setting the value in each index of the new BitArray to true if either lhs BitArray or the rhs BitArray -- but not both -- have a true value in that respective index.
- ///
- /// The following example creates a new a BitArray that is the XOR'd result of self and another BitArray
- /// let bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// let newBitArray = bitArray ^ secondBitArray
- /// print(Array(newBitArray))
- /// Prints "[false, false, true, true]"
- ///
- /// - Parameters:
- /// - lhs: An initialized BitArray
- /// - rhs: An initialized BitArray. `rhs` must have same count as `lhs`
- /// - Returns: The BitArray that is the XOR'd result of the lhs and rhs
- public static func ^ (lhs: BitArray, rhs: BitArray) -> BitArray {
- var copy = lhs
- copy.formBitwiseXor(rhs)
- return copy
- }
- /// The bitwise NOT operator (`~`) is a prefix operator that returns a value in which all the Bools of its argument are flipped
- ///
- /// The following example creates a new a BitArray to be NOT'd with another BitArray
- /// let bitArray: BitArray = [true, false, true, false]
- /// let newBitArray = ~bitArray
- /// print(Array(newBitArray))
- /// Prints "[false, true, false, true]"
- ///
- /// - Returns: The `BitArray` that contains the inverse or opposite values of that in `self`
- public static prefix func ~ (_ bitArray: BitArray) -> BitArray {
- var copy = bitArray
- copy.formBitwiseNot()
- return copy
- }
- /// overloaded operator that mutates the lhs BitArray by setting the value in each index to true if either the lhs BitArray or the rhs BitArray -- or both -- have a true value in that respective index.
- ///
- /// The following example mutates the lhs to be OR'd with the rhs
- /// var bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// bitArray |= secondBitArray
- /// print(Array(bitArray))
- /// Prints "[true, false, true, true]"
- ///
- /// - Parameters:
- /// - lhs: An initialized BitArray
- /// - rhs: An initialized BitArray. `rhs` must have same count as `lhs`
- public static func |= (lhs: inout BitArray, rhs: BitArray) {
- lhs.formBitwiseOr(rhs)
- }
- /// overloaded operator that mutates the lhs BitArray by setting the value in each index to true if both the lhs BitArray and the rhs BitArray have a true value in that respective index.
- ///
- /// The following example mutates the lhs to be AND'd with the rhs
- /// var bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// bitArray &= secondBitArray
- /// print(Array(bitArray))
- /// Prints "[true, false, false, false]"
- ///
- /// - Parameters:
- /// - lhs: An initialized BitArray
- /// - rhs: An initialized BitArray. `rhs` must have same count as `lhs`
- public static func &= (lhs: inout BitArray, rhs: BitArray) {
- lhs.formBitwiseAnd(rhs)
- }
- /// overloaded operator that mutates the lhs BitArray by setting the value in each index to true if either the lhs BitArray or the rhs BitArray -- but not both -- have a true value in that respective index.
- ///
- /// The following example mutates a BitArray to be XOR'd with another BitArray
- /// var bitArray: BitArray = [true, false, true, false]
- /// let secondBitArray = [true, false, false, true]
- /// bitArray ^= secondBitArray
- /// print(Array(bitArray))
- /// Prints "[false, false, true, true]"
- ///
- /// - Parameters:
- /// - lhs: An initialized BitArray
- /// - rhs: An initialized BitArray. `rhs` must have same count as `lhs`
- public static func ^= (lhs: inout BitArray, rhs: BitArray) {
- lhs.formBitwiseXor(rhs)
- }
-
-}
diff --git a/Sources/BitCollections/BitArray/BitArrayConformances.swift b/Sources/BitCollections/BitArray/BitArrayConformances.swift
deleted file mode 100644
index ab093031..00000000
--- a/Sources/BitCollections/BitArray/BitArrayConformances.swift
+++ /dev/null
@@ -1,76 +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 BitArray: Collection, RandomAccessCollection {
-
-
- public func index(after i: Int) -> Int {
- return i + 1
- }
-
- public var count: Int {
- let remaining: Int = (excess == 0) ? WORD.bitWidth : Int(excess)
- return (storage.count)*WORD.bitWidth - (WORD.bitWidth - remaining)
- }
-
- public var startIndex: Int {
- return 0
- }
-
- public var endIndex: Int {
- return count
- }
-
-}
-
-
-extension BitArray: BidirectionalCollection {
-
- public func index(before i: Int) -> Int {
- return i - 1
- }
-
-}
-
-extension BitArray: MutableCollection {
-
- public subscript(position: Int) -> Bool {
-
- get {
- precondition(position < endIndex && position >= startIndex, "Index out of bounds")
-
- let (index, mask) = _split(_position: position)
- return (storage[index] & mask != 0)
- }
- set {
- let (index, mask) = _split(_position: position)
- if (newValue) { storage[index] |= mask } else { storage[index] &= ~mask }
- }
-
- }
-
- private func _split(_position: Int) -> (Int, WORD) {
-
- let index: Int = _position/WORD.bitWidth
- let subPosition: Int = _position - index*WORD.bitWidth
- let mask: WORD = 1 << subPosition
-
- return (index, mask)
-
- }
-
-}
-
-extension BitArray: Equatable {
- public static func == (lhs: BitArray, rhs: BitArray) -> Bool {
- return ((lhs.excess == rhs.excess) && (lhs.storage == rhs.storage))
- }
-}
diff --git a/Sources/BitCollections/BitArray/BitArrayOperations.swift b/Sources/BitCollections/BitArray/BitArrayOperations.swift
deleted file mode 100644
index 89ce47a5..00000000
--- a/Sources/BitCollections/BitArray/BitArrayOperations.swift
+++ /dev/null
@@ -1,226 +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 BitArray {
-
- public mutating func append(_ newValue: Bool) {
-
- if (!newValue) {
- if(excess == 0) { storage.append(0)}
- _adjustExcessForAppend()
- return
- }
-
- if (excess == 0) {
- storage.append(1)
- } else {
- storage[storage.endIndex-1] += (1 << excess)
- }
-
- _adjustExcessForAppend()
- }
-
- private mutating func _adjustExcessForAppend(){
- if (self.excess == (WORD.bitWidth-1)) {
- self.excess = 0
- } else {
- self.excess += 1
- }
- }
-
- @discardableResult
- public mutating func remove(at: Int) -> Bool {
- precondition(self.count != 0, "The bit array is empty. There are no items to remove.")
- precondition(at < endIndex && at >= 0, "The index entered is out of range")
- defer {
- self[at] = false
- for index in (at+1).. Bool {
- precondition(self.count != 0, "The bit array is empty. There are no items to remove.")
- defer {
- self[endIndex-1] = false
- _adjustExcessForRemove()
- }
- return self[endIndex-1]
- }
- /// Removes the last several values in the end of the BitArray
- ///
- /// The following example removes the last 3 elements of a BitArray
- /// var bitArray: BitArray = [true, false, true, false, false, true]
- /// bitArray.removeLast(3)
- /// print(Array(bitArray))
- /// Prints "[true, false, true]"
- ///
- /// - Parameters:
- /// - k: an integer that represents the number of values desired to be removed from the beginning.
- ///`k` must be a positive number, and less than the `count` value of self
- public mutating func removeLast(_ k: Int){
- precondition(self.count != 0, "The bit array is empty. There are no items to remove.")
- precondition(k < endIndex, "The input amount is invalidly larger than the array itself.")
- precondition(k > 0, "Input amount must be a positive number.")
- let elementsInLastByte: Int = (excess == 0) ? WORD.bitWidth : Int(excess)
- if (k < elementsInLastByte) {
- for _ in 1...k {
- removeLast()
- }
- return
- } else if (k == elementsInLastByte) {
- storage.removeLast()
- excess = 0
- return
- }
- storage.removeLast()
- excess = 0
- let range = k - Int(elementsInLastByte)
- let removeableBytes: Int = range/(WORD.bitWidth)
- storage.removeLast(removeableBytes)
-
- // slower than necessary
- for _ in 0.. Bool {
- precondition(self.count != 0, "The bit array is empty. There are no items to remove")
- defer {
- self[0] = false
- for index in 1.. 0, "The input rangeSize must be a positive number.")
- let removeableBytes: Int = k/(WORD.bitWidth)
- let newCount = self.count-k
- storage.removeFirst(removeableBytes)
-
- let remainingElemCount = Int(k%(WORD.bitWidth))
- if (remainingElemCount != 0) {
- for i in 0.. Int? {
- var counter = -1
- for item in storage {
- counter += 1
- if (item > 0) {
- return item.trailingZeroBitCount + counter*WORD.bitWidth
- }
- }
- return nil
- }
- /// Returns the index of the last true value in the BitArray.
- /// If there are no true values in the BitArray, the function returns nil
- ///
- /// Examples:
- /// let bitArray: BitArray = [false, true, false, true]
- /// let lastTrue: Int? = bitArray.lastTrue()
- /// print(lastTrue)
- /// Prints "2"
- ///
- /// let allFalseBitArray: BitArray = [false, false, false]
- /// let lastTrue: Int? = allFalseBitArray.lastTrue()
- /// print(lastTrue)
- /// Prints "nil"
- ///
- /// - Returns: An optional integer value of the index where the last true was found
- /// If there are no true values in the BitArray, the function returns `nil`
- public func lastTrue() -> Int? {
- var counter = storage.count
- for item in storage.reversed() {
- counter -= 1
- if (item > 0) {
- return (WORD.bitWidth-item.leadingZeroBitCount) + counter*WORD.bitWidth - 1
- }
- }
- return nil
- }
-
-}
diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift
index cf750f87..4c26a36d 100644
--- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift
+++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift
@@ -30,10 +30,15 @@ extension BitSet {
internal let _mutable: Bool
#endif
- internal var _mutableWords: UnsafeMutableBufferPointer<_Word> {
+ @inline(__always)
+ internal func ensureMutable() {
#if DEBUG
assert(_mutable)
#endif
+ }
+
+ internal var _mutableWords: UnsafeMutableBufferPointer<_Word> {
+ ensureMutable()
return UnsafeMutableBufferPointer(mutating: _words)
}
@@ -59,12 +64,8 @@ extension BitSet {
count: Int,
mutable: Bool
) {
- assert(words.baseAddress != nil)
- self._words = UnsafeBufferPointer(words)
- self._count = count
-#if DEBUG
- self._mutable = mutable
-#endif
+ self.init(
+ words: UnsafeBufferPointer(words), count: count, mutable: mutable)
}
@inlinable
@@ -174,7 +175,7 @@ extension BitSet._UnsafeHandle {
@_effects(readnone)
@inline(__always)
internal static func wordCount(forCapacity capacity: UInt) -> Int {
- Index(capacity + UInt(_Word.capacity) - 1).word
+ _Word.wordCount(forBitCount: capacity)
}
internal var capacity: UInt {
@@ -197,9 +198,7 @@ extension BitSet._UnsafeHandle {
}
internal mutating func updateCount() {
-#if DEBUG
- assert(_mutable)
-#endif
+ ensureMutable()
_count = _words.reduce(into: 0) { $0 += $1.count }
}
@@ -215,6 +214,7 @@ extension BitSet._UnsafeHandle {
@_effects(releasenone)
@discardableResult
internal mutating func insert(_ element: UInt) -> Bool {
+ ensureMutable()
assert(isValid(element))
let index = Index(element)
let inserted = _mutableWords[index.word].insert(index.bit)
@@ -224,6 +224,7 @@ extension BitSet._UnsafeHandle {
@discardableResult
internal mutating func remove(_ element: UInt) -> Bool {
+ ensureMutable()
let index = Index(element)
if index.word >= _words.count { return false }
let removed = _mutableWords[index.word].remove(index.bit)
@@ -234,6 +235,7 @@ extension BitSet._UnsafeHandle {
@usableFromInline
@_effects(releasenone)
internal mutating func clear() {
+ ensureMutable()
guard wordCount > 0 else { return }
_mutableWords.baseAddress?.assign(
repeating: .empty, count: wordCount)
@@ -243,6 +245,7 @@ extension BitSet._UnsafeHandle {
@usableFromInline
@_effects(releasenone)
internal mutating func insertAll(upTo max: UInt) {
+ ensureMutable()
assert(max <= capacity)
guard max > 0 else { return }
let (w, b) = Index(max).split
@@ -258,6 +261,7 @@ extension BitSet._UnsafeHandle {
@usableFromInline
@_effects(releasenone)
internal mutating func removeAll(upTo max: UInt) {
+ ensureMutable()
assert(max <= capacity)
guard max > 0 else { return }
let (w, b) = Index(max).split
@@ -329,55 +333,7 @@ extension BitSet._UnsafeHandle: Sequence {
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)
- }
- }
+ internal typealias Index = _BitPosition
@inlinable
@inline(__always)
@@ -449,6 +405,7 @@ extension BitSet._UnsafeHandle {
with other: Self,
using function: (inout _Word, _Word) -> Void
) {
+ ensureMutable()
let c = Swift.min(self.wordCount, other.wordCount)
for w in 0 ..< c {
function(&self._mutableWords[w], other._words[w])
@@ -483,9 +440,7 @@ extension BitSet._UnsafeHandle {
}
internal mutating func formUnion(_ range: Range) {
-#if DEBUG
- assert(_mutable)
-#endif
+ ensureMutable()
let l = Index(range.lowerBound)
let u = Index(range.upperBound)
assert(u.value <= capacity)
@@ -507,9 +462,7 @@ extension BitSet._UnsafeHandle {
}
internal mutating func formIntersection(_ range: Range) {
-#if DEBUG
- assert(_mutable)
-#endif
+ ensureMutable()
let l = Index(Swift.min(range.lowerBound, capacity))
let u = Index(Swift.min(range.upperBound, capacity))
@@ -537,9 +490,7 @@ extension BitSet._UnsafeHandle {
}
internal mutating func formSymmetricDifference(_ range: Range) {
-#if DEBUG
- assert(_mutable)
-#endif
+ ensureMutable()
let l = Index(range.lowerBound)
let u = Index(range.upperBound)
assert(u.value <= capacity)
@@ -562,9 +513,7 @@ extension BitSet._UnsafeHandle {
}
internal mutating func subtract(_ range: Range) {
-#if DEBUG
- assert(_mutable)
-#endif
+ ensureMutable()
let l = Index(Swift.min(range.lowerBound, capacity))
let u = Index(Swift.min(range.upperBound, capacity))
diff --git a/Sources/BitCollections/BitSet/Range+Utilities.swift b/Sources/BitCollections/Shared/Range+Utilities.swift
similarity index 100%
rename from Sources/BitCollections/BitSet/Range+Utilities.swift
rename to Sources/BitCollections/Shared/Range+Utilities.swift
diff --git a/Sources/BitCollections/Shared/Slice+Utilities.swift b/Sources/BitCollections/Shared/Slice+Utilities.swift
new file mode 100644
index 00000000..37dcf7dc
--- /dev/null
+++ b/Sources/BitCollections/Shared/Slice+Utilities.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 Slice {
+ internal var _bounds: Range {
+ Range(uncheckedBounds: (startIndex, endIndex))
+ }
+}
diff --git a/Sources/BitCollections/Shared/UnsafeBufferPointer+Utilities.swift b/Sources/BitCollections/Shared/UnsafeBufferPointer+Utilities.swift
new file mode 100644
index 00000000..417f14eb
--- /dev/null
+++ b/Sources/BitCollections/Shared/UnsafeBufferPointer+Utilities.swift
@@ -0,0 +1,28 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 UnsafeBufferPointer {
+ @inlinable
+ @inline(__always)
+ internal func _ptr(at index: Int) -> UnsafePointer {
+ assert(index >= 0 && index < count)
+ return baseAddress.unsafelyUnwrapped + index
+ }
+}
diff --git a/Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift b/Sources/BitCollections/Shared/UnsafeMutableBufferPointer+Utilities.swift
similarity index 83%
rename from Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift
rename to Sources/BitCollections/Shared/UnsafeMutableBufferPointer+Utilities.swift
index 8c19603a..d8fe84a5 100644
--- a/Sources/BitCollections/BitSet/UnsafeMutableBufferPointer+Utilities.swift
+++ b/Sources/BitCollections/Shared/UnsafeMutableBufferPointer+Utilities.swift
@@ -9,15 +9,6 @@
//
//===----------------------------------------------------------------------===//
-extension Collection {
- @inlinable
- @inline(__always)
- internal func _rebased() -> UnsafeBufferPointer
- where Self == UnsafeBufferPointer.SubSequence {
- .init(rebasing: self)
- }
-}
-
extension Collection {
@inlinable
@inline(__always)
diff --git a/Sources/BitCollections/Shared/_BitPosition.swift b/Sources/BitCollections/Shared/_BitPosition.swift
new file mode 100644
index 00000000..b75bc3ec
--- /dev/null
+++ b/Sources/BitCollections/Shared/_BitPosition.swift
@@ -0,0 +1,84 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 _BitPosition: Comparable, Hashable {
+ @usableFromInline
+ internal var value: UInt
+
+ @inlinable
+ internal init(_ value: UInt) {
+ self.value = value
+ }
+
+ @inlinable
+ internal init(_ value: Int) {
+ self.value = UInt(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
+ internal var endSplit: (word: Int, bit: UInt) {
+ let w = word
+ let b = bit
+ if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) }
+ return (w, b)
+ }
+
+ @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
+ func successor() -> Self {
+ Self(value + 1)
+ }
+
+ @inlinable
+ func predecessor() -> Self {
+ Self(value - 1)
+ }
+}
diff --git a/Sources/BitCollections/BitSet/_Word.swift b/Sources/BitCollections/Shared/_Word.swift
similarity index 88%
rename from Sources/BitCollections/BitSet/_Word.swift
rename to Sources/BitCollections/Shared/_Word.swift
index 7ce8d3dc..8c1cb927 100644
--- a/Sources/BitCollections/BitSet/_Word.swift
+++ b/Sources/BitCollections/Shared/_Word.swift
@@ -30,10 +30,23 @@ internal struct _Word {
@inline(__always)
internal init(from start: UInt, to end: UInt) {
assert(start <= end && end <= _Word.capacity)
- self = Self(upTo: end).subtracting(Self(upTo: start))
+ self = Self(upTo: end).symmetricDifference(Self(upTo: start))
}
}
+extension _Word: CustomStringConvertible {
+ @usableFromInline
+ internal var description: String {
+ String(value, radix: 16)
+ }
+}
+
+extension _Word {
+ @inline(__always)
+ internal static func wordCount(forBitCount count: UInt) -> Int {
+ return _BitPosition(count + UInt(_Word.capacity) - 1).word
+ }
+}
extension _Word {
@inlinable
@inline(__always)
@@ -239,3 +252,17 @@ extension _Word {
self.value &= ~other.value
}
}
+
+extension _Word {
+ @inline(__always)
+ internal func shiftedDown(by shift: UInt) -> Self {
+ assert(shift >= 0 && shift < Self.capacity)
+ return _Word(self.value &>> shift)
+ }
+
+ @inline(__always)
+ internal func shiftedUp(by shift: UInt) -> Self {
+ assert(shift >= 0 && shift < Self.capacity)
+ return _Word(self.value &<< shift)
+ }
+}
diff --git a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift
index 1c3aa0a7..023f1fd4 100644
--- a/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift
+++ b/Sources/_CollectionsTestSupport/AssertionContexts/Combinatorics.swift
@@ -79,48 +79,55 @@ internal func _samples(from items: C) -> [C.Element] {
public func withSome(
_ label: String,
in items: C,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line,
run body: (C.Element) throws -> Void
) rethrows {
let context = TestContext.current
- for item in _samples(from: items) {
+
+ func check(item: C.Element) throws {
let entry = context.push("\(label): \(item)", file: file, line: line)
var done = false
defer {
- context.pop(entry)
if !done {
print(context.currentTrace(title: "Throwing trace"))
}
+ context.pop(entry)
}
try body(item)
done = true
}
+
+ let c = items.count
+
+ if let maxSamples = maxSamples, c > maxSamples {
+ // FIXME: Use randomSample() from swift-algorithms to eliminate dupes
+ for _ in 0 ..< maxSamples {
+ let r = Int.random(in: 0 ..< c)
+ let i = items.index(items.startIndex, offsetBy: r)
+ try check(item: items[i])
+ }
+ } else {
+ for item in items {
+ try check(item: item)
+ }
+ }
}
public func withSomeRanges(
_ label: String,
in bounds: Range,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line,
run body: (Range) throws -> Void
) rethrows where T.Stride == Int {
- let context = TestContext.current
- for lowerBound in _samples(from: bounds) {
- for upperBound in _samples(from: lowerBound ... bounds.upperBound) {
- let range = lowerBound ..< upperBound
- let entry = context.push("\(label): \(range)", file: file, line: line)
- var done = false
- defer {
- context.pop(entry)
- if !done {
- print(context.currentTrace(title: "Throwing trace"))
- }
- }
- try body(range)
- done = true
- }
- }
+ try withSome(
+ label,
+ in: IndexRangeCollection(bounds: bounds),
+ maxSamples: maxSamples,
+ run: body)
}
/// Utility function for testing mutations with value semantics.
diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift
index 5c14935d..1f0122a4 100644
--- a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift
+++ b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift
@@ -43,6 +43,7 @@ extension BidirectionalCollection {
public func checkBidirectionalCollection(
_ collection: C,
expectedContents: S,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where C.Element: Equatable, S.Element == C.Element {
@@ -50,6 +51,7 @@ public func checkBidirectionalCollection Bool,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where S.Element == C.Element {
@@ -68,10 +71,12 @@ public func checkBidirectionalCollection Bool,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where S.Element == C.Element {
@@ -108,40 +114,39 @@ public func _checkBidirectionalCollection(
_ collection: C,
expectedContents: Expected,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where C.Element: Equatable, Expected.Element == C.Element {
@@ -76,6 +77,7 @@ public func checkCollection(
collection,
expectedContents: expectedContents,
by: ==,
+ maxSamples: maxSamples,
file: file, line: line)
let indicesByIndexAfter = collection._indicesByIndexAfter()
@@ -101,6 +103,7 @@ public func checkCollection(
_ collection: C,
expectedContents: Expected,
by areEquivalent: (C.Element, C.Element) -> Bool,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where Expected.Element == C.Element {
@@ -113,6 +116,7 @@ public func checkCollection(
collection,
expectedContents: expectedContents,
by: areEquivalent,
+ maxSamples: maxSamples,
file: file, line: line)
}
@@ -120,6 +124,7 @@ public func _checkCollection(
_ collection: C,
expectedContents: Expected,
by areEquivalent: (C.Element, C.Element) -> Bool,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where Expected.Element == C.Element {
@@ -158,7 +163,10 @@ public func _checkCollection(
// Check the Indices associated type
if C.self != C.Indices.self {
- checkCollection(collection.indices, expectedContents: indicesByIndexAfter)
+ checkCollection(
+ collection.indices,
+ expectedContents: indicesByIndexAfter,
+ maxSamples: maxSamples)
} else {
expectEqual(collection.indices.count, collection.count)
expectEqualElements(collection.indices, indicesByIndexAfter)
@@ -168,20 +176,15 @@ public func _checkCollection(
// The sequence of indices must be monotonically increasing.
var allIndices = indicesByIndexAfter
allIndices.append(collection.endIndex)
- checkComparable(allIndices, oracle: { .comparing($0, $1) })
- // Check `index(_,offsetBy:)`
- for (offset, start) in allIndices.enumerated() {
- for distance in 0 ... indicesByIndexAfter.count - offset {
- let end = collection.index(start, offsetBy: distance)
- expectEqual(end, allIndices[offset + distance])
- if offset + distance < expectedContents.count {
- expectEquivalent(collection[end], expectedContents[offset + distance],
- by: areEquivalent)
- }
- }
+ if C.Index.self != Int.self {
+ checkComparable(
+ allIndices,
+ oracle: { .comparing($0, $1) },
+ maxSamples: maxSamples)
}
+ #if false
// Check `index(_,offsetBy:limitedBy:)`
let limits =
Set([0, allIndices.count - 1, allIndices.count / 2])
@@ -200,71 +203,81 @@ public func _checkCollection(
}
}
}
+ #endif
+
+ withSomeRanges(
+ "range", in: 0 ..< allIndices.count - 1, maxSamples: maxSamples
+ ) { range in
+ let i = range.lowerBound
+ let j = range.upperBound
- // Check `distance(from:to:)`
- withEvery("i", in: allIndices.indices) { i in
- withEvery("j", in: allIndices.indices[i...]) { j in
- let d = collection.distance(from: allIndices[i], to: allIndices[j])
- expectEqual(d, j - i)
+ // Check `index(_,offsetBy:)`
+ let e = collection.index(allIndices[i], offsetBy: j - i)
+ expectEqual(e, allIndices[j])
+ if j < expectedContents.count {
+ expectEquivalent(collection[e], expectedContents[j], by: areEquivalent)
}
- }
- // Check slicing.
- withEvery("i", in: 0 ..< allIndices.count) { i in
- withEvery("j", in: i ..< allIndices.count) { j in
- let range = allIndices[i] ..< allIndices[j]
- let slice = collection[range]
- expectEqual(slice.count, j - i)
- expectEqual(slice.isEmpty, i == j)
- expectEqual(slice.startIndex, allIndices[i])
- expectEqual(slice.endIndex, allIndices[j])
- expectEqual(slice.distance(from: allIndices[i], to: allIndices[j]), j - i)
- expectEqual(slice.index(allIndices[i], offsetBy: j - i), allIndices[j])
-
- expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[j]),
- allIndices[j])
- expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[i]),
- j - i > 0 ? nil : allIndices[i])
- expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[0]),
- i > 0 || j == 0 ? allIndices[j] : nil)
-
- expectEquivalentElements(slice, expectedContents[i ..< j],
- by: areEquivalent)
-
- expectEquivalentElements(
- slice._contentsByIterator(), expectedContents[i ..< j],
- by: areEquivalent)
- expectEquivalentElements(
- slice._contentsByCopyContents(), expectedContents[i ..< j],
- by: areEquivalent)
-
- // Check _copyContents.
- let copyContents = collection._contentsByCopyContents()
- expectEquivalentElements(
- copyContents, expectedContents,
- by: areEquivalent)
-
- expectEqualElements(slice._indicesByIndexAfter(), allIndices[i ..< j])
- expectEqualElements(slice._indicesByFormIndexAfter(), allIndices[i ..< j])
- expectEqualElements(slice.indices, allIndices[i ..< j])
- expectEqualElements(slice.indices._indicesByIndexAfter(), allIndices[i ..< j])
- expectEqualElements(slice.indices._indicesByFormIndexAfter(), allIndices[i ..< j])
- // Check the subsequence iterator.
- expectEquivalentElements(
- slice, expectedContents[i ..< j],
- by: areEquivalent)
- // Check the subsequence subscript.
- expectEquivalentElements(
- allIndices[i ..< j].map { slice[$0] }, expectedContents[i ..< j],
- by: areEquivalent)
- // Check _copyToContiguousArray.
- expectEquivalentElements(
- Array(slice), expectedContents[i ..< j],
- by: areEquivalent)
- // Check slicing of slices.
- expectEquivalentElements(
- slice[range], expectedContents[i ..< j],
+ // Check `distance(from:to:)`
+ let d = collection.distance(from: allIndices[i], to: allIndices[j])
+ expectEqual(d, j - i)
+
+ // Check slicing.
+ let range = allIndices[i] ..< allIndices[j]
+ let slice = collection[range]
+ expectEqual(slice.count, j - i)
+ expectEqual(slice.isEmpty, i == j)
+ expectEqual(slice.startIndex, allIndices[i])
+ expectEqual(slice.endIndex, allIndices[j])
+ expectEqual(slice.distance(from: allIndices[i], to: allIndices[j]), j - i)
+ expectEqual(slice.index(allIndices[i], offsetBy: j - i), allIndices[j])
+
+ expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[j]),
+ allIndices[j])
+ expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[i]),
+ j - i > 0 ? nil : allIndices[i])
+ expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[0]),
+ i > 0 || j == 0 ? allIndices[j] : nil)
+
+ expectEquivalentElements(slice, expectedContents[i ..< j],
+ by: areEquivalent)
+
+ expectEquivalentElements(
+ slice._contentsByIterator(), expectedContents[i ..< j],
+ by: areEquivalent)
+ expectEquivalentElements(
+ slice._contentsByCopyContents(), expectedContents[i ..< j],
+ by: areEquivalent)
+
+ // Check _copyContents.
+ let copyContents = collection._contentsByCopyContents()
+ expectEquivalentElements(
+ copyContents, expectedContents,
+ by: areEquivalent)
+
+ expectEqualElements(slice._indicesByIndexAfter(), allIndices[i ..< j])
+ expectEqualElements(slice._indicesByFormIndexAfter(), allIndices[i ..< j])
+ expectEqualElements(slice.indices, allIndices[i ..< j])
+ expectEqualElements(slice.indices._indicesByIndexAfter(), allIndices[i ..< j])
+ expectEqualElements(slice.indices._indicesByFormIndexAfter(), allIndices[i ..< j])
+ // Check the subsequence iterator.
+ expectEquivalentElements(
+ slice, expectedContents[i ..< j],
+ by: areEquivalent)
+ // Check the subsequence subscript.
+ withSome("k", in: i ..< j, maxSamples: 25) { k in
+ expectEquivalent(
+ slice[allIndices[k]],
+ expectedContents[k],
by: areEquivalent)
}
+ // Check _copyToContiguousArray.
+ expectEquivalentElements(
+ Array(slice), expectedContents[i ..< j],
+ by: areEquivalent)
+ // Check slicing of slices.
+ expectEquivalentElements(
+ slice[range], expectedContents[i ..< j],
+ by: areEquivalent)
}
}
diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift
index 5067b35e..e9866a59 100644
--- a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift
+++ b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift
@@ -48,6 +48,7 @@ extension ExpectedComparisonResult: CustomStringConvertible {
public func checkComparable(
sortedEquivalenceClasses: [[Instance]],
+ maxSamples: Int? = nil,
file: StaticString = #file, line: UInt = #line
) {
let instances = sortedEquivalenceClasses.flatMap { $0 }
@@ -60,6 +61,7 @@ public func checkComparable(
if oracle[$0] > oracle[$1] { return .gt }
return .eq
},
+ maxSamples: maxSamples,
file: file, line: line)
}
@@ -69,16 +71,24 @@ public func checkComparable(
public func checkComparable(
_ instances: Instances,
oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult,
+ maxSamples: Int? = nil,
file: StaticString = #file, line: UInt = #line
-) where Instances.Element: Comparable {
- checkEquatable(instances,
- oracle: { oracle($0, $1) == .eq },
- file: file, line: line)
- _checkComparable(instances, oracle: oracle, file: file, line: line)
+) where Instances.Element: Comparable, Instances.Index == Int {
+ checkEquatable(
+ instances,
+ oracle: { oracle($0, $1) == .eq },
+ maxSamples: maxSamples,
+ file: file, line: line)
+ _checkComparable(
+ instances,
+ oracle: oracle,
+ maxSamples: maxSamples,
+ file: file, line: line)
}
public func checkComparable(
- expected: ExpectedComparisonResult, _ lhs: T, _ rhs: T,
+ expected: ExpectedComparisonResult,
+ _ lhs: T, _ rhs: T,
file: StaticString = #file, line: UInt = #line
) {
checkComparable(
@@ -92,78 +102,86 @@ public func checkComparable(
public func _checkComparable(
_ instances: Instances,
oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult,
+ maxSamples: Int? = nil,
file: StaticString = #file, line: UInt = #line
-) where Instances.Element: Comparable {
+) where Instances.Element: Comparable, Instances.Index == Int {
let entry = TestContext.current.push("checkComparable", file: file, line: line)
defer { TestContext.current.pop(entry) }
- for i in instances.indices {
- let x = instances[i]
- expectFalse(
- x < x,
- "found 'x < x' at index \(i): \(String(reflecting: x))")
+ withSomeRanges(
+ "range", in: 0 ..< instances.count - 1, maxSamples: maxSamples
+ ) { range in
+ let i = range.lowerBound
+ let j = range.upperBound
- expectFalse(
- x > x,
- "found 'x > x' at index \(i): \(String(reflecting: x))")
+ if i == j {
+ let x = instances[i]
- expectTrue(x <= x,
- "found 'x <= x' to be false at index \(i): \(String(reflecting: x))")
+ expectFalse(
+ x < x,
+ "found 'x < x' at index \(i): \(String(reflecting: x))")
- expectTrue(x >= x,
- "found 'x >= x' to be false at index \(i): \(String(reflecting: x))")
+ expectFalse(
+ x > x,
+ "found 'x > x' at index \(i): \(String(reflecting: x))")
- for j in instances.indices where i != j {
+ expectTrue(x <= x,
+ "found 'x <= x' to be false at index \(i): \(String(reflecting: x))")
+
+ expectTrue(x >= x,
+ "found 'x >= x' to be false at index \(i): \(String(reflecting: x))")
+ } else {
+ let x = instances[i]
let y = instances[j]
-
+
let expected = oracle(i, j)
-
+
expectEqual(
expected.flip(), oracle(j, i),
- """
+ """
bad oracle: missing antisymmetry:
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
-
+
expectEqual(
expected == .lt, x < y,
- """
+ """
x < y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
-
+
expectEqual(
expected != .gt, x <= y,
- """
+ """
x <= y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
-
+
expectEqual(
expected != .lt, x >= y,
- """
+ """
x >= y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
-
+
expectEqual(
expected == .gt, x > y,
- """
+ """
x > y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
-
- for k in instances.indices {
+
+ withSome("k", in: instances.indices, maxSamples: 10) { k in
let expected2 = oracle(j, k)
if expected == expected2 {
expectEqual(
expected, oracle(i, k),
- """
+ """
bad oracle: transitivity violation
x (at index \(i)): \(String(reflecting: x))
y (at index \(j)): \(String(reflecting: y))
diff --git a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift
index 1b58b2e6..f4261dd7 100644
--- a/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift
+++ b/Sources/_CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift
@@ -14,6 +14,7 @@
public func checkEquatable(
equivalenceClasses: [[Instance]],
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) {
@@ -25,6 +26,7 @@ public func checkEquatable(
public func checkEquatable(
_ instances: C,
oracle: (C.Index, C.Index) -> Bool,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) where C.Element: Equatable {
@@ -48,6 +50,7 @@ public func checkEquatable(
public func checkEquatable(
_ instances: [Instance],
oracle: (Int, Int) -> Bool,
+ maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) {
@@ -57,21 +60,27 @@ public func checkEquatable(
// set of equal instances.
var transitivityScoreboard: [Box>] = instances.map { _ in Box([]) }
- for i in instances.indices {
+ withSomeRanges(
+ "range", in: 0 ..< instances.count - 1, maxSamples: maxSamples
+ ) { range in
+ let i = range.lowerBound
+ let j = range.upperBound
+
+ if i == j {
+ expectTrue(oracle(i, i),
+ "bad oracle: broken reflexivity at index \(i)")
+ }
let x = instances[i]
- expectTrue(oracle(i, i),
- "bad oracle: broken reflexivity at index \(i)")
+ let y = instances[j]
- for j in instances.indices {
- let y = instances[j]
-
- let expectedXY = oracle(i, j)
- expectEqual(oracle(j, i), expectedXY,
- "bad oracle: broken symmetry between indices \(i), \(j)")
-
- let actualXY = (x == y)
- expectEqual(
- actualXY, expectedXY,
+ let expectedXY = oracle(i, j)
+ expectEqual(oracle(j, i), expectedXY,
+ "bad oracle: broken symmetry between indices \(i), \(j)")
+
+ let actualXY = (x == y)
+ let actualYX = (y == x)
+ expectEqual(
+ actualXY, expectedXY,
"""
Elements \((expectedXY
? "expected equal, found not equal"
@@ -80,37 +89,47 @@ public func checkEquatable(
rhs (at index \(j)): \(String(reflecting: y))
""")
- // Not-equal is an inverse of equal.
- expectNotEqual(
- x != y, actualXY,
+ expectEqual(
+ actualYX, actualXY,
+ """
+ Reflexivity violation:
+ \(actualXY
+ ? "lhs == rhs but !(rhs == lhs)"
+ : "!(lhs == rhs) but rhs == lhs")
+ lhs (at index \(i)): \(String(reflecting: x))
+ rhs (at index \(j)): \(String(reflecting: y))
+ """)
+
+ // Not-equal must be the inverse of equal.
+ expectNotEqual(
+ x != y, actualXY,
"""
`!=` returns the same result as `==`:
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
-
- // Check transitivity of the predicate represented by the oracle.
- // If we are adding the instance `j` into an equivalence set, check that
- // it is equal to every other instance in the set.
- if expectedXY && i < j && transitivityScoreboard[i].value.insert(j).inserted {
- if transitivityScoreboard[i].value.count == 1 {
- transitivityScoreboard[i].value.insert(i)
- }
- for k in transitivityScoreboard[i].value {
- expectTrue(
- oracle(j, k),
+
+ // Check transitivity of the predicate represented by the oracle.
+ // If we are adding the instance `j` into an equivalence set, check that
+ // it is equal to every other instance in the set.
+ if expectedXY && i < j && transitivityScoreboard[i].value.insert(j).inserted {
+ if transitivityScoreboard[i].value.count == 1 {
+ transitivityScoreboard[i].value.insert(i)
+ }
+ for k in transitivityScoreboard[i].value {
+ expectTrue(
+ oracle(j, k),
"""
bad oracle: transitivity violation
x (at index \(i)): \(String(reflecting: x))
y (at index \(j)): \(String(reflecting: y))
z (at index \(k)): \(String(reflecting: instances[k]))
""")
- // No need to check equality between actual values, we will check
- // them with the checks above.
- }
- precondition(transitivityScoreboard[j].value.isEmpty)
- transitivityScoreboard[j] = transitivityScoreboard[i]
+ // No need to check equality between actual values, we will check
+ // them with the checks above.
}
+ precondition(transitivityScoreboard[j].value.isEmpty)
+ transitivityScoreboard[j] = transitivityScoreboard[i]
}
}
}
diff --git a/Sources/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift b/Sources/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift
new file mode 100644
index 00000000..f147ef9a
--- /dev/null
+++ b/Sources/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift
@@ -0,0 +1,90 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+public struct IndexRangeCollection
+where Bound.Stride == Int
+{
+ var _bounds: Range
+
+ public init(bounds: Range) {
+ self._bounds = bounds
+ }
+}
+
+extension IndexRangeCollection: RandomAccessCollection {
+ public typealias Element = Range
+ public typealias Iterator = IndexingIterator
+ public typealias SubSequence = Slice
+ public typealias Indices = DefaultIndices
+
+ public struct Index: Comparable {
+ var _start: Int
+ var _end: Int
+
+ internal init(_start: Int, end: Int) {
+ assert(_start >= 0 && _start <= end)
+ self._start = _start
+ self._end = end
+ }
+
+ internal init(_offset: Int) {
+ assert(_offset >= 0)
+ let end = ((8 * _offset + 1)._squareRoot() - 1) / 2
+ let base = end * (end + 1) / 2
+ self._start = _offset - base
+ self._end = end
+ }
+
+ internal var _offset: Int {
+ return _end * (_end + 1) / 2 + _start
+ }
+
+ public static func ==(left: Self, right: Self) -> Bool {
+ left._start == right._start && left._end == right._end
+ }
+
+ public static func <(left: Self, right: Self) -> Bool {
+ (left._end, left._start) < (right._end, right._start)
+ }
+ }
+
+ public var count: Int { (_bounds.count + 1) * (_bounds.count + 2) / 2 }
+
+ public var isEmpty: Bool { false }
+ public var startIndex: Index { Index(_start: 0, end: 0) }
+ public var endIndex: Index { Index(_start: 0, end: _bounds.count + 1) }
+
+ public func index(after i: Index) -> Index {
+ guard i._start < i._end else {
+ return Index(_start: 0, end: i._end + 1)
+ }
+ return Index(_start: i._start + 1, end: i._end)
+ }
+
+ public func index(before i: Index) -> Index {
+ guard i._start > 0 else {
+ return Index(_start: i._end - 1, end: i._end - 1)
+ }
+ return Index(_start: i._start - 1, end: i._end)
+ }
+
+ public func index(_ i: Index, offsetBy distance: Int) -> Index {
+ Index(_offset: i._offset + distance)
+ }
+
+ public subscript(position: Index) -> Range {
+ precondition(position._end <= _bounds.count)
+ return Range(
+ uncheckedBounds: (
+ lower: _bounds.lowerBound.advanced(by: position._start),
+ upper: _bounds.lowerBound.advanced(by: position._end)))
+ }
+}
diff --git a/Sources/_CollectionsTestSupport/Utilities/Integer Square Root.swift b/Sources/_CollectionsTestSupport/Utilities/Integer Square Root.swift
new file mode 100644
index 00000000..59e10752
--- /dev/null
+++ b/Sources/_CollectionsTestSupport/Utilities/Integer Square Root.swift
@@ -0,0 +1,26 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 FixedWidthInteger {
+ internal func _squareRoot() -> Self {
+ // Newton's method
+ precondition(self >= 0)
+ guard self != 0 else { return 0 }
+ var x: Self = 1 &<< ((self.bitWidth + 1) / 2)
+ var y: Self = 0
+ while true {
+ y = (self / x + x) &>> 1
+ if x == y || x == y - 1 { break }
+ x = y
+ }
+ return x
+ }
+}
diff --git a/Sources/_CollectionsTestSupport/Utilities/RandomStableSample.swift b/Sources/_CollectionsTestSupport/Utilities/RandomStableSample.swift
new file mode 100644
index 00000000..663169ed
--- /dev/null
+++ b/Sources/_CollectionsTestSupport/Utilities/RandomStableSample.swift
@@ -0,0 +1,69 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+// Note: This comes from swift-algorithms.
+
+extension Collection {
+ /// Randomly selects the specified number of elements from this collection,
+ /// maintaining their relative order.
+ ///
+ /// - Parameters:
+ /// - k: The number of elements to randomly select.
+ /// - rng: The random number generator to use for the sampling.
+ /// - Returns: An array of `k` random elements. If `k` is greater than this
+ /// collection's count, then this method returns the full collection.
+ ///
+ /// - Complexity: O(*n*), where *n* is the length of the collection.
+ @inlinable
+ public func randomStableSample(
+ count k: Int, using rng: inout G
+ ) -> [Element] {
+ guard k > 0 else { return [] }
+
+ var remainingCount = count
+ guard k < remainingCount else { return Array(self) }
+
+ var result: [Element] = []
+ result.reserveCapacity(k)
+
+ var i = startIndex
+ var countToSelect = k
+ while countToSelect > 0 {
+ let r = Int.random(in: 0.. [Element] {
+ var g = SystemRandomNumberGenerator()
+ return randomStableSample(count: k, using: &g)
+ }
+}
diff --git a/Tests/BitCollectionsTests/BitArrayTestSupport.swift b/Tests/BitCollectionsTests/BitArrayTestSupport_orig.swift
similarity index 100%
rename from Tests/BitCollectionsTests/BitArrayTestSupport.swift
rename to Tests/BitCollectionsTests/BitArrayTestSupport_orig.swift
diff --git a/Tests/BitCollectionsTests/BitArrayTests.swift b/Tests/BitCollectionsTests/BitArrayTests.swift
index 77883038..8e672e42 100644
--- a/Tests/BitCollectionsTests/BitArrayTests.swift
+++ b/Tests/BitCollectionsTests/BitArrayTests.swift
@@ -1,515 +1,614 @@
+//===----------------------------------------------------------------------===//
//
-// File.swift
-//
+// This source file is part of the Swift Collections open source project
//
-// Created by Mahanaz Atiqullah on 7/27/21.
+// 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
+//
+//===----------------------------------------------------------------------===//
-#if false
import XCTest
import _CollectionsTestSupport
-@testable import BitCollections
+@_spi(Testing) import BitCollections
-final class BitArrayTest: CollectionTestCase {
-
- typealias WORD = BitArray.WORD
- let sizes: [Int] = _getSizes(BitArray.WORD.bitWidth)
-
- func testEmptyInit() {
- let emptyBitArray = BitArray()
- expectEqual(emptyBitArray.storage, [])
- expectEqual(emptyBitArray.excess, 0)
- expectEqual(emptyBitArray.count, 0)
- expectEqual(emptyBitArray.startIndex, 0)
- expectEqual(emptyBitArray.endIndex, 0)
- expectEqual(emptyBitArray, emptyBitArray)
- }
-
- func testSequenceInitializer() {
- withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: BitArray.WORD.bitWidth) { boolArray in
- let testBitArray: BitArray = BitArray(boolArray)
- expectEqual(Array(testBitArray), boolArray)
- expectEqual(testBitArray.count, boolArray.count)
- expectEqual(testBitArray.endIndex, boolArray.count)
- expectEqual(testBitArray.excess, WORD(boolArray.count%WORD.bitWidth))
- }
- }
-
- func testExpressibleByArrayLiteralAndArrayLiteralInit() {
- withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: BitArray.WORD.bitWidth) { boolArray in
- let testBitArray = BitArray(boolArray)
- expectEqual(Array(testBitArray), boolArray)
- }
-
- // Using manually created Bool Arrays
- let testBitArray1: BitArray = []
- expectEqual(Array(testBitArray1), [])
- expectEqual(testBitArray1.excess, WORD(testBitArray1.count%WORD.bitWidth))
- expectEqual(testBitArray1.count, 0)
-
- let testBitArray2: BitArray = [true]
- expectEqual(Array(testBitArray2), [true])
- expectEqual(testBitArray2.storage, [1])
- expectEqual(testBitArray2.excess, WORD(testBitArray2.count%WORD.bitWidth))
- expectEqual(testBitArray2.count, 1)
-
- let testBitArray3: BitArray = [false]
- expectEqual(Array(testBitArray3), [false])
- expectEqual(testBitArray3.storage, [0])
- expectEqual(testBitArray3.excess, WORD(testBitArray3.count%WORD.bitWidth))
- expectEqual(testBitArray3.count, 1)
-
- let testBitArray4: BitArray = [true, true, true, true, true, true, true, true]
- expectEqual(Array(testBitArray4), [true, true, true, true, true, true, true, true])
- expectEqual(testBitArray4.storage, [255])
- expectEqual(testBitArray4.excess, WORD(testBitArray4.count%WORD.bitWidth))
- expectEqual(testBitArray4.count, 8)
-
- let testBitArray4B: BitArray = [true, true, true, true, true, true, true, true, true]
- expectEqual(Array(testBitArray4B), [true, true, true, true, true, true, true, true, true])
- expectEqual(testBitArray4B.excess, WORD(testBitArray4B.count%WORD.bitWidth))
- expectEqual(testBitArray4B.count, 9)
-
- let testBitArray5: BitArray = [false, false, false, false, false, false, false, false]
- expectEqual(Array(testBitArray5), [false, false, false, false, false, false, false, false])
- expectEqual(testBitArray5.storage, [0])
- expectEqual(testBitArray5.excess, WORD(testBitArray5.count%WORD.bitWidth))
- expectEqual(testBitArray5.count, 8)
-
- let testBitArray5B: BitArray = [false, false, false, false, false, false, false, false, false]
- expectEqual(Array(testBitArray5B), [false, false, false, false, false, false, false, false, false])
- expectEqual(testBitArray5B.excess, WORD(testBitArray5B.count%WORD.bitWidth))
- expectEqual(testBitArray5B.count, 9)
-
- let testBitArray6: BitArray = [true, false, true, false, false, false, true]
- expectEqual(Array(testBitArray6), [true, false, true, false, false, false, true])
- expectEqual(testBitArray6.storage, [69])
- expectEqual(testBitArray6.excess, WORD(testBitArray6.count%WORD.bitWidth))
- expectEqual(testBitArray6.count, 7)
- }
-
- func testRepeatingInit() {
- for count in 0...3*(WORD.bitWidth) {
- let trueArray = Array(repeating: true, count: count)
- let falseArray = Array(repeating: false, count: count)
-
- let trueBitArray = BitArray(repeating: true, count: count)
- let falseBitArray = BitArray(repeating: false, count: count)
-
- let repeatCount = (count%(WORD.bitWidth) == 0) ? Int(count/(WORD.bitWidth)) : Int(count/(WORD.bitWidth)) + 1
- let expectedFalseStorage: [WORD] = Array(repeating: 0, count: repeatCount)
- var expectedTrueStorage: [WORD] = Array(repeating: WORD.max, count: repeatCount)
- if (count%(WORD.bitWidth) != 0) {
- expectedTrueStorage.removeLast()
- let remaining = count%(WORD.bitWidth)
- var valueToAdd: WORD = 0
- for shift in 0.. bitArrayFromSet.storage.count) {
- for index in 0..(
+ _ value: S
+ ) -> BitArray where S.Element == Bool {
+ BitArray(value)
+ }
+}
+
+func randomBoolArray(count: Int) -> [Bool] {
+ var rng = SystemRandomNumberGenerator()
+ return randomBoolArray(count: count, using: &rng)
+}
+
+func randomBoolArray(
+ count: Int, using rng: inout R
+) -> [Bool] {
+ let wordCount = (count + UInt.bitWidth - 1) / UInt.bitWidth
+ var array: [Bool] = []
+ array.reserveCapacity(wordCount * UInt.bitWidth)
+ for _ in 0 ..< wordCount {
+ var word: UInt = rng.next()
+ for _ in 0 ..< UInt.bitWidth {
+ array.append(word & 1 == 1)
+ word &>>= 1
+ }
+ }
+ array.removeLast(array.count - count)
+ return array
+}
+
+final class BitArrayTests: CollectionTestCase {
+ func test_empty_initializer() {
+ let array = BitArray()
+ expectEqual(array.count, 0)
+ expectEqual(array.isEmpty, true)
+ expectEqual(array.startIndex, 0)
+ expectEqual(array.endIndex, 0)
+ expectEqualElements(array, [])
+ }
+
+ func test_RandomAccessCollection() {
+ var rng = RepeatableRandomNumberGenerator(seed: 0)
+ withEvery("count", in: [0, 1, 2, 13, 64, 65, 127, 128, 129]) { count in
+ let reference = randomBoolArray(count: count, using: &rng)
+ let value = BitArray(reference)
+ print(count)
+ checkBidirectionalCollection(
+ value, expectedContents: reference, maxSamples: 100)
+ }
+ }
+
+ func test_init_Sequence_BitArray() {
+ var rng = RepeatableRandomNumberGenerator(seed: 0)
+ withEvery("count", in: [0, 1, 2, 13, 64, 65, 127, 128, 129]) { count in
+ let reference = BitArray(randomBoolArray(count: count, using: &rng))
+ let value = BitArray._fromSequence(reference)
+ expectEqualElements(value, reference)
+
+ let value2 = BitArray(reference)
+ expectEqualElements(value2, reference)
+ }
+ }
+
+ func test_init_Sequence_BitArray_SubSequence() {
+ var rng = RepeatableRandomNumberGenerator(seed: 0)
+ withEvery("count", in: [0, 1, 2, 13, 64, 65, 127, 128, 129]) { count in
+ let array = randomBoolArray(count: count, using: &rng)
+ let ref = BitArray(array)
+ withSomeRanges("range", in: 0 ..< count, maxSamples: 100) { range in
+ let value = BitArray._fromSequence(ref[range])
+ expectEqualElements(value, array[range])
+
+ let value2 = BitArray(ref[range])
+ expectEqualElements(value2, array[range])
+ }
+ }
+ }
+
+ func test_MutableCollection() {
+ var rng = RepeatableRandomNumberGenerator(seed: 0)
+ withEvery("count", in: [0, 1, 2, 13, 64, 65, 127, 128, 129]) { count in
+ var ref = randomBoolArray(count: count, using: &rng)
+ let replacements = randomBoolArray(count: count, using: &rng)
+ var value = BitArray(ref)
+ withSome("i", in: 0 ..< count, maxSamples: 100) { i in
+ ref[i] = replacements[i]
+ value[i] = replacements[i]
+ expectEqualElements(value, ref)
+ }
+ }
+ }
+
+ func test_fill() {
+ var rng = RepeatableRandomNumberGenerator(seed: 0)
+ withEvery("count", in: [0, 1, 2, 13, 64, 65, 128, 129]) { count in
+ withSomeRanges("range", in: 0 ..< count, maxSamples: 200) { range in
+ withEvery("v", in: [false, true]) { v in
+ var ref = randomBoolArray(count: count, using: &rng)
+ var value = BitArray(ref)
+ ref.replaceSubrange(range, with: repeatElement(v, count: range.count))
+ value.fill(in: range, with: v)
+ expectEqualElements(value, ref)
+ }
+ }
+
+ var value = BitArray(randomBoolArray(count: count, using: &rng))
+ value.fill(with: false)
+ expectEqualElements(value, repeatElement(false, count: count))
+ value.fill(with: true)
+ expectEqualElements(value, repeatElement(true, count: count))
+ }
+ }
+
+ func test_init_bitPattern() {
+ expectEqualElements(
+ BitArray(bitPattern: 42 as UInt8),
+ [false, true, false, true, false, true, false, false])
+
+ withSome(
+ "value", in: -1_000_000 ..< 1_000_000, maxSamples: 1000
+ ) { value in
+ let actual = BitArray(bitPattern: value)
+ var expected: [Bool] = []
+ var v = value
+ for _ in 0 ..< Int.bitWidth {
+ expected.append(v & 1 == 1)
+ v &>>= 1
+ }
+ expectEqualElements(actual, expected)
+ }
+ }
+
+ func test_init_BitSet() {
+ expectEqualElements(BitArray(BitSet([])), [])
+ expectEqualElements(BitArray(BitSet([0])), [true])
+ expectEqualElements(BitArray(BitSet([1])), [false, true])
+ expectEqualElements(BitArray(BitSet([0, 1])), [true, true])
+ expectEqualElements(BitArray(BitSet([1, 2])), [false, true, true])
+ expectEqualElements(BitArray(BitSet([0, 2])), [true, false, true])
+
+ expectEqualElements(
+ BitArray(BitSet([1, 3, 6, 7])),
+ [false, true, false, true, false, false, true, true])
+
+ withEvery("count", in: [5, 63, 64, 65, 100, 1000]) { count in
+ var reference = randomBoolArray(count: count)
+ reference[reference.count - 1] = true // Fix the size of the bitset
+ let bitset = BitSet(reference.indices.filter { reference[$0] })
+ let actual = BitArray(bitset)
+ expectEqualElements(actual, reference)
+ }
+ }
+
+ func test_init_repeating() {
+ withEvery("count", in: [0, 1, 2, 13, 63, 64, 65, 127, 128, 129, 1000]) { count in
+ withEvery("v", in: [false, true]) { v in
+ let value = BitArray(repeating: v, count: count)
+ let reference = repeatElement(v, count: count)
+ expectEqualElements(value, reference)
+ }
+ }
+ }
+
+ func test_ExpressibleByArrayLiteral() {
+ let a: BitArray = []
+ expectEqualElements(a, [])
+
+ let b: BitArray = [true]
+ expectEqualElements(b, [true])
+
+ let c: BitArray = [true, false, false]
+ expectEqualElements(c, [true, false, false])
+
+ let d: BitArray = [true, false, false, false, true]
+ expectEqualElements(d, [true, false, false, false, true])
+
+ let e: BitArray = [
+ true, false, false, false, true, false, false,
+ true, true, false, false, true, false, false,
+ false, false, false, false, true, false, false,
+ true, false, true, false, true, false, false,
+ true, false, false, true, true, false, false,
+ true, false, false, false, false, false, false,
+ false, false, true, false, true, true, false,
+ true, false, false, false, true, false, true,
+ true, true, false, false, true, true, true,
+ ]
+ expectEqualElements(e, [
+ true, false, false, false, true, false, false,
+ true, true, false, false, true, false, false,
+ false, false, false, false, true, false, false,
+ true, false, true, false, true, false, false,
+ true, false, false, true, true, false, false,
+ true, false, false, false, false, false, false,
+ false, false, true, false, true, true, false,
+ true, false, false, false, true, false, true,
+ true, true, false, false, true, true, true,
+ ])
+ }
+
+ func test_Hashable() {
+ // This is a silly test, but it does exercise hashing a bit.
+ let classes: [[BitArray]] = [
+ [[]],
+ [[false], [false]],
+ [[false, false], [false, false]],
+ [[false, false, true], [false, false, true]],
+ [[false, false, true, false, false],
+ [false, false, true, false, false]],
+ ]
+ checkHashable(equivalenceClasses: classes)
+ }
+
+ func test_replaceSubrange_Array() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSomeRanges("range", in: 0 ..< count, maxSamples: 50) { range in
+ withEvery(
+ "length", in: [0, 1, range.count, 2 * range.count]
+ ) { length in
+ var reference = randomBoolArray(count: count)
+ let replacement = randomBoolArray(count: length)
+ var actual = BitArray(reference)
+
+ reference.replaceSubrange(range, with: replacement)
+ actual.replaceSubrange(range, with: replacement)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+ }
+
+ func test_replaceSubrange_BitArray() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSomeRanges("range", in: 0 ..< count, maxSamples: 50) { range in
+ withEvery(
+ "length", in: [0, 1, range.count, 2 * range.count]
+ ) { length in
+ var reference = randomBoolArray(count: count)
+ let value = BitArray(reference)
+
+ let refReplacement = randomBoolArray(count: length)
+ let replacement = BitArray(refReplacement)
+
+ reference.replaceSubrange(range, with: refReplacement)
+
+ var actual = value
+ actual.replaceSubrange(range, with: replacement)
+ expectEqualElements(actual, reference)
+
+ // Also check through the generic API
+ func forceCollection(_ v: C) where C.Element == Bool {
+ var actual = value
+ actual.replaceSubrange(range, with: v)
+ expectEqualElements(actual, reference)
+ }
+ forceCollection(replacement)
+ }
+ }
+ }
+ }
+
+ func test_replaceSubrange_BitArray_SubSequence() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSomeRanges("range", in: 0 ..< count, maxSamples: 25) { range in
+ withSomeRanges(
+ "replacementRange",
+ in: 0 ..< count,
+ maxSamples: 10
+ ) { replacementRange in
+ var reference = randomBoolArray(count: count)
+ let value = BitArray(reference)
+
+ let refReplacement = randomBoolArray(count: count)
+ let replacement = BitArray(refReplacement)
+
+ reference.replaceSubrange(
+ range, with: refReplacement[replacementRange])
+
+ var actual = value
+ actual.replaceSubrange(range, with: replacement[replacementRange])
+ expectEqualElements(actual, reference)
+
+ // Also check through the generic API
+ func forceCollection(_ v: C) where C.Element == Bool {
+ var actual = value
+ actual.replaceSubrange(range, with: v)
+ expectEqualElements(actual, reference)
+ }
+ forceCollection(replacement[replacementRange])
+ }
+ }
+ }
+ }
+
+ func test_append() {
+ withEvery("count", in: 0 ..< 129) { count in
+ withEvery("v", in: [false, true]) { v in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+ reference.append(v)
+ actual.append(v)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_append_Sequence() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSome("length", in: 0 ..< 256, maxSamples: 50) { length in
+ let reference = randomBoolArray(count: count)
+ let addition = randomBoolArray(count: length)
+
+ let value = BitArray(reference)
+
+ func check(_ addition: S) where S.Element == Bool {
+ var ref = reference
+ var actual = value
+
+ ref.append(contentsOf: addition)
+ actual.append(contentsOf: addition)
+ expectEqualElements(actual, ref)
+ }
+ check(addition)
+ check(BitArray(addition))
+ check(BitArray(addition)[...])
+ }
+ }
+ }
+
+ func test_append_BitArray() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSome("length", in: 0 ..< 256, maxSamples: 50) { length in
+ var reference = randomBoolArray(count: count)
+ let addition = randomBoolArray(count: length)
+
+ var actual = BitArray(reference)
+
+ reference.append(contentsOf: addition)
+ actual.append(contentsOf: BitArray(addition))
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_append_BitArray_SubSequence() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSomeRanges("range", in: 0 ..< 512, maxSamples: 50) { range in
+ var reference = randomBoolArray(count: count)
+ let addition = randomBoolArray(count: 512)
+
+ var actual = BitArray(reference)
+
+ reference.append(contentsOf: addition[range])
+ actual.append(contentsOf: BitArray(addition)[range])
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_insert() {
+ withEvery("count", in: 0 ..< 129) { count in
+ withSome("i", in: 0 ..< count + 1, maxSamples: 20) { i in
+ withEvery("v", in: [false, true]) { v in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+ reference.insert(v, at: i)
+ actual.insert(v, at: i)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+ }
+
+ func test_insert_contentsOf_Sequence() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSome("length", in: 0 ..< 256, maxSamples: 5) { length in
+ withSome("i", in: 0 ..< count + 1, maxSamples: 10) { i in
+ let reference = randomBoolArray(count: count)
+ let addition = randomBoolArray(count: length)
+
+ let value = BitArray(reference)
+
+ func check(_ addition: C) where C.Element == Bool {
+ var ref = reference
+ var actual = value
+
+ ref.insert(contentsOf: addition, at: i)
+ actual.insert(contentsOf: addition, at: i)
+ expectEqualElements(actual, ref)
+ }
+ check(addition)
+ check(BitArray(addition))
+ check(BitArray(addition)[...])
+ }
+ }
+ }
+ }
+
+ func test_insert_contentsOf_BitArray() {
+ withSome("count", in: 0 ..< 512, maxSamples: 10) { count in
+ print(count)
+ withSome("length", in: 0 ..< 256, maxSamples: 5) { length in
+ withSome("i", in: 0 ..< count + 1, maxSamples: 10) { i in
+ let reference = randomBoolArray(count: count)
+ let addition = randomBoolArray(count: length)
+
+ let value = BitArray(reference)
+
+ var ref = reference
+ var actual = value
+
+ ref.insert(contentsOf: addition, at: i)
+ actual.insert(contentsOf: BitArray(addition), at: i)
+ expectEqualElements(actual, ref)
+ }
+ }
+ }
+ }
+
+ func test_remove() {
+ withSome("count", in: 0 ..< 512, maxSamples: 50) { count in
+ withSome("i", in: 0 ..< count, maxSamples: 30) { i in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+
+ let v1 = reference.remove(at: i)
+ let v2 = actual.remove(at: i)
+ expectEqual(v2, v1)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_removeSubrange() {
+ withSome("count", in: 0 ..< 512, maxSamples: 50) { count in
+ withSomeRanges("range", in: 0 ..< count, maxSamples: 50) { range in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+ reference.removeSubrange(range)
+ actual.removeSubrange(range)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_removeLast() {
+ withEvery("count", in: 1 ..< 512) { count in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+ let v1 = reference.removeLast()
+ let v2 = actual.removeLast()
+ expectEqual(v1, v2)
+ expectEqualElements(actual, reference)
+ }
+ }
+
+ func test_removeFirst() {
+ withEvery("count", in: 1 ..< 512) { count in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+ let v1 = reference.removeFirst()
+ let v2 = actual.removeFirst()
+ expectEqual(v1, v2)
+ expectEqualElements(actual, reference)
+ }
+ }
+
+ func test_removeFirst_n() {
+ withSome("count", in: 0 ..< 512, maxSamples: 50) { count in
+ withSome("n", in: 0 ... count, maxSamples: 30) { n in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+
+ reference.removeFirst(n)
+ actual.removeFirst(n)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_removeLast_n() {
+ withSome("count", in: 0 ..< 512, maxSamples: 50) { count in
+ withSome("n", in: 0 ... count, maxSamples: 30) { n in
+ var reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+
+ reference.removeLast(n)
+ actual.removeLast(n)
+ expectEqualElements(actual, reference)
+ }
+ }
+ }
+
+ func test_removeAll() {
+ withSome("count", in: 0 ..< 512, maxSamples: 50) { count in
+ withEvery("keep", in: [false, true]) { keep in
+ let reference = randomBoolArray(count: count)
+ var actual = BitArray(reference)
+ actual.removeAll(keepingCapacity: keep)
+ expectEqualElements(actual, [])
+ if keep {
+ expectGreaterThanOrEqual(actual._capacity, count)
+ } else {
+ expectEqual(actual._capacity, 0)
+ }
+ }
+ }
+ }
+
+ func test_reserveCapacity() {
+ var bits = BitArray()
+ expectEqual(bits._capacity, 0)
+ bits.reserveCapacity(1)
+ expectGreaterThanOrEqual(bits._capacity, 1)
+ bits.reserveCapacity(0)
+ expectGreaterThanOrEqual(bits._capacity, 1)
+ bits.reserveCapacity(100)
+ expectGreaterThanOrEqual(bits._capacity, 100)
+ bits.reserveCapacity(0)
+ expectGreaterThanOrEqual(bits._capacity, 100)
+ bits.append(contentsOf: repeatElement(true, count: 1000))
+ expectGreaterThanOrEqual(bits._capacity, 1000)
+ bits.reserveCapacity(2000)
+ expectGreaterThanOrEqual(bits._capacity, 2000)
+ }
+
+ func test_bitwiseOr() {
+ withSome("count", in: 0 ..< 512, maxSamples: 100) { count in
+ withEvery("i", in: 0 ..< 10) { i in
+ let a = randomBoolArray(count: count)
+ let b = randomBoolArray(count: count)
+
+ let c = BitArray(a)
+ let d = BitArray(b)
+
+ let expected = zip(a, b).map { $0 || $1 }
+ let actual = c | d
+
+ expectEqualElements(actual, expected)
+ }
+ }
+ }
+
+ func test_bitwiseAnd() {
+ withSome("count", in: 0 ..< 512, maxSamples: 100) { count in
+ withEvery("i", in: 0 ..< 10) { i in
+ let a = randomBoolArray(count: count)
+ let b = randomBoolArray(count: count)
+
+ let c = BitArray(a)
+ let d = BitArray(b)
+
+ let expected = zip(a, b).map { $0 && $1 }
+ let actual = c & d
+
+ expectEqualElements(actual, expected)
+ }
+ }
+ }
+
+ func test_bitwiseXor() {
+ withSome("count", in: 0 ..< 512, maxSamples: 100) { count in
+ withEvery("i", in: 0 ..< 10) { i in
+ let a = randomBoolArray(count: count)
+ let b = randomBoolArray(count: count)
+
+ let c = BitArray(a)
+ let d = BitArray(b)
+
+ let expected = zip(a, b).map { $0 != $1 }
+ let actual = c ^ d
+
+ expectEqualElements(actual, expected)
+ }
+ }
+ }
+
+ func test_bitwiseComplement() {
+ withSome("count", in: 0 ..< 512, maxSamples: 100) { count in
+ withEvery("i", in: 0 ..< 10) { i in
+ let a = randomBoolArray(count: count)
+
+ let b = BitArray(a)
+
+ let expected = a.map { !$0 }
+ let actual = ~b
+
+ expectEqualElements(actual, expected)
+ }
+ }
}
}
-#endif
diff --git a/Tests/BitCollectionsTests/BitArrayTests_orig.swift b/Tests/BitCollectionsTests/BitArrayTests_orig.swift
new file mode 100644
index 00000000..77883038
--- /dev/null
+++ b/Tests/BitCollectionsTests/BitArrayTests_orig.swift
@@ -0,0 +1,515 @@
+//
+// File.swift
+//
+//
+// Created by Mahanaz Atiqullah on 7/27/21.
+//
+
+#if false
+import XCTest
+import _CollectionsTestSupport
+@testable import BitCollections
+
+final class BitArrayTest: CollectionTestCase {
+
+ typealias WORD = BitArray.WORD
+ let sizes: [Int] = _getSizes(BitArray.WORD.bitWidth)
+
+ func testEmptyInit() {
+ let emptyBitArray = BitArray()
+ expectEqual(emptyBitArray.storage, [])
+ expectEqual(emptyBitArray.excess, 0)
+ expectEqual(emptyBitArray.count, 0)
+ expectEqual(emptyBitArray.startIndex, 0)
+ expectEqual(emptyBitArray.endIndex, 0)
+ expectEqual(emptyBitArray, emptyBitArray)
+ }
+
+ func testSequenceInitializer() {
+ withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: BitArray.WORD.bitWidth) { boolArray in
+ let testBitArray: BitArray = BitArray(boolArray)
+ expectEqual(Array(testBitArray), boolArray)
+ expectEqual(testBitArray.count, boolArray.count)
+ expectEqual(testBitArray.endIndex, boolArray.count)
+ expectEqual(testBitArray.excess, WORD(boolArray.count%WORD.bitWidth))
+ }
+ }
+
+ func testExpressibleByArrayLiteralAndArrayLiteralInit() {
+ withSomeUsefulBoolArrays("boolArray", ofSizes: sizes, ofUnitBitWidth: BitArray.WORD.bitWidth) { boolArray in
+ let testBitArray = BitArray(boolArray)
+ expectEqual(Array(testBitArray), boolArray)
+ }
+
+ // Using manually created Bool Arrays
+ let testBitArray1: BitArray = []
+ expectEqual(Array(testBitArray1), [])
+ expectEqual(testBitArray1.excess, WORD(testBitArray1.count%WORD.bitWidth))
+ expectEqual(testBitArray1.count, 0)
+
+ let testBitArray2: BitArray = [true]
+ expectEqual(Array(testBitArray2), [true])
+ expectEqual(testBitArray2.storage, [1])
+ expectEqual(testBitArray2.excess, WORD(testBitArray2.count%WORD.bitWidth))
+ expectEqual(testBitArray2.count, 1)
+
+ let testBitArray3: BitArray = [false]
+ expectEqual(Array(testBitArray3), [false])
+ expectEqual(testBitArray3.storage, [0])
+ expectEqual(testBitArray3.excess, WORD(testBitArray3.count%WORD.bitWidth))
+ expectEqual(testBitArray3.count, 1)
+
+ let testBitArray4: BitArray = [true, true, true, true, true, true, true, true]
+ expectEqual(Array(testBitArray4), [true, true, true, true, true, true, true, true])
+ expectEqual(testBitArray4.storage, [255])
+ expectEqual(testBitArray4.excess, WORD(testBitArray4.count%WORD.bitWidth))
+ expectEqual(testBitArray4.count, 8)
+
+ let testBitArray4B: BitArray = [true, true, true, true, true, true, true, true, true]
+ expectEqual(Array(testBitArray4B), [true, true, true, true, true, true, true, true, true])
+ expectEqual(testBitArray4B.excess, WORD(testBitArray4B.count%WORD.bitWidth))
+ expectEqual(testBitArray4B.count, 9)
+
+ let testBitArray5: BitArray = [false, false, false, false, false, false, false, false]
+ expectEqual(Array(testBitArray5), [false, false, false, false, false, false, false, false])
+ expectEqual(testBitArray5.storage, [0])
+ expectEqual(testBitArray5.excess, WORD(testBitArray5.count%WORD.bitWidth))
+ expectEqual(testBitArray5.count, 8)
+
+ let testBitArray5B: BitArray = [false, false, false, false, false, false, false, false, false]
+ expectEqual(Array(testBitArray5B), [false, false, false, false, false, false, false, false, false])
+ expectEqual(testBitArray5B.excess, WORD(testBitArray5B.count%WORD.bitWidth))
+ expectEqual(testBitArray5B.count, 9)
+
+ let testBitArray6: BitArray = [true, false, true, false, false, false, true]
+ expectEqual(Array(testBitArray6), [true, false, true, false, false, false, true])
+ expectEqual(testBitArray6.storage, [69])
+ expectEqual(testBitArray6.excess, WORD(testBitArray6.count%WORD.bitWidth))
+ expectEqual(testBitArray6.count, 7)
+ }
+
+ func testRepeatingInit() {
+ for count in 0...3*(WORD.bitWidth) {
+ let trueArray = Array(repeating: true, count: count)
+ let falseArray = Array(repeating: false, count: count)
+
+ let trueBitArray = BitArray(repeating: true, count: count)
+ let falseBitArray = BitArray(repeating: false, count: count)
+
+ let repeatCount = (count%(WORD.bitWidth) == 0) ? Int(count/(WORD.bitWidth)) : Int(count/(WORD.bitWidth)) + 1
+ let expectedFalseStorage: [WORD] = Array(repeating: 0, count: repeatCount)
+ var expectedTrueStorage: [WORD] = Array(repeating: WORD.max, count: repeatCount)
+ if (count%(WORD.bitWidth) != 0) {
+ expectedTrueStorage.removeLast()
+ let remaining = count%(WORD.bitWidth)
+ var valueToAdd: WORD = 0
+ for shift in 0.. bitArrayFromSet.storage.count) {
+ for index in 0..