[BitArray] Add docs.

This commit is contained in:
Karoy Lorentey committed 2022-08-25 23:50:35 -07:00
1 parent fcac09d86a
commit 5bc22eaf9b
9 files changed
+348 -12

No files matched your search

@@ -10,6 +10,12 @@
//===----------------------------------------------------------------------===//
extension BitArray {
/// Stores the result of performing a bitwise OR operation on two
/// equal-sized bit arrays in the left-hand-side variable.
///
/// - Parameter left: A bit array.
/// - Parameter right: Another bit array of the same size.
/// - Complexity: O(left.count)
public static func |=(left: inout Self, right: Self) {
precondition(left.count == right.count)
left._update { target in
@@ -22,6 +28,13 @@ extension BitArray {
left._checkInvariants()
}
/// Returns the result of performing a bitwise OR operation on two
/// equal-sized bit arrays.
///
/// - Parameter left: A bit array.
/// - Parameter right: Another bit array of the same size.
/// - Returns: The bitwise OR of `left` and `right`.
/// - Complexity: O(left.count)
public static func |(left: Self, right: Self) -> Self {
precondition(left.count == right.count)
var result = left
@@ -29,6 +42,12 @@ extension BitArray {
return result
}
/// Stores the result of performing a bitwise AND operation on two given
/// equal-sized bit arrays in the left-hand-side variable.
///
/// - Parameter left: A bit array.
/// - Parameter right: Another bit array of the same size.
/// - Complexity: O(left.count)
public static func &=(left: inout Self, right: Self) {
precondition(left.count == right.count)
left._update { target in
@@ -41,6 +60,13 @@ extension BitArray {
left._checkInvariants()
}
/// Returns the result of performing a bitwise AND operation on two
/// equal-sized bit arrays.
///
/// - Parameter left: A bit array.
/// - Parameter right: Another bit array of the same size.
/// - Returns: The bitwise AND of `left` and `right`.
/// - Complexity: O(left.count)
public static func &(left: Self, right: Self) -> Self {
precondition(left.count == right.count)
var result = left
@@ -48,6 +74,12 @@ extension BitArray {
return result
}
/// Stores the result of performing a bitwise XOR operation on two given
/// equal-sized bit arrays in the left-hand-side variable.
///
/// - Parameter left: A bit array.
/// - Parameter right: Another bit array of the same size.
/// - Complexity: O(left.count)
public static func ^=(left: inout Self, right: Self) {
precondition(left.count == right.count)
left._update { target in
@@ -60,6 +92,13 @@ extension BitArray {
left._checkInvariants()
}
/// Returns the result of performing a bitwise XOR operation on two
/// equal-sized bit arrays.
///
/// - Parameter left: A bit array.
/// - Parameter right: Another bit array of the same size.
/// - Returns: The bitwise XOR of `left` and `right`.
/// - Complexity: O(left.count)
public static func ^(left: Self, right: Self) -> Self {
precondition(left.count == right.count)
var result = left
@@ -67,6 +106,12 @@ extension BitArray {
return result
}
/// Returns the complement of the given bit array.
///
/// - Parameter value: A bit array.
/// - Returns: A bit array constructed by flipping each bit in `value`.
/// flipped.
/// - Complexity: O(value.count)
public static prefix func ~(value: Self) -> Self {
var result = value
result._update { handle in
@@ -10,6 +10,14 @@
//===----------------------------------------------------------------------===//
extension BitArray: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameter lhs: A value to compare.
/// - Parameter rhs: Another value to compare.
/// - Complexity: O(left.count)
public static func ==(left: Self, right: Self) -> Bool {
guard left._count == right._count else { return false }
return left._storage == right._storage
@@ -10,6 +10,8 @@
//===----------------------------------------------------------------------===//
extension BitArray: ExpressibleByArrayLiteral {
/// Creates an instance initialized with the given elements.
@inlinable
public init(arrayLiteral elements: Bool...) {
self.init(elements)
}
@@ -10,6 +10,12 @@
//===----------------------------------------------------------------------===//
extension BitArray {
/// Set the count of this bit array to `count`, by either truncating it or
/// extending it by appending the specified Boolean value (`false` by default).
///
/// - Parameter count: The desired count of the bit array on return.
/// - Parameter padding: The value to append the array if the array is
/// currently too short.
public mutating func truncateOrExtend(
toCount count: Int,
with padding: Bool = false
@@ -10,10 +10,18 @@
//===----------------------------------------------------------------------===//
extension BitArray {
/// Set every bit of this array to `value` (`true` by default).
///
/// - Parameter value: The Boolean value to which to set the array's elements.
public mutating func fill(with value: Bool = true) {
fill(in: Range(uncheckedBounds: (0, count)), with: value)
}
/// Set every bit of this array within the specified range to `value`
/// (`true` by default).
///
/// - Parameter range: The range whose elements to overwrite.
/// - Parameter value: The Boolean value to which to set the array's elements.
public mutating func fill(in range: Range<Int>, with value: Bool = true) {
_update { handle in
if value {
@@ -10,6 +10,11 @@
//===----------------------------------------------------------------------===//
extension BitArray: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher) {
hasher.combine(_count)
for word in _storage {
@@ -10,11 +10,17 @@
//===----------------------------------------------------------------------===//
extension BitArray {
/// Initialize a bit array from a bit set.
///
/// - Complexity: O(1)
public init(_ set: BitSet) {
guard let l = set.last else { self.init(); return }
self.init(_storage: set._storage, count: l + 1)
}
/// Initialize a bit array from the binary representation of an integer.
///
/// - Complexity: O(value.bitWidth)
public init<I: BinaryInteger>(bitPattern value: I) {
let words = value.words.map { _Word($0) }
let count = value.bitWidth
@@ -10,11 +10,19 @@
//===----------------------------------------------------------------------===//
extension BitArray {
/// Create and return a new bit array consisting of `count` random bits.
///
/// - Parameter count: The number of random bits to generate.
public static func random(count: Int) -> BitArray {
var rng = SystemRandomNumberGenerator()
return random(count: count, using: &rng)
}
/// Create and return a new bit array consisting of `count` random bits,
/// using the given random number generator.
///
/// - Parameter count: The number of random bits to generate.
/// - Parameter rng: The random number generator to use.
public static func random<R: RandomNumberGenerator>(
count: Int,
using rng: inout R
@@ -12,15 +12,31 @@
extension BitArray: RangeReplaceableCollection {}
extension BitArray {
/// Prepares the bit array to store the specified number of bits.
///
/// If you are adding a known number of elements to an array, use this
/// method to avoid multiple reallocations.
///
/// - Parameter n: The requested number of bits to store.
public mutating func reserveCapacity(_ n: Int) {
let wordCount = _Word.wordCount(forBitCount: UInt(n))
_storage.reserveCapacity(wordCount)
}
/// Creates a new, empty bit array.
///
/// - Complexity: O(1)
public init() {
self.init(_storage: [], count: 0)
}
/// Creates a new bit array containing the specified number of a single,
/// repeated Boolean value.
///
/// - Parameters:
/// - repeatedValue: The Boolean value 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) {
let wordCount = _Word.wordCount(forBitCount: UInt(count))
var storage: [_Word] = .init(
@@ -34,6 +50,12 @@ extension BitArray {
}
extension BitArray {
/// Creates a new bit array containing the Boolean values in a sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
/// `elements` must be finite.
/// - Complexity: O(*count*) where *count* is the number of values in
/// `elements`.
@inlinable
public init<S: Sequence>(_ elements: S) where S.Element == Bool {
defer { _checkInvariants() }
@@ -51,15 +73,28 @@ extension BitArray {
}
// Specializations
public init(_ values: BitArray) {
self = values
/// Creates a new bit array containing the Boolean values in a sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
/// `elements` must be finite.
/// - Complexity: O(*count*) where *count* is the number of values in
/// `elements`.
public init(_ elements: BitArray) {
self = elements
}
public init(_ values: BitArray.SubSequence) {
let wordCount = _Word.wordCount(forBitCount: UInt(values.count))
/// Creates a new bit array containing the Boolean values in a sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
/// `elements` must be finite.
/// - Complexity: O(*count*) where *count* is the number of values in
/// `elements`.
public init(_ elements: BitArray.SubSequence) {
let wordCount = _Word.wordCount(forBitCount: UInt(elements.count))
let storage = Array(repeating: _Word.empty, count: wordCount)
self.init(_storage: storage, count: values.count)
self._copy(from: values, to: 0)
self.init(_storage: storage, count: elements.count)
self._copy(from: elements, to: 0)
_checkInvariants()
}
}
@@ -82,6 +117,32 @@ extension BitArray {
}
}
/// Replaces the specified subrange of bits with the values in the given
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If you pass a zero-length range as the `range` parameter, this method
/// inserts the elements of `newElements` at `range.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// - Parameters:
/// - range: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the collection, this method is
/// equivalent to `append(contentsOf:)`.
public mutating func replaceSubrange<C: Collection>(
_ range: Range<Int>,
with newElements: __owned C
@@ -98,6 +159,32 @@ extension BitArray {
_checkInvariants()
}
/// Replaces the specified subrange of bits with the values in the given
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If you pass a zero-length range as the `range` parameter, this method
/// inserts the elements of `newElements` at `range.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// - Parameters:
/// - range: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the collection, this method is
/// equivalent to `append(contentsOf:)`.
public mutating func replaceSubrange(
_ range: Range<Int>,
with newElements: __owned BitArray
@@ -105,6 +192,32 @@ extension BitArray {
replaceSubrange(range, with: newElements[...])
}
/// Replaces the specified subrange of bits with the values in the given
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If you pass a zero-length range as the `range` parameter, this method
/// inserts the elements of `newElements` at `range.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// - Parameters:
/// - range: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the collection, this method is
/// equivalent to `append(contentsOf:)`.
public mutating func replaceSubrange(
_ range: Range<Int>,
with newElements: __owned BitArray.SubSequence
@@ -116,6 +229,12 @@ extension BitArray {
}
extension BitArray {
/// Adds a new element to the end of the bit array.
///
/// - Parameter newElement: The element to append to the bit array.
///
/// - Complexity: Amortized O(1), averaged over many calls to `append(_:)`
/// on the same bit array.
public mutating func append(_ newElement: Bool) {
let (word, bit) = _BitPosition(_count).split
if bit == 0 {
@@ -130,6 +249,16 @@ extension BitArray {
_checkInvariants()
}
/// Adds the elements of a sequence or collection to the end of this
/// bit array.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// - Parameter newElements: The elements to append to the bit array.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`, if
/// `self` is the only copy of this bit array. Otherwise O(`count` + *m*).
public mutating func append<S: Sequence>(
contentsOf newElements: __owned S
) where S.Element == Bool {
@@ -163,12 +292,32 @@ extension BitArray {
_checkInvariants()
}
/// Adds the elements of a sequence or collection to the end of this
/// bit array.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// - Parameter newElements: The elements to append to the bit array.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`, if
/// `self` is the only copy of this bit array. Otherwise O(`count` + *m*).
public mutating func append(contentsOf newElements: BitArray) {
_extend(by: newElements.count)
_copy(from: newElements, to: count - newElements.count)
_checkInvariants()
}
/// Adds the elements of a sequence or collection to the end of this
/// bit array.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// - Parameter newElements: The elements to append to the bit array.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`, if
/// `self` is the only copy of this bit array. Otherwise O(`count` + *m*).
public mutating func append(contentsOf newElements: BitArray.SubSequence) {
_extend(by: newElements.count)
_copy(from: newElements, to: count - newElements.count)
@@ -177,6 +326,26 @@ extension BitArray {
}
extension BitArray {
/// Inserts a new element into the bit array at the specified position.
///
/// The new element is inserted before the element currently at the
/// specified index. If you pass the bit array's `endIndex` as
/// the `index` parameter, then the new element is appended to the
/// collection.
///
/// var bits = [false, true, true, false, true]
/// bits.insert(true, at: 3)
/// bits.insert(false, at: numbers.endIndex)
///
/// print(bits)
/// // Prints "[false, true, true, true, false, true, false]"
///
/// - Parameter newElement: The new element to insert into the bit array.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index into the bit array.
///
/// - Complexity: O(`count` - i), if `self` is the only copy of this bit
/// array. Otherwise O(`count`).
public mutating func insert(_ newElement: Bool, at i: Int) {
if _BitPosition(_count).bit == 0 {
_storage.append(_Word.empty)
@@ -190,6 +359,19 @@ extension BitArray {
_checkInvariants()
}
/// Inserts the elements of a collection into the bit array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// - Parameter newElements: The new elements to insert into the bit array.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(`self.count` + `newElements.count`).
/// If `i == endIndex`, this method is equivalent to `append(contentsOf:)`.
public mutating func insert<C: Collection>(
contentsOf newElements: __owned C,
at i: Int
@@ -211,6 +393,19 @@ extension BitArray {
_checkInvariants()
}
/// Inserts the elements of a collection into the bit array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// - Parameter newElements: The new elements to insert into the bit array.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(`self.count` + `newElements.count`).
/// If `i == endIndex`, this method is equivalent to `append(contentsOf:)`.
public mutating func insert(
contentsOf newElements: __owned BitArray,
at i: Int
@@ -218,6 +413,19 @@ extension BitArray {
insert(contentsOf: newElements[...], at: i)
}
/// Inserts the elements of a collection into the bit array at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// - Parameter newElements: The new elements to insert into the bit array.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(`self.count` + `newElements.count`).
/// If `i == endIndex`, this method is equivalent to `append(contentsOf:)`.
public mutating func insert(
contentsOf newElements: __owned BitArray.SubSequence,
at i: Int
@@ -232,6 +440,17 @@ extension BitArray {
}
extension BitArray {
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap.
///
/// - Parameter i: The position of the element to remove. `index` must be
/// a valid index of the collection that is not equal to the collection's
/// end index.
/// - Returns: The removed element.
///
/// - Complexity: O(`count`)
@discardableResult
public mutating func remove(at i: Int) -> Bool {
let result = self[i]
@@ -241,14 +460,20 @@ extension BitArray {
return result
}
public mutating func removeSubrange(_ bounds: Range<Int>) {
/// Removes the specified subrange of elements from the collection.
///
/// - Parameter range: The subrange of the collection to remove. The bounds
/// of the range must be valid indices of the collection.
///
/// - Complexity: O(`count`)
public mutating func removeSubrange(_ range: Range<Int>) {
precondition(
bounds.lowerBound >= 0 && bounds.upperBound <= count,
range.lowerBound >= 0 && range.upperBound <= count,
"Bounds out of range")
_copy(
from: Range(uncheckedBounds: (bounds.upperBound, count)),
to: bounds.lowerBound)
_removeLast(bounds.count)
from: Range(uncheckedBounds: (range.upperBound, count)),
to: range.lowerBound)
_removeLast(range.count)
_checkInvariants()
}
@@ -267,6 +492,13 @@ extension BitArray {
return true
}
/// Removes and returns the first element of the bit array.
///
/// The bit array must not be empty.
///
/// - Returns: The removed element.
///
/// - Complexity: O(`count`)
@discardableResult
public mutating func removeFirst() -> Bool {
precondition(_count > 0)
@@ -277,6 +509,14 @@ extension BitArray {
return result
}
/// Removes the specified number of elements from the beginning of the
/// bit array.
///
/// - Parameter k: The number of elements to remove from the bit array.
/// `k` must be greater than or equal to zero and must not exceed the
/// number of elements in the bit array.
///
/// - Complexity: O(`count`)
public mutating func removeFirst(_ k: Int) {
precondition(k >= 0 && k <= _count)
_copy(from: k ..< count, to: 0)
@@ -284,6 +524,14 @@ extension BitArray {
_checkInvariants()
}
/// Removes all elements from the bit array.
///
/// - Parameter keepCapacity: Pass `true` to request that the collection
/// avoid releasing its storage. Retaining the collection's storage can
/// be a useful optimization when you're planning to grow the collection
/// again. The default value is `false`.
///
/// - Complexity: O(`count`)
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
_storage.removeAll(keepingCapacity: keepCapacity)
_count = 0