mirror of
https://github.com/apple/swift-collections
synced 2026-11-24 04:27:53 +00:00
[BitArray] Update LosslessStringConvertible initializer to accept new description format
This commit is contained in:
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
|
||||
|
||||
Reference in new issue
Block a user