From b797a6ff50cab7475e6eda220a7ccd54c5dec576 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 16 Jul 2020 13:16:20 +0100 Subject: [PATCH] Add support for encoding/decoding binary data --- .../Decoder/BareInnerListDecoder.swift | 9 +- .../Decoder/BareItemDecoder.swift | 15 +++ .../Decoder/DictionaryKeyedContainer.swift | 9 +- .../Decoder/KeyedInnerListDecoder.swift | 9 +- .../Decoder/KeyedItemDecoder.swift | 9 +- .../Decoder/ParametersDecoder.swift | 9 +- .../Decoder/StructuredFieldDecoder.swift | 11 ++- .../Decoder/TopLevelListDecoder.swift | 9 +- .../Encoder/StructuredFieldEncoder.swift | 39 +++++++- .../StructuredFieldDecoderTests.swift | 93 +++++++++++++++++++ .../StructuredFieldEncoderTests.swift | 11 +++ 11 files changed, 211 insertions(+), 12 deletions(-) diff --git a/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift index 5790e86..b7e118a 100644 --- a/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import Foundation import StructuredHeaders struct BareInnerListDecoder 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(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { diff --git a/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift index 162ea5b..b8a1c68 100644 --- a/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import Foundation import StructuredHeaders struct BareItemDecoder 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. diff --git a/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift b/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift index 11fac4e..3aae1b1 100644 --- a/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift +++ b/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import Foundation import StructuredHeaders struct DictionaryKeyedContainer 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(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { diff --git a/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift index def9470..e57508f 100644 --- a/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift @@ -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(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { diff --git a/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift index 67f98ca..6f0a2f7 100644 --- a/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift @@ -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(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { diff --git a/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift index 1d5a8b4..dc50d60 100644 --- a/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import Foundation import StructuredHeaders struct ParametersDecoder 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(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { diff --git a/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift index 2c81968..e03b99a 100644 --- a/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift @@ -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) + } } } diff --git a/Sources/CodableStructuredHeaders/Decoder/TopLevelListDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/TopLevelListDecoder.swift index 90ec0df..0631e4b 100644 --- a/Sources/CodableStructuredHeaders/Decoder/TopLevelListDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/TopLevelListDecoder.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// +import Foundation import StructuredHeaders struct TopLevelListDecoder 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(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { diff --git a/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift b/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift index d063686..3acdba8 100644 --- a/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift +++ b/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift @@ -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(_ 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(_ 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(_ 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(_ 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 + typealias DataType = Data case dictionaryHeader case listHeader @@ -808,7 +837,7 @@ extension _StructuredFieldEncoder { } -extension Item where BaseData == ArraySlice { +extension Item where BaseData == _StructuredFieldEncoder.NodeType.DataType { fileprivate init(_ partialItem: _StructuredFieldEncoder.NodeType.PartialItem) { self.init(bareItem: partialItem.bareItem!, parameters: partialItem.parameters) } diff --git a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift index 5ca4038..dfc6b2f 100644 --- a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift +++ b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift @@ -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)) + ) + } } diff --git a/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift b/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift index 77b67d5..2f5d0a4 100644 --- a/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift +++ b/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift @@ -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 {