mirror of
https://github.com/apple/swift-collections
synced 2026-11-25 04:37:48 +00:00
[BitArray] Use a platform-independent Codable encoding
This commit is contained in:
1 parent
a137a71c6f
commit
141ef3c706
2 files changed
+64
-49
No files matched your search
@@ -12,35 +12,45 @@
|
||||
extension BitArray: Codable {
|
||||
/// Encodes this bit array into the given encoder.
|
||||
///
|
||||
/// Bit arrays are encoded as an unkeyed container of `UInt` values,
|
||||
/// Bit arrays are encoded as an unkeyed container of `UInt64` values,
|
||||
/// representing the total number of bits in the array, followed by
|
||||
/// UInt-sized pieces of the underlying bitmap.
|
||||
/// UInt64-sized pieces of the underlying bitmap.
|
||||
///
|
||||
/// - Parameter encoder: The encoder to write data to.
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.unkeyedContainer()
|
||||
try container.encode(_count)
|
||||
for word in _storage {
|
||||
try container.encode(word.value)
|
||||
}
|
||||
try container.encode(UInt64(truncatingIfNeeded: _count))
|
||||
try _storage._encodeAsUInt64(to: &container)
|
||||
}
|
||||
|
||||
/// Creates a new bit array by decoding from the given decoder.
|
||||
///
|
||||
/// Bit arrays are encoded as an unkeyed container of `UInt` values,
|
||||
/// Bit arrays are encoded as an unkeyed container of `UInt64` values,
|
||||
/// representing the total number of bits in the array, followed by
|
||||
/// UInt-sized pieces of the underlying bitmap.
|
||||
/// UInt64-sized pieces of the underlying bitmap.
|
||||
///
|
||||
/// - Parameter decoder: The decoder to read data from.
|
||||
public init(from decoder: Decoder) throws {
|
||||
var container = try decoder.unkeyedContainer()
|
||||
let count = try container.decode(UInt.self)
|
||||
var words: [_Word] = []
|
||||
if let c = container.count {
|
||||
words.reserveCapacity(c)
|
||||
guard let count = UInt(exactly: try container.decode(UInt64.self)) else {
|
||||
let context = DecodingError.Context(
|
||||
codingPath: container.codingPath,
|
||||
debugDescription: "Bit Array too long")
|
||||
throw DecodingError.dataCorrupted(context)
|
||||
}
|
||||
while !container.isAtEnd {
|
||||
words.append(_Word(try container.decode(UInt.self)))
|
||||
var words = try [_Word](
|
||||
_fromUInt64: &container,
|
||||
reservingCount: container.count.map { Swift.max(1, $0) - 1 })
|
||||
if _Word.capacity < UInt64.bitWidth,
|
||||
count <= (words.count - 1) * _Word.capacity
|
||||
{
|
||||
let last = words.removeLast()
|
||||
guard last.isEmpty else {
|
||||
let context = DecodingError.Context(
|
||||
codingPath: container.codingPath,
|
||||
debugDescription: "Unexpected bits after end")
|
||||
throw DecodingError.dataCorrupted(context)
|
||||
}
|
||||
}
|
||||
guard
|
||||
count <= words.count * _Word.capacity,
|
||||
|
||||
Reference in new issue
Block a user