Add support for encoding/decoding binary data

This commit is contained in:
Cory Benfield committed 2020-07-16 13:16:20 +01:00
1 parent 5aaca631da
commit b797a6ff50
11 files changed
+211 -12

No files matched your search

@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
struct BareInnerListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
@@ -64,7 +65,13 @@ extension BareInnerListDecoder: UnkeyedDecodingContainer {
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
if type is Data.Type {
let container = try self.decoder.singleValueContainer()
return try container.decode(Data.self) as! T
} else {
return try type.init(from: self.decoder)
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
struct BareItemDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
@@ -96,6 +97,18 @@ extension BareItemDecoder: SingleValueDecodingContainer {
return bool
}
func decode(_ type: Data.Type) throws -> Data {
guard case .undecodedByteSequence(let data) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
guard let decoded = Data(base64Encoded: Data(data)) else {
throw StructuredHeaderError.invalidByteSequence
}
return decoded
}
func decodeNil() -> Bool {
// Items are never nil.
return false
@@ -131,6 +144,8 @@ extension BareItemDecoder: SingleValueDecodingContainer {
return try self.decode(String.self) as! T
case is Bool.Type:
return try self.decode(Bool.self) as! T
case is Data.Type:
return try self.decode(Data.self) as! T
default:
// Some other codable type. Not sure what to do here yet.
// TODO: What about binary data here? For now we'll ignore it.
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
struct DictionaryKeyedContainer<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
@@ -47,7 +48,13 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol {
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
if type is Data.Type {
let container = try self.decoder.singleValueContainer()
return try container.decode(Data.self) as! T
} else {
return try type.init(from: self.decoder)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
private let keyedInnerListDecoderSupportedKeys = ["items", "parameters"]
@@ -52,7 +53,13 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol {
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
if type is Data.Type {
let container = try self.decoder.singleValueContainer()
return try container.decode(Data.self) as! T
} else {
return try type.init(from: self.decoder)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
private let keyedItemDecoderSupportedKeys = ["item", "parameters"]
@@ -52,7 +53,13 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol {
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
if type is Data.Type {
let container = try self.decoder.singleValueContainer()
return try container.decode(Data.self) as! T
} else {
return try type.init(from: self.decoder)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
struct ParametersDecoder<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
@@ -47,7 +48,13 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol {
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
if type is Data.Type {
let container = try self.decoder.singleValueContainer()
return try container.decode(Data.self) as! T
} else {
return try type.init(from: self.decoder)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
public struct StructuredFieldDecoder {
@@ -58,7 +59,15 @@ extension StructuredFieldDecoder {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseItemField()
return try type.init(from: decoder)
// An escape hatch here for top-level data: if we don't do this, it'll ask for
// an unkeyed container and get very confused.
if type is Data.Type {
let container = try decoder.singleValueContainer()
return try container.decode(Data.self) as! StructuredField
} else {
return try type.init(from: decoder)
}
}
}
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
struct TopLevelListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
@@ -64,7 +65,13 @@ extension TopLevelListDecoder: UnkeyedDecodingContainer {
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
if type is Data.Type {
let container = try self.decoder.singleValueContainer()
return try container.decode(Data.self) as! T
} else {
return try type.init(from: self.decoder)
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
@@ -11,6 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
public struct StructuredFieldEncoder {
@@ -105,7 +106,17 @@ class _StructuredFieldEncoder {
fileprivate func encodeItemField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
self.push(key: .init(stringValue: ""), newStorage: .itemHeader)
try data.encode(to: self)
// There's an awkward special hook here: if the outer type is `Data`,
// we skip the regular encoding path. This is because otherwise `Data` will
// ask for an unkeyed container and it all falls apart.
//
// Everything else goes through the normal flow.
if let value = data as? Data {
try self.encode(value)
} else {
try data.encode(to: self)
}
switch self.currentStackEntry.storage {
case .item(let item):
@@ -223,6 +234,11 @@ extension _StructuredFieldEncoder: SingleValueEncodingContainer {
try self._encodeFixedWidthInteger(value)
}
func encode(_ data: Data) throws {
let encoded = data.base64EncodedData()
try self.currentStackEntry.storage.insertBareItem(.undecodedByteSequence(encoded))
}
func encode<T>(_ value: T) throws where T : Encodable {
switch value {
case let value as UInt8:
@@ -253,9 +269,9 @@ extension _StructuredFieldEncoder: SingleValueEncodingContainer {
try self.encode(value)
case let value as Bool:
try self.encode(value)
case let value as Data:
try self.encode(value)
default:
// Some other codable type. Not sure what to do yet.
// TODO: what about binary data here?
throw StructuredHeaderError.invalidTypeForItem
}
}
@@ -364,6 +380,10 @@ extension _StructuredFieldEncoder {
try self._appendFixedWidthInteger(value)
}
func append(_ value: Data) throws {
try self.currentStackEntry.storage.appendBareItem(.undecodedByteSequence(value.base64EncodedData()))
}
func append<T>(_ value: T) throws where T : Encodable {
switch value {
case let value as UInt8:
@@ -394,6 +414,8 @@ extension _StructuredFieldEncoder {
try self.append(value)
case let value as Bool:
try self.append(value)
case let value as Data:
try self.append(value)
default:
// Some other codable type.
switch self.currentStackEntry.storage {
@@ -512,6 +534,11 @@ extension _StructuredFieldEncoder {
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: Data, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self.currentStackEntry.storage.insertBareItem(.undecodedByteSequence(value.base64EncodedData()), atKey: key)
}
func encode<T>(_ value: T, forKey key: String) throws where T: Encodable {
let key = self.sanitizeKey(key)
@@ -544,6 +571,8 @@ extension _StructuredFieldEncoder {
try self.encode(value, forKey: key)
case let value as Bool:
try self.encode(value, forKey: key)
case let value as Data:
try self.encode(value, forKey: key)
default:
// Ok, we don't know what this is. This can only happen for a dictionary, or
// for anything with parameters, or for inner lists.
@@ -642,7 +671,7 @@ extension _StructuredFieldEncoder {
/// Note that we never have a bare item here. This is deliberate: bare items
/// are not a container for anything else, and so can never appear.
internal enum NodeType {
typealias DataType = ArraySlice<UInt8>
typealias DataType = Data
case dictionaryHeader
case listHeader
@@ -808,7 +837,7 @@ extension _StructuredFieldEncoder {
}
extension Item where BaseData == ArraySlice<UInt8> {
extension Item where BaseData == _StructuredFieldEncoder.NodeType.DataType {
fileprivate init(_ partialItem: _StructuredFieldEncoder.NodeType.PartialItem) {
self.init(bareItem: partialItem.bareItem!, parameters: partialItem.parameters)
}
@@ -189,4 +189,97 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "innerlist=x"
XCTAssertThrowsError(try StructuredFieldDecoder().decodeDictionaryField(MissingInnerList.self, from: Array(headerField.utf8)))
}
func testDecodingBinaryAsTopLevelData() throws {
let headerField = ":AQIDBA==:"
XCTAssertEqual(
Data([1, 2, 3, 4]),
try StructuredFieldDecoder().decodeItemField(Data.self, from: Array(headerField.utf8))
)
}
func testDecodingBinaryAsParameterisedData() throws {
struct Item: Codable, Equatable {
var item: Data
var parameters: [String: Float]
}
let headerFieldNoParameters = ":AQIDBA==:"
let headerFieldParameters = ":AQIDBA==:;q=0.8"
XCTAssertEqual(
Item(item: Data([1, 2, 3, 4]), parameters: [:]),
try StructuredFieldDecoder().decodeItemField(Item.self, from: Array(headerFieldNoParameters.utf8))
)
XCTAssertEqual(
Item(item: Data([1, 2, 3, 4]), parameters: ["q": 0.8]),
try StructuredFieldDecoder().decodeItemField(Item.self, from: Array(headerFieldParameters.utf8))
)
}
func testDecodingBinaryInParameterField() throws {
struct Item: Codable, Equatable {
var item: Int
var parameters: [String: Data]
}
let headerField = "1;q=:AQIDBA==:"
XCTAssertEqual(
Item(item: 1, parameters: ["q": Data([1, 2, 3, 4])]),
try StructuredFieldDecoder().decodeItemField(Item.self, from: Array(headerField.utf8))
)
}
func testDecodingBinaryInOuterListRaw() throws {
let headerField = ":AQIDBA==:, :BQYHCA==:"
XCTAssertEqual(
[Data([1, 2, 3, 4]), Data([5, 6, 7, 8])],
try StructuredFieldDecoder().decodeListField([Data].self, from: Array(headerField.utf8))
)
}
func testDecodingBinaryInOuterListKeyed() throws {
struct ListField: Codable, Equatable {
var items: [Data]
}
let headerField = ":AQIDBA==:, :BQYHCA==:"
XCTAssertEqual(
[Data([1, 2, 3, 4]), Data([5, 6, 7, 8])],
try StructuredFieldDecoder().decodeListField([Data].self, from: Array(headerField.utf8))
)
}
func testDecodingBinaryInInnerListRaw() throws {
let headerField = "(:AQIDBA==: :BQYHCA==:), (:AQIDBA==: :BQYHCA==:)"
XCTAssertEqual(
Array(repeating: [Data([1, 2, 3, 4]), Data([5, 6, 7, 8])], count: 2),
try StructuredFieldDecoder().decodeListField([[Data]].self, from: Array(headerField.utf8))
)
}
func testDecodingBinaryInInnerListKeyed() throws {
struct ListField: Codable, Equatable {
var items: [Data]
var parameters: [String: Bool]
}
let headerField = "(:AQIDBA==: :BQYHCA==:);foo, (:AQIDBA==: :BQYHCA==:);foo"
XCTAssertEqual(
Array(repeating: ListField(items: [Data([1, 2, 3, 4]), Data([5, 6, 7, 8])], parameters: ["foo": true]), count: 2),
try StructuredFieldDecoder().decodeListField([ListField].self, from: Array(headerField.utf8))
)
}
func testDecodingBinaryInDictionaries() throws {
struct DictionaryField: Codable, Equatable {
var bin: Data
var box: Data
}
let headerField = "bin=:AQIDBA==:, box=:AQIDBA==:"
XCTAssertEqual(
DictionaryField(bin: Data([1, 2, 3, 4]), box: Data([1, 2, 3, 4])),
try StructuredFieldDecoder().decodeDictionaryField(DictionaryField.self, from: Array(headerField.utf8))
)
}
}
@@ -37,6 +37,9 @@ final class StructuredFieldEncoderTests: XCTestCase {
// Decimal
XCTAssertEqual(Array("102.2".utf8), try encoder.encodeItemField(Float(102.2)))
XCTAssertEqual(Array("-166.66".utf8), try encoder.encodeItemField(Double(-166.66)))
// Binary Data
XCTAssertEqual(Array(":AQIDBA==:".utf8), try encoder.encodeItemField(Data([1, 2, 3, 4])))
}
func testEncodeKeyedItemHeader() throws {
@@ -62,6 +65,10 @@ final class StructuredFieldEncoderTests: XCTestCase {
// Decimal
XCTAssertEqual(Array("102.2;y=?0".utf8), try encoder.encodeItemField(KeyedItem(item: Float(102.2), parameters: ["y": false])))
XCTAssertEqual(Array("-166.66".utf8), try encoder.encodeItemField(KeyedItem(item: Double(-166.66), parameters: [:])))
// Binary
XCTAssertEqual(Array(":AQIDBA==:;y=?0".utf8), try encoder.encodeItemField(KeyedItem(item: Data([1, 2, 3, 4]), parameters: ["y": false])))
XCTAssertEqual(Array(":AQIDBA==:".utf8), try encoder.encodeItemField(KeyedItem(item: Data([1, 2, 3, 4]), parameters: [:])))
}
func testEncodeKeyedItemHeaderWithParamsAsStruct() throws {
@@ -118,6 +125,10 @@ final class StructuredFieldEncoderTests: XCTestCase {
// Decimal
XCTAssertEqual(Array("102.2, -166.66".utf8), try encoder.encodeListField([Float(102.2), Float(-166.66)]))
// Binary
XCTAssertEqual(Array(":AQIDBA==:, :BQYHCA==:".utf8),
try encoder.encodeListField([Data([1, 2, 3, 4]), Data([5, 6, 7, 8])]))
}
func testListFieldInnerItemsWithDict() throws {