BitArrayModule ⟹ BitCollections

This commit is contained in:
Károly Lőrentey committed 2021-12-28 15:45:38 -08:00
1 parent 49a82fe6e1
commit 537382f2a6
14 files changed
+58 -10

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
}
}