From 6cb03fee98a3065f938c269fc2c5340a8e262f9f Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:30:39 -0800 Subject: [PATCH 01/11] [BitCollections] Update file headers --- .../BitArray/BitArray+BitwiseOperations.swift | 2 +- .../BitArray+ChunkedBitsIterators.swift | 2 +- .../BitArray/BitArray+Codable.swift | 2 +- .../BitArray/BitArray+Collection.swift | 2 +- .../BitCollections/BitArray/BitArray+Copy.swift | 2 +- .../BitArray+CustomDebugStringConvertible.swift | 17 ----------------- .../BitArray/BitArray+CustomReflectable.swift | 2 +- .../BitArray/BitArray+Equatable.swift | 2 +- .../BitArray+ExpressibleByArrayLiteral.swift | 2 +- .../BitArray/BitArray+Extras.swift | 2 +- .../BitCollections/BitArray/BitArray+Fill.swift | 2 +- .../BitArray/BitArray+Hashable.swift | 2 +- .../BitArray/BitArray+Initializers.swift | 2 +- .../BitArray/BitArray+Invariants.swift | 2 +- .../BitArray+RangeReplaceableCollection.swift | 4 ++-- .../BitArray/BitArray+Testing.swift | 2 +- .../BitArray/BitArray._UnsafeHandle.swift | 2 +- Sources/BitCollections/BitArray/BitArray.swift | 2 +- 18 files changed, 18 insertions(+), 35 deletions(-) delete mode 100644 Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift diff --git a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift index 770a9bbc..b697032b 100644 --- a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift +++ b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift index 2f50b921..21b44484 100644 --- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift +++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Codable.swift b/Sources/BitCollections/BitArray/BitArray+Codable.swift index f8a0a8b5..1d2c7857 100644 --- a/Sources/BitCollections/BitArray/BitArray+Codable.swift +++ b/Sources/BitCollections/BitArray/BitArray+Codable.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Collection.swift b/Sources/BitCollections/BitArray/BitArray+Collection.swift index 728909c3..0c7385a8 100644 --- a/Sources/BitCollections/BitArray/BitArray+Collection.swift +++ b/Sources/BitCollections/BitArray/BitArray+Collection.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index 1f339c33..0da47fa9 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift deleted file mode 100644 index f8502d2e..00000000 --- a/Sources/BitCollections/BitArray/BitArray+CustomDebugStringConvertible.swift +++ /dev/null @@ -1,17 +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: CustomDebugStringConvertible { - /// A textual representation of this instance, suitable for debugging. - public var debugDescription: String { - "BitArray(\(_bitString))" - } -} diff --git a/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift b/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift index a61d3b77..89cbe6e5 100644 --- a/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift +++ b/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Equatable.swift b/Sources/BitCollections/BitArray/BitArray+Equatable.swift index d7926a9e..5741ce6b 100644 --- a/Sources/BitCollections/BitArray/BitArray+Equatable.swift +++ b/Sources/BitCollections/BitArray/BitArray+Equatable.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift b/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift index e10c0e3b..0271097b 100644 --- a/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift +++ b/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Extras.swift b/Sources/BitCollections/BitArray/BitArray+Extras.swift index a6554509..d0ecd69a 100644 --- a/Sources/BitCollections/BitArray/BitArray+Extras.swift +++ b/Sources/BitCollections/BitArray/BitArray+Extras.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Fill.swift b/Sources/BitCollections/BitArray/BitArray+Fill.swift index bf42c338..fd96dd56 100644 --- a/Sources/BitCollections/BitArray/BitArray+Fill.swift +++ b/Sources/BitCollections/BitArray/BitArray+Fill.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Hashable.swift b/Sources/BitCollections/BitArray/BitArray+Hashable.swift index d8ff3da8..2e5726ed 100644 --- a/Sources/BitCollections/BitArray/BitArray+Hashable.swift +++ b/Sources/BitCollections/BitArray/BitArray+Hashable.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index 155740c7..e9be95a4 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+Invariants.swift b/Sources/BitCollections/BitArray/BitArray+Invariants.swift index d194ea0b..d7f791e6 100644 --- a/Sources/BitCollections/BitArray/BitArray+Invariants.swift +++ b/Sources/BitCollections/BitArray/BitArray+Invariants.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift index 5ab87d7d..755210cf 100644 --- a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift +++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift @@ -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. /// diff --git a/Sources/BitCollections/BitArray/BitArray+Testing.swift b/Sources/BitCollections/BitArray/BitArray+Testing.swift index 3269ce30..54afb107 100644 --- a/Sources/BitCollections/BitArray/BitArray+Testing.swift +++ b/Sources/BitCollections/BitArray/BitArray+Testing.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift index ba69f1e7..7c4157f7 100644 --- a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift +++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift @@ -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 diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift index e40cc0e2..832e5fa0 100644 --- a/Sources/BitCollections/BitArray/BitArray.swift +++ b/Sources/BitCollections/BitArray/BitArray.swift @@ -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 From 03b62ffb6e80d4514a86645c2858c5d7bc21cfb9 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:33:05 -0800 Subject: [PATCH 02/11] =?UTF-8?q?[BitArray]=20random(count:using:)=20?= =?UTF-8?q?=E2=86=92=20randomBits(count:using:)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...Array+Random.swift => BitArray+RandomBits.swift} | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) rename Sources/BitCollections/BitArray/{BitArray+Random.swift => BitArray+RandomBits.swift} (77%) diff --git a/Sources/BitCollections/BitArray/BitArray+Random.swift b/Sources/BitCollections/BitArray/BitArray+RandomBits.swift similarity index 77% rename from Sources/BitCollections/BitArray/BitArray+Random.swift rename to Sources/BitCollections/BitArray/BitArray+RandomBits.swift index 5c58cf78..9a13e78c 100644 --- a/Sources/BitCollections/BitArray/BitArray+Random.swift +++ b/Sources/BitCollections/BitArray/BitArray+RandomBits.swift @@ -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( + public static func randomBits( 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) } From 4281dc4482114d17727f1c1cd7a6f3a8690bdf0e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:39:46 -0800 Subject: [PATCH 03/11] [BitArray] Change description to print bit arrays as binary numerals This matches std::bitset, and it seems to be the more logical option. --- .../BitArray+CustomStringConvertible.swift | 41 ------------ .../BitArray/BitArray+Descriptions.swift | 63 +++++++++++++++++++ 2 files changed, 63 insertions(+), 41 deletions(-) delete mode 100644 Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift create mode 100644 Sources/BitCollections/BitArray/BitArray+Descriptions.swift diff --git a/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift deleted file mode 100644 index 91357755..00000000 --- a/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift +++ /dev/null @@ -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 - } -} diff --git a/Sources/BitCollections/BitArray/BitArray+Descriptions.swift b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift new file mode 100644 index 00000000..be4f0421 --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift @@ -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 + } +} From c15e484f5aa2a404daa36bcb71b487433cc02885 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:43:06 -0800 Subject: [PATCH 04/11] [BitArray] Add init(minimumCapacity:) --- .../BitCollections/BitArray/BitArray+Initializers.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index e9be95a4..bc19006e 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -26,4 +26,12 @@ extension BitArray { let count = value.bitWidth 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) + } +} } From c15b0d9889ef065ba1f6c9b33ae5cc057fd03ff6 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:59:24 -0800 Subject: [PATCH 05/11] =?UTF-8?q?[BitArray]=20Add=20BitArray=20=E2=86=92?= =?UTF-8?q?=20BinaryInteger=20conversion=20initializers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit extension BinaryInteger { public init(truncatingIfNeeded source: BitArray) public init?(exactly source: BitArray) public init(_ source: BitArray) } --- .../BitArray/BitArray+Initializers.swift | 236 +++++++++++++++++- .../BitArray/BitArray._UnsafeHandle.swift | 18 ++ 2 files changed, 253 insertions(+), 1 deletion(-) diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index bc19006e..5269a736 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -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,29 @@ 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(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) } @@ -34,4 +62,210 @@ extension BitArray { 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 + } + } } diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift index 7c4157f7..26ceb79d 100644 --- a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift +++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift @@ -81,6 +81,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) From a8bde6343976f70ce5043516f474fcd17bb52dac Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 17:59:56 -0800 Subject: [PATCH 06/11] [BitArray] Add toggleAll(), toggleAll(in:) --- .../BitArray/BitArray+BitwiseOperations.swift | 54 +++++++++++++++---- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift index b697032b..24cdec23 100644 --- a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift +++ b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift @@ -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) { + 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( + in range: R + ) where R.Bound == Int { + toggleAll(in: range.relative(to: self)) + } } From a90b73966ae43f4c92ae2d5ec0deeb12c46c9499 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:00:27 -0800 Subject: [PATCH 07/11] [BitArray] Add conformance to ExpressibleByStringLiteral --- .../BitArray+ExpressibleByStringLiteral.swift | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift diff --git a/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift b/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift new file mode 100644 index 00000000..a886a557 --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift @@ -0,0 +1,21 @@ +//===----------------------------------------------------------------------===// +// +// 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: 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 + } +} From 17343b752a208b8545dbec998cd71a465a54bde4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:01:46 -0800 Subject: [PATCH 08/11] [BitArray] fill(in:with:), insert(repeating:count:at:), append(repeating:count:) --- .../BitArray/BitArray+Extras.swift | 21 +++++++++++++++++++ .../BitArray/BitArray+Fill.swift | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/Sources/BitCollections/BitArray/BitArray+Extras.swift b/Sources/BitCollections/BitArray/BitArray+Extras.swift index d0ecd69a..6bf4c0b1 100644 --- a/Sources/BitCollections/BitArray/BitArray+Extras.swift +++ b/Sources/BitCollections/BitArray/BitArray+Extras.swift @@ -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) + } +} diff --git a/Sources/BitCollections/BitArray/BitArray+Fill.swift b/Sources/BitCollections/BitArray/BitArray+Fill.swift index fd96dd56..6c8223f6 100644 --- a/Sources/BitCollections/BitArray/BitArray+Fill.swift +++ b/Sources/BitCollections/BitArray/BitArray+Fill.swift @@ -31,4 +31,11 @@ extension BitArray { } } } + + public mutating func fill( + in range: R, + with value: Bool = true + ) where R.Bound == Int { + fill(in: range.relative(to: self), with: value) + } } From 866d00798f6c802bc7c70244d8f7766c933ed566 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:02:16 -0800 Subject: [PATCH 09/11] [BitArray] Add LosslessStringConvertible conformance --- .../BitArray+LosslessStringConvertible.swift | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift diff --git a/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift new file mode 100644 index 00000000..2166b166 --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift @@ -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?(_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 } + } +} From a360969ec6ec8dd0ce8d65dbcdca3be6bb444a34 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:04:30 -0800 Subject: [PATCH 10/11] [BitArray] Add masking and resizing shifts --- .../BitArray/BitArray+Shifts.swift | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 Sources/BitCollections/BitArray/BitArray+Shifts.swift diff --git a/Sources/BitCollections/BitArray/BitArray+Shifts.swift b/Sources/BitCollections/BitArray/BitArray+Shifts.swift new file mode 100644 index 00000000..7eb6601d --- /dev/null +++ b/Sources/BitCollections/BitArray/BitArray+Shifts.swift @@ -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))) + } +} From 3e6df33472d54ed83dffe3bca7a3c8f65bab4c43 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 31 Jan 2023 18:04:41 -0800 Subject: [PATCH 11/11] [BitArray] Update tests --- Tests/BitCollectionsTests/BitArrayTests.swift | 211 +++++++++++++++++- 1 file changed, 200 insertions(+), 11 deletions(-) diff --git a/Tests/BitCollectionsTests/BitArrayTests.swift b/Tests/BitCollectionsTests/BitArrayTests.swift index 303ec8b4..bbda7973 100644 --- a/Tests/BitCollectionsTests/BitArrayTests.swift +++ b/Tests/BitCollectionsTests/BitArrayTests.swift @@ -144,7 +144,115 @@ final class BitArrayTests: CollectionTestCase { expectEqualElements(actual, expected) } } - + + func test_conversion_to_BinaryInteger_truncating() { + let cases: [(bits: BitArray, signed: Int8, unsigned: UInt8)] = [ + ("", 0, 0), + ("0", 0, 0), + ("1", -1, 1), + ("00", 0, 0), + ("01", 1, 1), + ("10", -2, 2), + ("11", -1, 3), + ("001", 1, 1), + ("010", 2, 2), + ("011", 3, 3), + ("100", -4, 4), + ("101", -3, 5), + ("110", -2, 6), + ("111", -1, 7), + // 8 bits + ("00000000", 0, 0), + ("10000000", -128, 128), + ("10000001", -127, 129), + ("11111111", -1, 255), + // 9 bits + ("000000000", 0, 0), + ("000000100", 4, 4), + ("010000000", -128, 128), + ("010000001", -127, 129), + ("011111111", -1, 255), + ("100000000", 0, 0), + ("100000001", 1, 1), + ("101111111", 127, 127), + ("110000000", -128, 128), + ("110000001", -127, 129), + ("111111110", -2, 254), + ("111111111", -1, 255), + // 32 bits + ("00000000000000000000000000000000", 0, 0), + ("00000000000000000000000001111111", 127, 127), + ("00000000000000000000000010000000", -128, 128), + ("00000000000000000000000011111111", -1, 255), + ("00000000000000000000000100000000", 0, 0), + ("11111111111111111111111110000000", -128, 128), + ("11111111111111111111111111111110", -2, 254), + ("11111111111111111111111111111111", -1, 255), + ] + + withEvery("pair", in: cases) { (bits, signed, unsigned) in + let actual1 = Int8(truncatingIfNeeded: bits) + expectEqual(actual1, signed) + + let actual2 = UInt8(truncatingIfNeeded: bits) + expectEqual(actual2, unsigned) + } + } + + func test_conversion_to_BinaryInteger_exact() { + let cases: [(bits: BitArray, signed: Int8?, unsigned: UInt8?)] = [ + ("", 0, 0), + ("0", 0, 0), + ("1", -1, 1), + ("00", 0, 0), + ("01", 1, 1), + ("10", -2, 2), + ("11", -1, 3), + ("001", 1, 1), + ("010", 2, 2), + ("011", 3, 3), + ("100", -4, 4), + ("101", -3, 5), + ("110", -2, 6), + ("111", -1, 7), + // 8 bits + ("00000000", 0, 0), + ("10000000", -128, 128), + ("10000001", -127, 129), + ("11111111", -1, 255), + // 9 bits + ("000000000", 0, 0), + ("000000100", 4, 4), + ("010000000", nil, 128), + ("010000001", nil, 129), + ("011111111", nil, 255), + ("100000000", nil, nil), + ("100000001", nil, nil), + ("101111111", nil, nil), + ("110000000", -128, nil), + ("110000001", -127, nil), + ("111111110", -2, nil), + ("111111111", -1, nil), + // 32 bits + ("00000000000000000000000000000000", 0, 0), + ("00000000000000000000000001111111", 127, 127), + ("00000000000000000000000010000000", nil, 128), + ("00000000000000000000000011111111", nil, 255), + ("00000000000000000000000100000000", nil, nil), + ("11111111111111111111111110000000", -128, nil), + ("11111111111111111111111111111110", -2, nil), + ("11111111111111111111111111111111", -1, nil), + ] + + withEvery("pair", in: cases) { (bits, signed, unsigned) in + let actual1 = Int8(exactly: bits) + expectEqual(actual1, signed) + + let actual2 = UInt8(exactly: bits) + expectEqual(actual2, unsigned) + } + } + func test_init_BitSet() { expectEqualElements(BitArray(BitSet([])), []) expectEqualElements(BitArray(BitSet([0])), [true]) @@ -212,7 +320,76 @@ final class BitArrayTests: CollectionTestCase { true, true, false, false, true, true, true, ]) } - + + func test_ExpressibleByStringLiteral() { + let a: BitArray = "" + expectEqualElements(a, []) + + let b: BitArray = "1" + expectEqualElements(b, [true]) + + let c: BitArray = "001" + expectEqualElements(c, [true, false, false]) + + let d: BitArray = "10001" + expectEqualElements(d, [true, false, false, false, true]) + + let e: BitArray = """ + 111001110100010110100000000100110010010101001000000100110010001 + """ + expectEqualElements(e, [ + true, false, false, false, true, false, false, + true, true, false, false, true, false, false, + false, false, false, false, true, false, false, + true, false, true, false, true, false, false, + true, false, false, true, true, false, false, + true, false, false, false, false, false, false, + false, false, true, false, true, true, false, + true, false, false, false, true, false, true, + true, true, false, false, true, true, true, + ]) + } + + func test_literals() { + let cases: [(a: BitArray, b: BitArray)] = [ + ("", []), + ("0", [false]), + ("1", [true]), + ("1010", [false, true, false, true]), + ("0101", [true, false, true, false]), + ("111000", [false, false, false, true, true, true]), + ("000111", [true, true, true, false, false, false]), + ] + withEvery("i", in: cases.indices) { i in + let (a, b) = cases[i] + expectEqual(a, b) + } + } + + func test_LosslessStringConvertible() { + let cases: [(a: String, b: BitArray?)] = [ + ("", []), + ("0", [false]), + ("1", [true]), + ("1010", [false, true, false, true]), + ("0101", [true, false, true, false]), + ("111000", [false, false, false, true, true, true]), + ("000111", [true, true, true, false, false, false]), + ("_", nil), + ("00010101X", nil), + ("①⓪⓪①", nil), + ("2341", nil), + ("00 10 01", nil), + (" 01", nil), + ("01 ", nil), + ] + withEvery("i", in: cases.indices) { i in + let (a, b) = cases[i] + let bits = BitArray(a) + expectEqual(bits, b) + } + } + func test_Hashable() { // This is a silly test, but it does exercise hashing a bit. let classes: [[BitArray]] = [ @@ -628,7 +805,19 @@ final class BitArrayTests: CollectionTestCase { bits.reserveCapacity(2000) expectGreaterThanOrEqual(bits._capacity, 2000) } - + + func test_init_minimumCapacity() { + let b1 = BitArray(minimumCapacity: 0) + expectEqual(b1._capacity, 0) + + let cases = [0, 1, 100, 1000, 2000] + withEvery("capacity", in: cases) { capacity in + let bits = BitArray(minimumCapacity: capacity) + expectTrue(bits.isEmpty) + expectGreaterThanOrEqual(bits._capacity, capacity) + } + } + func test_bitwiseOr() { withSome("count", in: 0 ..< 512, maxSamples: 100) { count in withEvery("i", in: 0 ..< 10) { i in @@ -719,35 +908,35 @@ final class BitArrayTests: CollectionTestCase { func test_random() { var rng = AllOnesRandomNumberGenerator() for c in [0, 10, 64, 65, 77, 1200] { - let array = BitArray.random(count: c, using: &rng) + let array = BitArray.randomBits(count: c, using: &rng) expectEqual(array.count, c) expectEqualElements(array, repeatElement(true, count: c)) } - let a = Set((0..<10).map { _ in BitArray.random(count: 1000) }) + let a = Set((0..<10).map { _ in BitArray.randomBits(count: 1000) }) expectEqual(a.count, 10) } func test_description() { let a: BitArray = [] - expectEqual("\(a)", "0") + expectEqual("\(a)", "") let b: BitArray = [true, false, true, true, true] - expectEqual("\(b)", "10111") + expectEqual("\(b)", "11101") let c: BitArray = [false, false, false, false, true, true, true, false] - expectEqual("\(c)", "00001110") + expectEqual("\(c)", "01110000") } func test_debugDescription() { let a: BitArray = [] - expectEqual("\(String(reflecting: a))", "BitArray(0)") + expectEqual("\(String(reflecting: a))", "BitArray()") let b: BitArray = [true, false, true, true, true] - expectEqual("\(String(reflecting: b))", "BitArray(10111)") + expectEqual("\(String(reflecting: b))", "BitArray(11101)") let c: BitArray = [false, false, false, false, true, true, true, false] - expectEqual("\(String(reflecting: c))", "BitArray(00001110)") + expectEqual("\(String(reflecting: c))", "BitArray(01110000)") } func test_mirror() {