[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