Merge pull request #263 from lorentey/bitcollections-finalization

BitArray API refinements & additions
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2023-04-10 17:32:10 -07:00
commit 8ca5c0367f
24 files changed
+844 -92

No files matched your search

@@ -2,7 +2,7 @@
//
// 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-2023 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
@@ -114,16 +114,50 @@ extension BitArray {
/// - Complexity: O(value.count)
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()
result.toggleAll()
return result
}
public mutating func toggleAll() {
_update { handle in
let w = handle._mutableWords
for i in 0 ..< handle._words.count {
w[i].formComplement()
}
let p = handle.end
if p.bit > 0 {
w[p.word].subtract(_Word(upTo: p.bit).complement())
}
}
_checkInvariants()
}
public mutating func toggleAll(in range: Range<Int>) {
precondition(range.upperBound <= count, "Range out of bounds")
_update { handle in
let words = handle._mutableWords
let start = _BitPosition(range.lowerBound)
let end = _BitPosition(range.upperBound)
if start.word == end.word {
let bits = _Word(from: start.bit, to: end.bit)
words[start.word].formSymmetricDifference(bits)
return
}
words[start.word].formSymmetricDifference(
_Word(upTo: start.bit).complement())
for i in stride(from: start.word + 1, to: end.word, by: 1) {
words[i].formComplement()
}
if end.bit > 0 {
words[end.word].formSymmetricDifference(_Word(upTo: end.bit))
}
}
}
@inlinable
public mutating func toggleAll<R: RangeExpression>(
in range: R
) where R.Bound == Int {
toggleAll(in: range.relative(to: self))
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Copyright (c) 2022-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Copyright (c) 2022-2023 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
@@ -1,41 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 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: CustomStringConvertible {
// A textual representation of this instance.
public var description: String {
_bitString
}
internal var _bitString: String {
var result: String
if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
result = String(unsafeUninitializedCapacity: self.count) { target in
let b0: UInt8 = 48 // ASCII 0
let b1: UInt8 = 49 // ASCII 1
var i = 0
for v in self {
target.initializeElement(at: i, to: v ? b1 : b0)
i &+= 1
}
return i
}
} else {
result = ""
result.reserveCapacity(self.count)
for v in self {
result.append(v ? "1" : "0")
}
}
if result.isEmpty { result = "0" }
return result
}
}
@@ -0,0 +1,63 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022-2023 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 UInt8 {
@inline(__always)
internal static var _ascii0: Self { 48 }
@inline(__always)
internal static var _ascii1: Self { 49 }
}
extension BitArray: CustomStringConvertible {
/// A textual representation of this instance.
/// Bit arrays print themselves as a string of binary bits, with the highest-indexed elements
/// appearing first, as in the binary representation of integers:
///
/// let bits: BitArray = [false, false, false, true, true]
/// print(bits) // "11000"
///
/// The description of an empty bit array is an empty string.
public var description: String {
_bitString
}
}
extension BitArray: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
"BitArray(\(_bitString))"
}
}
extension BitArray {
internal var _bitString: String {
guard !isEmpty else { return "" }
var result: String
if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
result = String(unsafeUninitializedCapacity: self.count) { target in
var i = count - 1
for v in self {
target.initializeElement(at: i, to: v ? ._ascii1 : ._ascii0)
i &-= 1
}
return count
}
} else {
result = ""
result.reserveCapacity(self.count)
for v in self.reversed() {
result.append(v ? "1" : "0")
}
}
return result
}
}
@@ -2,7 +2,7 @@
//
// 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-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -2,16 +2,20 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Copyright (c) 2023 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: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
"BitArray(\(_bitString))"
extension BitArray: ExpressibleByStringLiteral {
/// Creates an instance initialized with the given elements.
@inlinable
public init(stringLiteral value: String) {
guard let bits = Self(value) else {
fatalError("Invalid bit array literal")
}
self = bits
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Copyright (c) 2022-2023 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
@@ -28,3 +28,24 @@ extension BitArray {
}
}
}
extension BitArray {
public mutating func insert(
repeating value: Bool,
count: Int,
at index: Int
) {
precondition(count >= 0, "Can't insert a negative number of values")
precondition(index >= 0 && index <= count, "Index out of bounds")
guard count > 0 else { return }
_extend(by: count, with: false)
_copy(from: index ..< self.count - count, to: index + count)
fill(in: index ..< index + count, with: value)
}
public mutating func append(repeating value: Bool, count: Int) {
precondition(count >= 0, "Can't append a negative number of values")
guard count > 0 else { return }
_extend(by: count, with: value)
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -31,4 +31,11 @@ extension BitArray {
}
}
}
public mutating func fill<R: RangeExpression>(
in range: R,
with value: Bool = true
) where R.Bound == Int {
fill(in: range.relative(to: self), with: value)
}
}
@@ -2,7 +2,7 @@
//
// 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-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -12,6 +12,16 @@
extension BitArray {
/// Initialize a bit array from a bit set.
///
/// The result contains exactly as many bits as the maximum item in
/// the source set, plus one. If the set is empty, the result will
/// be empty, too.
///
/// BitArray([] as BitSet) // (empty)
/// BitArray([0] as BitSet) // 1
/// BitArray([1] as BitSet) // 10
/// BitArray([1, 2, 4] as BitSet) // 1011
/// BitArray([7] as BitSet) // 1000000
///
/// - Complexity: O(1)
public init(_ set: BitSet) {
guard let l = set.last else { self.init(); return }
@@ -19,11 +29,243 @@ extension BitArray {
}
/// Initialize a bit array from the binary representation of an integer.
/// The result will contain exactly `value.bitWidth` bits.
///
/// BitArray(bitPattern: 3 as UInt8) // 00000011
/// BitArray(bitPattern: 42 as Int8) // 00101010
/// BitArray(bitPattern: -1 as Int8) // 11111111
/// BitArray(bitPattern: 3 as Int16) // 0000000000000111
/// BitArray(bitPattern: 42 as Int16) // 0000000000101010
/// BitArray(bitPattern: -1 as Int16) // 1111111111111111
/// BitArray(bitPattern: 3 as Int) // 0000000000...0000000111
/// BitArray(bitPattern: 42 as Int) // 0000000000...0000101010
/// BitArray(bitPattern: -1 as Int) // 1111111111...1111111111
///
/// - Complexity: O(value.bitWidth)
public init<I: BinaryInteger>(bitPattern value: I) {
let words = value.words.map { _Word($0) }
var words = value.words.map { _Word($0) }
let count = value.bitWidth
if words.isEmpty {
precondition(count == 0, "Inconsistent bitWidth")
} else {
let (w, b) = _UnsafeHandle._BitPosition(count).endSplit
precondition(words.count == w + 1, "Inconsistent bitWidth")
words[w].formIntersection(_Word(upTo: b))
}
self.init(_storage: words, count: count)
}
/// Creates a new, empty bit array with preallocated space for at least the
/// specified number of elements.
public init(minimumCapacity: Int) {
self.init()
reserveCapacity(minimumCapacity)
}
}
extension BinaryInteger {
@inlinable
internal static func _convert(
_ source: BitArray
) -> (value: Self, isNegative: Bool) {
var value: Self = .zero
let isNegative = source._foreachTwosComplementWordDownward(
isSigned: Self.isSigned
) { _, word in
value <<= UInt.bitWidth
value |= Self(truncatingIfNeeded: word)
return true
}
return (value, isNegative)
}
/// Creates a new instance by truncating or extending the bits in the given
/// bit array, as needed. The bit at position 0 in `source` will correspond
/// to the least-significant bit in the result.
///
/// If `Self` is an unsigned integer type, then the result will contain as
/// many bits from `source` it can accommodate, truncating off any extras.
///
/// UInt8(truncatingIfNeeded: "" as BitArray) // 0
/// UInt8(truncatingIfNeeded: "0" as BitArray) // 0
/// UInt8(truncatingIfNeeded: "1" as BitArray) // 1
/// UInt8(truncatingIfNeeded: "11" as BitArray) // 3
/// UInt8(truncatingIfNeeded: "11111111" as BitArray) // 255
/// UInt8(truncatingIfNeeded: "1100000001" as BitArray) // 1
/// UInt8(truncatingIfNeeded: "1100000101" as BitArray) // 5
///
/// If `Self` is a signed integer type, then the contents of the bit array
/// are interpreted to be a two's complement representation of a signed
/// integer value, with the last bit in the array representing the sign of
/// the result.
///
/// Int8(truncatingIfNeeded: "" as BitArray) // 0
/// Int8(truncatingIfNeeded: "0" as BitArray) // 0
/// Int8(truncatingIfNeeded: "1" as BitArray) // -1
/// Int8(truncatingIfNeeded: "01" as BitArray) // 1
/// Int8(truncatingIfNeeded: "101" as BitArray) // -3
/// Int8(truncatingIfNeeded: "0101" as BitArray) // 5
///
/// Int8(truncatingIfNeeded: "00000001" as BitArray) // 1
/// Int8(truncatingIfNeeded: "00000101" as BitArray) // 5
/// Int8(truncatingIfNeeded: "01111111" as BitArray) // 127
/// Int8(truncatingIfNeeded: "10000000" as BitArray) // -128
/// Int8(truncatingIfNeeded: "11111111" as BitArray) // -1
///
/// Int8(truncatingIfNeeded: "000011111111" as BitArray) // -1
/// Int8(truncatingIfNeeded: "111100000000" as BitArray) // 0
/// Int8(truncatingIfNeeded: "111100000001" as BitArray) // 1
@inlinable
public init(truncatingIfNeeded source: BitArray) {
self = Self._convert(source).value
}
/// Creates a new instance from the bits in the given bit array, if the
/// corresponding integer value can be represented exactly.
/// If the value is not representable exactly, then the result is `nil`.
///
/// If `Self` is an unsigned integer type, then the contents of the bit array
/// are interpreted to be the binary representation of a nonnegative
/// integer value. The bit array is allowed to contain bits in unrepresentable
/// positions, as long as they are all cleared.
///
/// UInt8(exactly: "" as BitArray) // 0
/// UInt8(exactly: "0" as BitArray) // 0
/// UInt8(exactly: "1" as BitArray) // 1
/// UInt8(exactly: "10" as BitArray) // 2
/// UInt8(exactly: "00000000" as BitArray) // 0
/// UInt8(exactly: "11111111" as BitArray) // 255
/// UInt8(exactly: "0000000000000" as BitArray) // 0
/// UInt8(exactly: "0000011111111" as BitArray) // 255
/// UInt8(exactly: "0000100000000" as BitArray) // nil
/// UInt8(exactly: "1111111111111" as BitArray) // nil
///
/// If `Self` is a signed integer type, then the contents of the bit array
/// are interpreted to be a two's complement representation of a signed
/// integer value, with the last bit in the array representing the sign of
/// the result.
///
/// Int8(exactly: "" as BitArray) // 0
/// Int8(exactly: "0" as BitArray) // 0
/// Int8(exactly: "1" as BitArray) // -1
/// Int8(exactly: "01" as BitArray) // 1
/// Int8(exactly: "101" as BitArray) // -3
/// Int8(exactly: "0101" as BitArray) // 5
///
/// Int8(exactly: "00000001" as BitArray) // 1
/// Int8(exactly: "00000101" as BitArray) // 5
/// Int8(exactly: "01111111" as BitArray) // 127
/// Int8(exactly: "10000000" as BitArray) // -128
/// Int8(exactly: "11111111" as BitArray) // -1
///
/// Int8(exactly: "00000000000" as BitArray) // 0
/// Int8(exactly: "00001111111" as BitArray) // 127
/// Int8(exactly: "00010000000" as BitArray) // nil
/// Int8(exactly: "11101111111" as BitArray) // nil
/// Int8(exactly: "11110000000" as BitArray) // -128
/// Int8(exactly: "11111111111" as BitArray) // -1
@inlinable
public init?(exactly source: BitArray) {
let (value, isNegative) = Self._convert(source)
guard isNegative == (value < 0) else { return nil }
let words = value.words
var equal = true
_ = source._foreachTwosComplementWordDownward(isSigned: Self.isSigned) { i, word in
assert(equal)
let w = (
i < words.count ? words[i]
: isNegative ? UInt.max
: UInt.zero)
equal = (w == word)
return equal
}
guard equal else { return nil }
self = value
}
/// Creates a new instance from the bits in the given bit array, if the
/// corresponding integer value can be represented exactly.
/// If the value is not representable exactly, then a runtime error will
/// occur.
///
/// If `Self` is an unsigned integer type, then the contents of the bit array
/// are interpreted to be the binary representation of a nonnegative
/// integer value. The bit array is allowed to contain bits in unrepresentable
/// positions, as long as they are all cleared.
///
/// UInt8("" as BitArray) // 0
/// UInt8("0" as BitArray) // 0
/// UInt8("1" as BitArray) // 1
/// UInt8("10" as BitArray) // 2
/// UInt8("00000000" as BitArray) // 0
/// UInt8("11111111" as BitArray) // 255
/// UInt8("0000000000000" as BitArray) // 0
/// UInt8("0000011111111" as BitArray) // 255
/// UInt8("0000100000000" as BitArray) // ERROR
/// UInt8("1111111111111" as BitArray) // ERROR
///
/// If `Self` is a signed integer type, then the contents of the bit array
/// are interpreted to be a two's complement representation of a signed
/// integer value, with the last bit in the array representing the sign of
/// the result.
///
/// Int8("" as BitArray) // 0
/// Int8("0" as BitArray) // 0
/// Int8("1" as BitArray) // -1
/// Int8("01" as BitArray) // 1
/// Int8("101" as BitArray) // -3
/// Int8("0101" as BitArray) // 5
///
/// Int8("00000001" as BitArray) // 1
/// Int8("00000101" as BitArray) // 5
/// Int8("01111111" as BitArray) // 127
/// Int8("10000000" as BitArray) // -128
/// Int8("11111111" as BitArray) // -1
///
/// Int8("00000000000" as BitArray) // 0
/// Int8("00001111111" as BitArray) // 127
/// Int8("00010000000" as BitArray) // ERROR
/// Int8("11101111111" as BitArray) // ERROR
/// Int8("11110000000" as BitArray) // -128
/// Int8("11111111111" as BitArray) // -1
@inlinable
public init(_ source: BitArray) {
guard let value = Self(exactly: source) else {
fatalError("""
BitArray value cannot be converted to \(Self.self) because it is \
outside the representable range
""")
}
self = value
}
}
extension BitArray {
@usableFromInline
internal func _foreachTwosComplementWordDownward(
isSigned: Bool,
body: (Int, UInt) -> Bool
) -> Bool {
self._read {
guard $0._words.count > 0 else { return false }
var isNegative = false
let end = $0.end.endSplit
assert(end.bit > 0)
let last = $0._words[end.word]
if isSigned, last.contains(end.bit - 1) {
// Sign extend last word
isNegative = true
if !body(end.word, last.union(_Word(upTo: end.bit).complement()).value) {
return isNegative
}
} else if !body(end.word, last.value) {
return isNegative
}
for i in stride(from: end.word - 1, through: 0, by: -1) {
if !body(i, $0._words[i].value) { return isNegative }
}
return isNegative
}
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -0,0 +1,52 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 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: LosslessStringConvertible {
/// Initializes a new bit array from a string representation.
///
/// The string given is interpreted as if it was the binary representation
/// of an integer value, consisting of the digits `0` and `1`, with the
/// highest digits appearing first.
///
/// BitArray("") // []
/// BitArray("001") // [true, false, false]
/// BitArray("1110") // [false, true, true, true]
/// BitArray("42") // nil
/// BitArray("Foo") // nil
///
public init?(_ description: String) {
let bits: BitArray? = description.utf8.withContiguousStorageIfAvailable { buffer in
Self(_utf8: buffer)
} ?? Self(_utf8: description.utf8)
guard let bits = bits else {
return nil
}
self = bits
}
internal init?<C: Collection>(_utf8 utf8: C) where C.Element == UInt8 {
let c = utf8.count
self.init(repeating: false, count: c)
var i = c &- 1
let success = _update { handle in
for byte in utf8 {
if byte == ._ascii1 {
handle.set(at: i)
} else {
guard byte == ._ascii0 else { return false }
}
i &-= 1
}
return true
}
guard success else { return nil }
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Copyright (c) 2022-2023 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
@@ -10,12 +10,13 @@
//===----------------------------------------------------------------------===//
extension BitArray {
/// Create and return a new bit array consisting of `count` random bits.
/// Create and return a new bit array consisting of `count` random bits,
/// using the system random number generator.
///
/// - Parameter count: The number of random bits to generate.
public static func random(count: Int) -> BitArray {
public static func randomBits(count: Int) -> BitArray {
var rng = SystemRandomNumberGenerator()
return random(count: count, using: &rng)
return randomBits(count: count, using: &rng)
}
/// Create and return a new bit array consisting of `count` random bits,
@@ -23,11 +24,11 @@ extension BitArray {
///
/// - Parameter count: The number of random bits to generate.
/// - Parameter rng: The random number generator to use.
public static func random<R: RandomNumberGenerator>(
public static func randomBits<R: RandomNumberGenerator>(
count: Int,
using rng: inout R
) -> BitArray {
precondition(count >= 0, "Invalid capacity value")
precondition(count >= 0, "Invalid count")
guard count > 0 else { return BitArray() }
let (w, b) = _BitPosition(count).endSplit
var words = (0 ... w).map { _ in _Word(rng.next() as UInt) }
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -29,7 +29,7 @@ extension BitArray {
public init() {
self.init(_storage: [], count: 0)
}
/// Creates a new bit array containing the specified number of a single,
/// repeated Boolean value.
///
@@ -0,0 +1,162 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022-2023 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 {
/// Shift the bits in this array by the specified number of places to the
/// left (towards the end of the array), by inserting `amount` false values
/// at the beginning.
///
/// If `amount` is negative, this is equivalent to shifting `-amount`
/// places to the right.
///
/// var bits: BitArray = "1110110"
/// bits.maskingShiftLeft(by: 2)
/// // bits is now 111011000
/// bits.maskingShiftLeft(by: -4)
/// // bits is now 11101
/// bits.maskingShiftLeft(by: 8)
/// // bits is now 111010000000
public mutating func resizingShiftLeft(by amount: Int) {
guard amount != 0 else { return }
if amount > 0 {
_resizingShiftLeft(by: amount)
} else {
_resizingShiftRight(by: -amount)
}
}
/// Shift the bits in this array by the specified number of places to the
/// right (towards the start of the array), by removing `amount` existing
/// values from the front of the array.
///
/// If `amount` is negative, then this is equivalent to shifting `-amount`
/// places to the left. If amount is greater than or equal to `count`,
/// then the resulting bit array will be empty.
///
/// var bits: BitArray = "1110110"
/// bits.maskingShiftRight(by: 2)
/// // bits is now 11101
/// bits.maskingShiftRight(by: -4)
/// // bits is now 111010000
/// bits.maskingShiftRight(by: 10)
/// // bits is now empty
///
/// If `amount` is between 0 and `count`, then this has the same effect as
/// `removeFirst(amount)`.
public mutating func resizingShiftRight(by amount: Int) {
guard amount != 0 else { return }
if amount > 0 {
_resizingShiftRight(by: amount)
} else {
_resizingShiftLeft(by: -amount)
}
}
internal mutating func _resizingShiftLeft(by amount: Int) {
assert(amount > 0)
_extend(by: amount, with: false)
maskingShiftLeft(by: amount)
}
internal mutating func _resizingShiftRight(by amount: Int) {
assert(amount > 0)
guard amount < count else {
self = .init()
return
}
self._copy(from: Range(uncheckedBounds: (amount, count)), to: 0)
self._removeLast(count &- amount)
}
}
extension BitArray {
// FIXME: Add maskingShiftRight(by:in:) and maskingShiftLeft(by:in:) for shifting slices.
/// Shift the bits in this array by the specified number of places to the
/// left (towards the end of the array), without changing
/// its count.
///
/// Values that are shifted off the array are discarded. Values that are
/// shifted in are all set to false.
///
/// If `amount` is negative, this is equivalent to shifting `-amount`
/// places to the right. If `amount` is greater than or equal to `count`,
/// then all values are set to false.
///
/// var bits: BitArray = "1110110"
/// bits.maskingShiftLeft(by: 2)
/// // bits is now 1011000
/// bits.maskingShiftLeft(by: -4)
/// // bits is now 0000101
/// bits.maskingShiftLeft(by: 8)
/// // bits is now 0000000
public mutating func maskingShiftLeft(by amount: Int) {
guard amount != 0 else { return }
_update {
if amount > 0 {
$0._maskingShiftLeft(by: amount)
} else {
$0._maskingShiftRight(by: -amount)
}
}
}
/// Shift the bits in this array by the specified number of places to the
/// right (towards the beginning of the array), without changing
/// its count.
///
/// Values that are shifted off the array are discarded. Values that are
/// shifted in are all set to false.
///
/// If `amount` is negative, this is equivalent to shifting `-amount`
/// places to the left. If `amount` is greater than or equal to `count`,
/// then all values are set to false.
///
/// var bits: BitArray = "1110110"
/// bits.maskingShiftRight(by: 2)
/// // bits is now 0011101
/// bits.maskingShiftRight(by: -3)
/// // bits is now 1101000
/// bits.maskingShiftRight(by: 8)
/// // bits is now 0000000
public mutating func maskingShiftRight(by amount: Int) {
guard amount != 0 else { return }
_update {
if amount > 0 {
$0._maskingShiftRight(by: amount)
} else {
$0._maskingShiftLeft(by: -amount)
}
}
}
}
extension BitArray._UnsafeHandle {
internal mutating func _maskingShiftLeft(by amount: Int) {
assert(amount > 0)
let d = Swift.min(amount, self.count)
if d == amount {
let range = Range(uncheckedBounds: (0, self.count &- d))
self.copy(from: range, to: d)
}
self.clear(in: Range(uncheckedBounds: (0, d)))
}
internal mutating func _maskingShiftRight(by amount: Int) {
assert(amount > 0)
let d = Swift.min(amount, self.count)
if d == amount {
let range = Range(uncheckedBounds: (d, self.count))
self.copy(from: range, to: 0)
}
self.clear(in: Range(uncheckedBounds: (self.count &- d, self.count)))
}
}
@@ -2,7 +2,7 @@
//
// 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-2023 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
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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
@@ -83,6 +83,24 @@ extension BitArray._UnsafeHandle {
Int(_count)
}
internal var end: _BitPosition {
_BitPosition(_count)
}
internal func set(at position: Int) {
ensureMutable()
assert(position >= 0 && position < _count)
let (word, bit) = _BitPosition(UInt(position)).split
_mutableWords[word].insert(bit)
}
internal func clear(at position: Int) {
ensureMutable()
assert(position >= 0 && position < _count)
let (word, bit) = _BitPosition(UInt(position)).split
_mutableWords[word].remove(bit)
}
internal subscript(position: Int) -> Bool {
get {
assert(position >= 0 && position < _count)
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Copyright (c) 2021-2023 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