mirror of
https://github.com/apple/swift-collections
synced 2026-11-29 05:14:20 +00:00
Review & update BitArray
This commit is contained in:
1 parent
8f2e0c79c3
commit
565c09e8d5
43 files changed
+2915
-1575
No files matched your search
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<Int>
|
||||
) {
|
||||
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<Int>
|
||||
) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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<BitArray>
|
||||
}
|
||||
|
||||
extension BitArray: RandomAccessCollection, MutableCollection {
|
||||
public typealias Index = Int
|
||||
public typealias SubSequence = Slice<BitArray>
|
||||
public typealias Indices = Range<Int>
|
||||
|
||||
@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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Int>,
|
||||
to target: Int
|
||||
) {
|
||||
_update { handle in
|
||||
handle.copy(from: range, to: target)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func _copy(
|
||||
from range: Range<Int>,
|
||||
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<S: Sequence>(
|
||||
from source: S,
|
||||
to range: Range<Int>
|
||||
) 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<Int>,
|
||||
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<Int>,
|
||||
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<S: Sequence>(
|
||||
from source: S,
|
||||
to range: Range<Int>
|
||||
) 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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<Int>, with value: Bool = true) {
|
||||
_update { handle in
|
||||
if value {
|
||||
handle.fill(in: range)
|
||||
} else {
|
||||
handle.clear(in: range)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<I: BinaryInteger>(bitPattern value: I) {
|
||||
let words = value.words.map { _Word($0) }
|
||||
let count = value.bitWidth
|
||||
self.init(_storage: words, count: count)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<S: Sequence>(_ 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<Int>, 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<C: Collection>(
|
||||
_ range: Range<Int>,
|
||||
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<Int>,
|
||||
with newElements: __owned BitArray
|
||||
) {
|
||||
replaceSubrange(range, with: newElements[...])
|
||||
}
|
||||
|
||||
public mutating func replaceSubrange(
|
||||
_ range: Range<Int>,
|
||||
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<S: Sequence>(
|
||||
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<C: Collection>(
|
||||
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<Int>) {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<Int>) {
|
||||
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<Int>) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -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<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))
|
||||
}
|
||||
|
||||
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<R>(
|
||||
_ 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<R>(
|
||||
_ 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)
|
||||
}
|
||||
}
|
||||
@@ -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..<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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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)..<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
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user