[BitArray] Update LosslessStringConvertible initializer to accept new description format

This commit is contained in:
Karoy Lorentey committed 2024-01-31 19:34:36 -08:00
1 parent ae641c3d5d
commit a0da2df799
2 files changed
+34 -4

No files matched your search

@@ -22,17 +22,29 @@ extension BitArray: LosslessStringConvertible {
/// BitArray("42") // nil
/// BitArray("Foo") // nil
///
/// To accept the display format used by `description`, the digits in the
/// input string are also allowed to be surrounded by a single pair of ASCII
/// angle brackets:
///
/// let bits: BitArray = [false, false, true, true]
/// let string = bits.description // "<1100>"
/// let sameBits = BitArray(string)! // [false, false, true, true]
///
public init?(_ description: String) {
let bits: BitArray? = description.utf8.withContiguousStorageIfAvailable { buffer in
Self(_utf8: buffer)
} ?? Self(_utf8: description.utf8)
var digits = description[...]
if digits.utf8.first == ._asciiLT, digits.utf8.last == ._asciiGT {
digits = digits.dropFirst().dropLast()
}
let bits: BitArray? = digits.utf8.withContiguousStorageIfAvailable { buffer in
Self(_utf8Digits: buffer)
} ?? Self(_utf8Digits: description.utf8)
guard let bits = bits else {
return nil
}
self = bits
}
internal init?(_utf8 utf8: some Collection<UInt8>) {
internal init?(_utf8Digits utf8: some Collection<UInt8>) {
let c = utf8.count
self.init(repeating: false, count: c)
var i = c &- 1
@@ -373,13 +373,31 @@ final class BitArrayTests: CollectionTestCase {
func test_LosslessStringConvertible() {
let cases: [(a: String, b: BitArray?)] = [
("", []),
("<>", []),
("0", [false]),
("<0>", [false]),
("1", [true]),
("<1>", [true]),
("1010", [false, true, false, true]),
("<1010>", [false, true, false, true]),
("0101", [true, false, true, false]),
("<0101>", [true, false, true, false]),
("111000", [false, false, false, true, true, true]),
("<111000>", [false, false, false, true, true, true]),
("000111", [true, true, true, false, false, false]),
("<000111>", [true, true, true, false, false, false]),
("_", nil),
("<", nil),
("<<", nil),
(">", nil),
(">>", nil),
("<01", nil),
("101>", nil),
("<<100>>", nil),
("01<10", nil),
("10>10", nil),
("1<010>", nil),
("<010>1", nil),
("00010101X", nil),
("①⓪⓪①", nil),
("2341", nil),