BitArray and BitSet data structures (#83)

* Create Screen Shot 2021-05-17 at 7.15.09 PM.png

* Delete Screen Shot 2021-05-17 at 7.15.09 PM.png

* Create BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Added BitArray as a product to the package

* Update Package.swift

* Update Package.swift

* Update Package.swift

* Update BitArray.swift

* Update Package.swift

* Update Collections.swift

* Update Collections.swift

* Update Package.swift

* Create BitArray.xcscheme

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* build: add a CMake based build system (#42)

Add a CMake based build system to enable bootstrapping the toolchain
with the ability to use Swift Collections in SPM.

* Update BitArray.swift

* Update BitArray.swift

* git: ignore vim swap files (#41)

* Initial conformation to Collection. Lots of faulty code right now

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* [Deque] Work around stdlib issue with Array.withContiguousStorageIfAvailable (#44)

Resolves #27.

* [manifest] Ignore CMake files (#47)

The package manager doesn’t like it when it finds unexpected non-source files in source directories.

* [meta] Update dependencies (#48)

(This only affects local development.)

* [Deque][NFC] Remove unused code (#49)

* Changes to support OpenBSD. (#52)

* [cmake] Support amd64 architecture name.

On OpenBSD, "x86_64" is called "amd64", and therefore recognition of this
name is required for the cmake build.

* [cmake] Add missing file.

This is required since, for example, `Deque+Extras` requires
`_withContiguousStorageIfAvailable_SR14663`.

* ManagedBuffer.capacity is unavailable on OpenBSD.

ManagedBuffer requires nonstandard API to implement `capacity` and
subsequently is unavailable on OpenBSD. For portability, just use
`minimumCapacity` on this platform.

* Fixed subscript to have bit manipulations

* Update BitArray.swift

* Update BitArray.swift

* Moved Collection Conformance into appropriate file

* Implements some bit manip

* Fixed issue with endIndex resetting when storage element is full

When an element of the storage array in the BitArray filled, the endIndex would reset to 0, but then would be the correct value at any other time. This was due to a calculation error in endIndex

* Update invalid OrderedDictionary invariant check. (#53)

* Added XCTests, MutableCollection Conformance, Fixed endIndex bug

MutableCollection conformance still has bugs to be fixed
Additionally, the code is still very rough
endIndex had an issue where it was 0 when the array was empty. Fixed this by switching the code for count and endIndex, and making endIndex = 1 when count is 0

* Update BitArrayTests.swift

* Fixed subscript bug

Wouldn't work sometimes when current value was true because the return for `storage[index] & mask` could be anything >= 1, and not == 1, hence resulting in a unwanted toggle of the value. Fixed by comparing a boolean value of the current value to the boolean value of the newValue instead of the integers

* Code clean up ish

* Fixing a small typo on quick help documentation. (#55)

* Modifying Existing Code From Feedback

- `endIndex` corrected
- changed `remaining` in `count` to use ternary operator instead of being a computed local variable
- added `_split` as a helper function to `subscript`
- modified `set{...}` portion of `subscript` and included comments of the different options
- removed `clear()` as `removeAll()` seems to already exist somewhere
- modified unit tests to have a new BitArray for every test instead of a shared one
- Improved `testSubscriptSetOnly()` to hopefully be more thorough

* Added Bitwise Operations (No Tests)

Both mutable and immutable OR, AND, XOR operations

* Mark OrderedSetDiffingTests with availability (#54)

* Added Rough Bitwise Operation UnitTests

* Added BitSet Files

Did not add methods as I know a lot will go in BitStorage, which Im still figuring out

* Beginning implementations for BitSet

* Mutating Bitwise Operations

Performance-UNfriendly starter implementations

* Fixed subscript set mask for the &= operation and changed fatalErrors to preconditions

changed mask on &= operation from 0 to ~mask

* Also corrected subscript set test to fail if mask of 0 was used (instead of ~mask)

* Implemented BitSet with BitArray storage type and some tests

Tests are not yet passing. Pushing early so mentor can see progress
So sorry for waiting to push so late!

* Fixed error in first BitSet test ( which is testAppend() ) so it passes!

* BitSet formUnion initial implementation

* formUnion() test added and implementation modified to pass test

formUnion() is still incomplete and needs more tests atm

* Finished formUnion() for BitSet

* Modified formUnion() to use bit shifts instead

* Initial formIntersection function for BitSet

Untested

* Added an array view for BitSet, fixed BitSet.count bug, added and modified tests

* Initial Cartesian Product implementation and unfinished test

* Update BitArrayConformances.swift

* [CMake] swift-collections → SwiftCollections (#60)

* [CMake] swift-collections → SwiftCollections

This is an integration FIXME for SwiftPM: https://github.com/apple/swift-package-manager/pull/3595#issuecomment-875201764

* [CMake] Generate exports under cmake/modules/SwiftCollectionsConfig.cmake

* Work around another MergeModules crash (#62)

* [utils] Add utility for shuffling sources to help reproduce MergeModules issues

* [Deque] Collapse Sequence/Collection conformances into a single file

The MergeModules phase in the compiler is broken: it isn’t always able to correctly handle circular dependencies across source files, like the ones that keep organically popping up with Sequence/Collection conformances that are defined in separate files.

Such dependencies sometimes triggers a compiler crash, depending on some (unknown) environmental parameters.

Trying to manually find and eliminate these circular dependencies has not proved productive. Instead, roll all Collection conformances into a single, huge source file.

* [Deque] Update CMakeLists

* [test] checkCollection: Don’t pass decreasing indices to distance(from:to:) (#63)

Also, try running the conformance checkers on the minimal collection types to catch similar issues.

* Attempting to make an Index

* First steps in implementing Index struct for BitSet

* Fixed up endIndex

* Last tweaks of tonight

Tomorrow: fix up Index implementations, SetAlgebra, Unit Testing

* Adding index function preconditions

* Altered index(_ index: Index, offsetBy distance: Int) -> Index

* Update BitSetConformances.swift

* Update BitSetBitwiseOperations.swift

* Time for SetAlgebra!

* Transitioning to using CollectionsTestSupport

* Conformance to Set Algebra (without bringing in bitarray methods)

* Overloaded Bitwise Operators on BitArray

* Tilday (bitwiseNOT operations)

* Fixed coding style - 2 space indents

* Initial implementation od initializers

Bug found

* Fixed count bug

* Completed and XCTested BitArray initializers

By"XCTested" I mean using my own XCTests without the thorough CollectionsTestSupport

* Update BitArray.swift

* BitSet Initializers -- XCTested

By "XCTested" I mean not thoroughly tested with the CollectionsTestSupport methods

* BitSet's "custom" SetAlgebra

* contains(Int) and dropExcessFalses() methods for BitSet

* Consistently use UNIT.bitWidth instead of the number 8

This will be useful for benchmarking purposes

* Modified BitArray.swift according to feedback

Also added more typealias consistencies (using `UNIT.max` instead of hardcoded 255)

* Modified BitArray bitwise operations according to feedback

Added overloaded mutating operators

* Modified BitArrayConformances.swift according to feedback

* Modified BitArrayOperations.swift according to feedbacl

* Adjust Bitwise Operations' naming to be consistent with that of the atomics package

* .

* Modified According to Feedback

* testing

* First working test using CollectionsTestSupport

Testing sequence initializer

* All initializer tests for BitArray (except using BitSet)

* Update BitArrayTests.swift

* BitArray Append test

* Improved BitArray append() test to test multiple appends

* Untested remove functions

Also updated any UInt8 usages to use the UNIT typealias instead

* BitArray removeLast() Test

* Update BitArrayTests.swift

* BitArray removeAll() test

* BitArray removeLast(_ rangeSize: Int) function test and bug fix

* BitArray removet(at: Int) tests

Also added test for discardable results for current and existing remove tests

* BitArray removeFirst(_ rangeSize: Int) test implemented and passing

Current method has terrible run time for now as I can't get the optimized version to work yet

* BitArray first and last true index functions TEST and BUG FIX

firstTrueIndex()
lastTrueIndex()

* Failing OR and AND bitwise operations test on BitArray

* Update BitArrayTests.swift

* Update BitArrayTests.swift

* Update BitArrayTests.swift

* PUSHHHHH

* removeFirst(_ rangeSize: Int) optimization/bugFix

* BitArray bitwise operations tests and bug fixes

* BitSet tests, bug fixes, and name changes

sequence init test and bug fix
change "UNIT" to "WORD"

* Update BitArrayTests.swift

* add BitSet layout to test support

* BitSet testExpressibleByArrayLiteralAndArrayLiteralInit()

* testExpressibleByArrayLiteralAndArrayLiteralInit()

* BitSet insert and contains functions test + bug fixes

* forceInsert test for BitSet

* BitSet remove function test and improvements

* Update BitSetSetAlgebra.swift

* BitSet intersection tests and bug fixes

* BitSet symmetricDifference test and bug fix

* starting index test and found interesting bug...

* BitArray init(BitSet) test

* Update BitSetTests.swift

* patch

* bug fix in BitSet index after

* BitSet index before test

* Clean up unneeded code

* Delete BitArrayBenchmarks.swift

* My added, not-working benchmark

* BitSet init from BitArray benchmark

* BiSet insert benchmark

* BitSet forceInsert benchmark

* Passing BitSet index offset by test

I plan to add more to the test to test offsets from indices in the middle and not just start and end

* BitArray testing modification to accommodate varying WORD sizes

* Minor comment clean-up

* Correcting bitset tests for varying WORD sizes

* Headers with License info

* simple set operation comparison

incomplete

* .

* adjustments

* Update BitSetOperations.swift

* Benchmarks and preconditions

* Update BitArrayOperations.swift

* Update BitSetTests.swift

* quick edits

* .

* Documentation for bitwise operations and some initializers

* Testing `==` operator to ensure bug fix

* BitSet SetAlgebra and Operations Documentation

* Update BitSetOperations.swift

Co-authored-by: Saleem Abdulrasool <compnerd@compnerd.org>
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
Co-authored-by: 3405691582 <dsk@google.com>
Co-authored-by: Vihan <vihan_bhargava@apple.com>
Co-authored-by: Rodrigo Kreutz <8869678+rkreutz@users.noreply.github.com>
Co-authored-by: Andrew Monshizadeh <1282845+amonshiz@users.noreply.github.com>
This commit is contained in:
66 files changed
+4107 -969

No files matched your search

@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
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<S>(_ 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<<i)
}
} else {
let bytes: Int = (count%(WORD.bitWidth) > 0) ? (count/(WORD.bitWidth))+1 : count/(WORD.bitWidth)
storage = Array(repeating: 0, count: bytes)
excess = WORD(count%(WORD.bitWidth))
}
}
/// 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
}
}
@@ -0,0 +1,283 @@
//===----------------------------------------------------------------------===//
//
// 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..<self.storage.endIndex {
self.storage[i] |= other.storage[i]
}
}
/// mutates self by setting the value in each index to true if both self and the passed in BitArray have a true value in that respective index.
///
/// The following example mutates a BitArray to be AND'd with another BitArray
/// var bitArray: BitArray = [true, false, true, false]
/// let secondBitArray = [true, false, false, true]
/// bitArray.formBitwiseAnd(secondBitArray)
/// print(Array(bitArray))
/// Prints "[true, false, false, false]"
///
/// - Parameters:
/// - other: An initialized BitArray. `other` must have the same count as `self`
public mutating func formBitwiseAnd(_ other: BitArray) {
precondition(self.storage.count == other.storage.count, "Bitwise operations on BitArrays of different length is currently not supported")
for i in 0..<self.storage.count {
self.storage[i] &= other.storage[i]
}
}
/// mutates self by setting the value in each index to true if either self or the passed in BitArray -- but not both -- have a true value in that respective index.
///
/// The following example mutates self to be XOR'd with another BitArray
/// var bitArray: BitArray = [true, false, true, false]
/// let secondBitArray = [true, false, false, true]
/// bitArray.formBitwiseXor(secondBitArray)
/// print(Array(bitArray))
/// Prints "[false, false, true, true]"
///
/// - Parameters:
/// - other: An initialized BitArray. `other` must have the same count as `self`
public mutating func formBitwiseXor(_ other: BitArray) {
precondition(self.storage.count == other.storage.count, "Bitwise operations on BitArrays of different length is currently not supported")
for i in 0..<self.storage.count {
self.storage[i] ^= other.storage[i]
}
}
/// mutates self by flipping each binary value in self
///
/// The following example mutates self to its own NOT or inverted self
/// var bitArray: BitArray = [true, false, true, false]
/// bitArray.formBitwiseNot()
/// print(Array(bitArray))
/// Prints "[false, true, false, true]"
public mutating func formBitwiseNot() {
if (count == 0) {
return
}
let remaining: Int = (excess == 0) ? WORD.bitWidth : Int(excess)
for i in 0..<self.storage.endIndex {
self.storage[i] = ~self.storage[i]
}
var mask: WORD = 1 << remaining
// flip the last bits past excess that aren't part of the set back to 0
for _ in 1...((WORD.bitWidth)-Int(excess)) {
self.storage[storage.endIndex-1] ^= mask
mask <<= 1
}
}
/// creates and returns a new BitArray by setting the value in each index of the new BitArray to true if either self or the passed in 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 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 "[true, 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 bitwiseOr(_ other: BitArray) -> 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)
}
}
@@ -0,0 +1,76 @@
//===----------------------------------------------------------------------===//
//
// 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))
}
}
@@ -0,0 +1,226 @@
//===----------------------------------------------------------------------===//
//
// 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)..<endIndex {
if(self[index]) {
self[index-1] = true
self[index] = false
}
}
_adjustExcessForRemove()
}
return self[at]
}
@discardableResult
public mutating func removeLast() -> 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..<range%(WORD.bitWidth) {
removeLast()
}
}
private mutating func _adjustExcessForRemove() {
if (excess == 0) {
excess = WORD(WORD.bitWidth-1)
} else {
excess -= 1
if (excess == 0) {
storage.removeLast()
}
}
}
public mutating func removeAll() {
storage = []
excess = 0
}
@discardableResult
public mutating func removeFirst() -> Bool {
precondition(self.count != 0, "The bit array is empty. There are no items to remove")
defer {
self[0] = false
for index in 1..<endIndex {
if(self[index]) {
self[index-1] = true
self[index] = false
}
}
_adjustExcessForRemove()
}
return self[0]
}
/// Removes the first several values in the beginning of the BitArray
/// self must not be empty
///
/// The following example removes the first 3 elements of a BitArray
/// var bitArray: BitArray = [true, false, true, false, true]
/// bitArray.removeFirst(3)
/// print(Array(bitArray))
/// Prints "[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 removeFirst(_ k: Int) {
precondition(self.count != 0, "The bit array is empty. There are no items to remove")
precondition(k < endIndex, "The input rangeSize is invalidly larger than the bit array itself.")
precondition(k > 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..<remainingElemCount {
self[i] = false
}
for i in remainingElemCount..<endIndex {
if (self[i]) {
self[i-remainingElemCount] = true
self[i] = false
}
}
excess = WORD(newCount)%WORD((WORD.bitWidth))
if (count != newCount) {
storage.removeLast()
}
}
}
/// Returns the index of the first 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 firstTrue: Int? = bitArray.firstTrue()
/// print(firstTrue)
/// Prints "2"
///
/// let allFalseBitArray: BitArray = [false, false, false]
/// let firstTrue: Int? = allFalseBitArray.firstTrue()
/// print(firstTrue)
/// Prints "nil"
///
/// - Returns: An optional integer value of the index where the first true was found.
/// If there are no true values in the BitArray, the function returns `nil`
public func firstTrue() -> 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
}
}
@@ -0,0 +1,66 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public struct BitSet: ExpressibleByArrayLiteral, Codable {
var storage = BitArray()
public init() { }
public init<S>(_ sequence: __owned S) where S : Sequence, Int == S.Element {
for value in sequence {
while (value >= storage.count) {
storage.storage.append(0)
}
storage[value] = true
}
storage.excess = 0
}
public init(arrayLiteral elements: Int...) {
for value in elements {
while (value >= storage.count) {
storage.storage.append(0)
}
storage[value] = true
}
storage.excess = 0
}
public init(_ bitArray: BitArray) {
storage = bitArray
// clean up overly excess false values
while(storage.storage.count != 0 && storage.storage[storage.storage.endIndex-1] == 0) {
storage.storage.removeLast()
}
storage.excess = 0
}
public struct Index {
var bitArrayIndex: Int
internal init(bitArrayIndex: Int) {
self.bitArrayIndex = bitArrayIndex
}
}
}
extension BitSet.Index: Comparable, Hashable {
public static func < (lhs: BitSet.Index, rhs: BitSet.Index) -> Bool {
return (lhs.bitArrayIndex < rhs.bitArrayIndex)
}
}
@@ -0,0 +1,105 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension BitSet: Collection, BidirectionalCollection {
public var isEmpty: Bool { return count == 0 }
public var startIndex: Index { return _getStartIndex() }
// leaving it like this might be correct if firstTrueIndex was fast enough -- BENCHMARKS
private func _getStartIndex() -> Index {
guard let index = storage.firstTrue() else {
return Index(bitArrayIndex: storage.endIndex)
}
return Index(bitArrayIndex: index)
}
public var endIndex: Index { return Index(bitArrayIndex: storage.endIndex) }
public var count: Int {
var count = 0
for byte in storage.storage {
count += byte.nonzeroBitCount
}
return count
}
public subscript(position: Index) -> Int {
get {
precondition((startIndex.bitArrayIndex <= position.bitArrayIndex) && (endIndex.bitArrayIndex > position.bitArrayIndex), "Given Index is out of range")
precondition((storage[position.bitArrayIndex]), "Index passed in is invalid: does not exist in the set")
return position.bitArrayIndex
}
}
public func index(after: Index) -> Index {
precondition((startIndex.bitArrayIndex <= after.bitArrayIndex) && (endIndex.bitArrayIndex > after.bitArrayIndex), "Given Index is out of range")
precondition((storage[after.bitArrayIndex]), "Index passed in is invalid: does not exist in the set")
precondition(after.bitArrayIndex != endIndex.bitArrayIndex, "Passed in Index is already the endIndex, and has no existing Indexes after it")
// Potentially optimizeable using leadingZeroCount/trailingZeroCount
for i in (after.bitArrayIndex+1)..<storage.count {
if (storage[i]) {
return Index(bitArrayIndex: i)
}
}
return endIndex
}
public func index(before: Index) -> Index {
precondition(before.bitArrayIndex != startIndex.bitArrayIndex, "Passed in Index is already the startIndex, and has no existing Indexes before it")
precondition((startIndex.bitArrayIndex < before.bitArrayIndex) && (endIndex.bitArrayIndex >= before.bitArrayIndex), "Given Index is out of range")
precondition( ((before == endIndex) || (storage[before.bitArrayIndex])), "Index passed in is invalid: does not exist in the set")
// Potentially optimizeable using leadingZeroCount/trailingZeroCount
for i in stride(from: (before.bitArrayIndex-1), through: 0, by: -1) {
if (storage[i]) {
return Index(bitArrayIndex: i)
}
}
fatalError("Before not found :(")
}
public func index(_ index: Index, offsetBy distance: Int) -> Index {
precondition((startIndex.bitArrayIndex <= index.bitArrayIndex) && (endIndex.bitArrayIndex >= index.bitArrayIndex), "Given Index is out of range")
precondition((index == endIndex) || (storage[index.bitArrayIndex]), "Index passed in is invalid: does not exist in the set")
precondition(self.count != 0, "Set is empty and has no indexes to iterate through")
// Potentially optimizeable using leadingZeroCount/trailingZeroCount
var counter = 0
if (distance == 0) {
return index
} else if (distance > 0) {
for i in (index.bitArrayIndex+1)..<storage.count {
if (storage[i]) {
counter += 1
}
if (counter == distance) {
return Index(bitArrayIndex: i)
}
}
fatalError("positive distance not found")
} else {
for i in (0..<index.bitArrayIndex).reversed() {
if (storage[i]) {
counter -= 1
}
if (counter == distance) {
return Index(bitArrayIndex: i)
}
}
fatalError("negative distance not found")
}
fatalError("Passed in distance points to an Index beyond the scope of the set")
}
}
@@ -0,0 +1,32 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension BitSet {
/// Checks whether the set contains a value or not
///
/// Example:
/// let bitSet: BitSet = [0, 2, 5, 6, 7]
/// let doesContain: Bool = bitSet.contains(0)
/// print(doesContain) // prints "true"
/// doesContain = bitSet.contains(8)
/// print(doesContain) // prints "false"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise returns `false`.
public func contains(_ member: Int) -> Bool {
precondition(member >= 0, "Input must be a positive number")
if (member >= storage.count) {
return false
}
return storage[member]
}
}
@@ -0,0 +1,217 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension BitSet: Equatable {
/// Inserts a new member into the set
/// The following examples insert a 2 into a set that already has a 2 and a set that doesn't, respectively
/// var bitSetWithTwo: BitSet = [0, 2, 4, 5]
/// var didInsert: Bool = bitSetWithTwo.insert(2)
/// print(didInsert)
/// // Prints "false"
/// print(Array(bitSetWithTwo))
/// // Prints "[0, 2, 4, 5]"
///
/// var bitSetWithoutTwo: BitSet = [0, 3, 4, 6]
/// didInsert = bitSetWithoutTwo.insert(2)
/// print(didInsert)
/// // Prints "true"
/// print(Array(bitSetWithoutTwo))
/// // Prints "[0, 2, 3, 4, 6]"
///
/// - Parameter newMember: An element to insert into the set
/// - Returns: `true` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `false`. Returned value is discarded without giving a warning if unused
@discardableResult
public mutating func insert(_ newMember: Int) -> Bool {
precondition(newMember >= 0, "Inserts can only be executed with a positive number. Bit sets do not hold negative values.")
if (newMember >= storage.count) {
// can also try ceil()
let padding: Double = (Double(newMember - storage.count + 1)/Double(BitArray.WORD.bitWidth)).rounded(.up)
storage.storage += Array(repeating: 0, count: Int(padding))
}
let returnVal = !storage[newMember]
storage[newMember] = true
return returnVal
}
internal mutating func _forceInsert(_ newMember: Int) {
precondition(newMember >= 0, "Inserts can only be executed with a positive number. Bit sets do not hold negative values.")
while (storage.count-1 < newMember) {
storage.storage.append(0)
}
storage[newMember] = true
}
/// Removes a member from the set
/// The following examples remove a 2 from a set that has a 2 and a set that doesn't, respectively
/// var bitSetWithTwo: BitSet = [0, 2, 4, 5]
/// var didRemove: Bool = bitSetWithTwo.remove(2)
/// print(didRemove)
/// // Prints "true"
/// print(Array(bitSetWithTwo))
/// // Prints "[0, 4, 5]"
///
/// var bitSetWithoutTwo: BitSet = [0, 3, 4, 6]
/// didRemove = bitSetWithoutTwo.remove(2)
/// print(didRemove)
/// // Prints "false"
/// print(Array(bitSetWithoutTwo))
/// // Prints "[0, 3, 4, 6]"
///
/// - Parameter member: An element to remove from the set.
/// - Returns: `true` if `member` was contained in the
/// set. If an element equal to `member` was not already contained in the
/// set, the method returns `false`. Returned value is discarded without giving a warning if unused
@discardableResult
public mutating func remove(_ member: Int) -> Bool {
precondition(member >= 0, "Removals can only be executed with a positive number. Bit sets do not hold negative values.")
if (member >= storage.endIndex) {
return false
}
let returnVal = storage[member]
storage[member] = false
return returnVal
}
/// creates a new BitSet that is the resulting union of itself and another set
/// The union is the set of values that exist in either or both sets
///
/// The following example creates a set that is the union of two sets
/// let firstBitSet: BitSet = [0, 2, 3, 5]
/// let secondBitSet: BitSet = [2, 4, 5, 6]
/// let resultSet = firstBitSet.union(secondBitSet)
/// print(Array(resultSet)) // prints "[0, 2, 3, 4, 5, 6]"
///
/// - Parameter other: Another BitSet
/// - Returns: A new BitSet with the elements that are in this set or `other` or both.
public func union(_ other: BitSet) -> BitSet {
var newBitSet = self
newBitSet.formUnion(other)
return newBitSet
}
/// creates a new BitSet that is the resulting intersection of itself and another set
/// The intersection is the set of values that exist both sets
///
/// The following example creates a set that is the union of two sets
/// let firstBitSet: BitSet = [0, 2, 3, 5]
/// let secondBitSet: BitSet = [2, 4, 5, 6]
/// let resultSet = firstBitSet.intersection(secondBitSet)
/// print(Array(resultSet)) // prints "[2, 5]"
///
/// - Parameter other: Another BitSet
/// - Returns: A new BitSet with the elements that are both in this set and `other`.
public func intersection(_ other: BitSet) -> BitSet {
var newBitSet = self
newBitSet.formIntersection(other)
return newBitSet
}
/// creates a new BitSet that is the resulting symmetric difference of itself and another set
/// The symmetric difference is the set of values that exist one set or the other, but not both
///
/// The following example creates a set that is the symmetric difference of two sets
/// let firstBitSet: BitSet = [0, 2, 3, 5]
/// let secondBitSet: BitSet = [2, 4, 5, 6]
/// let resultSet = firstBitSet.symmetricDifference(secondBitSet)
/// print(Array(resultSet)) // prints "[0, 3, 4, 6]"
///
/// - Parameter other: Another BitSet
/// - Returns: A new BitSet with the elements that are in either this set or the other set, but not both
public func symmetricDifference(_ other: BitSet) -> BitSet {
var newBitSet = self
newBitSet.formSymmetricDifference(other)
return newBitSet
}
/// mutates self to be the resulting union of itself and another set
/// The union is the set of values that exist in either or both sets
///
/// The following example takes a set and transforms it into the union of itself and another set
/// var firstBitSet: BitSet = [0, 2, 3, 5]
/// let secondBitSet: BitSet = [2, 4, 5, 6]
/// firstBitSet.formUnion(secondBitSet)
/// print(Array(firstBitSet)) // prints "[0, 2, 3, 4, 5, 6]"
///
/// - Parameter other: Another BitSet. `other` must be finite
public mutating func formUnion(_ other: BitSet) {
if (other.storage.count < self.storage.count) {
for i in 0..<other.storage.storage.count {
self.storage.storage[i] |= other.storage.storage[i]
}
} else if (self.storage.count < other.storage.count){
for j in 0..<self.storage.storage.count {
self.storage.storage[j] |= other.storage.storage[j]
}
for a in self.storage.count..<other.storage.count {
if(other.storage[a]) {
self._forceInsert(a)
}
}
} else {
for b in 0..<self.storage.storage.count {
self.storage.storage[b] |= other.storage.storage[b]
}
}
}
/// mutates self to be the resulting intersection of itself and another set
/// The intersection is the set of values that exist both sets
///
/// The following example takes a set and transforms it into the intersection of itself and another set
/// var firstBitSet: BitSet = [0, 2, 3, 5]
/// let secondBitSet: BitSet = [2, 4, 5, 6]
/// firstBitSet.formIntersection(secondBitSet)
/// print(Array(firstBitSet)) // prints "[2, 5]"
///
/// - Parameter other: Another BitSet
public mutating func formIntersection(_ other: BitSet) {
let size: Int = (self.storage.storage.count >= other.storage.storage.count) ? other.storage.storage.count : self.storage.storage.count // take the set with the smaller BitArray
for i in 0..<size {
self.storage.storage[i] &= other.storage.storage[i]
}
for i in size..<self.storage.storage.count {
self.storage.storage[i] = 0
}
}
/// mutates self to be the resulting symmetric difference of itself and another set
/// The symmetric difference is the set of values that exist one set or the other, but not both
///
/// The following example takes a set and mutates it into the symmetric difference between itself and another set
/// var firstBitSet: BitSet = [0, 2, 3, 5]
/// let secondBitSet: BitSet = [2, 4, 5, 6]
/// firstBitSet.formSymmetricDifference(secondBitSet)
/// print(Array(firstBitSet)) // prints "[0, 3, 4, 6]"
///
/// - Parameter other: Another BitSet
public mutating func formSymmetricDifference(_ other: BitSet) { // can be optimized later
if (other.storage.storage.count > self.storage.storage.count) {
for i in 0..<self.storage.storage.count {
self.storage.storage[i] ^= other.storage.storage[i]
}
for i in self.storage.storage.count..<other.storage.storage.count {
self.storage.storage.append(other.storage.storage[i])
}
} else {
for i in 0..<other.storage.storage.count {
self.storage.storage[i] ^= other.storage.storage[i]
}
}
}
public static func == (lhs: BitSet, rhs: BitSet) -> Bool {
return (lhs.storage == rhs.storage)
}
}