From 141f102bd0eec70d5fd5bfad82c89b999c9e6d8c Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 16 Jul 2020 17:28:47 +0100 Subject: [PATCH] Support Decimal as well --- .../Decoder/BareInnerListDecoder.swift | 3 + .../Decoder/BareItemDecoder.swift | 14 +++- .../Decoder/DictionaryKeyedContainer.swift | 3 + .../Decoder/KeyedInnerListDecoder.swift | 3 + .../Decoder/KeyedItemDecoder.swift | 3 + .../Decoder/ParametersDecoder.swift | 3 + .../Decoder/StructuredFieldDecoder.swift | 3 + .../Decoder/TopLevelListDecoder.swift | 3 + .../Encoder/StructuredFieldEncoder.swift | 43 +++++++++- .../StructuredFieldDecoderTests.swift | 82 +++++++++++++++++++ .../StructuredFieldEncoderTests.swift | 5 ++ 11 files changed, 161 insertions(+), 4 deletions(-) diff --git a/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift index b7e118a..5e84858 100644 --- a/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/BareInnerListDecoder.swift @@ -69,6 +69,9 @@ extension BareInnerListDecoder: UnkeyedDecodingContainer { if type is Data.Type { let container = try self.decoder.singleValueContainer() return try container.decode(Data.self) as! T + } else if type is Decimal.Type { + let container = try self.decoder.singleValueContainer() + return try container.decode(Decimal.self) as! T } else { return try type.init(from: self.decoder) } diff --git a/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift index b8a1c68..c9017d4 100644 --- a/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/BareItemDecoder.swift @@ -109,6 +109,16 @@ extension BareItemDecoder: SingleValueDecodingContainer { return decoded } + func decode(_ type: Decimal.Type) throws -> Decimal { + guard case .decimal(let pseudoDecimal) = self.item else { + throw StructuredHeaderError.invalidTypeForItem + } + + return Decimal(sign: pseudoDecimal.mantissa > 0 ? .plus : .minus, + exponent: Int(pseudoDecimal.exponent), + significand: Decimal(pseudoDecimal.mantissa)) + } + func decodeNil() -> Bool { // Items are never nil. return false @@ -146,9 +156,9 @@ extension BareItemDecoder: SingleValueDecodingContainer { return try self.decode(Bool.self) as! T case is Data.Type: return try self.decode(Data.self) as! T + case is Decimal.Type: + return try self.decode(Decimal.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. throw StructuredHeaderError.invalidTypeForItem } } diff --git a/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift b/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift index 3aae1b1..d7ea83d 100644 --- a/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift +++ b/Sources/CodableStructuredHeaders/Decoder/DictionaryKeyedContainer.swift @@ -52,6 +52,9 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol { if type is Data.Type { let container = try self.decoder.singleValueContainer() return try container.decode(Data.self) as! T + } else if type is Decimal.Type { + let container = try self.decoder.singleValueContainer() + return try container.decode(Decimal.self) as! T } else { return try type.init(from: self.decoder) } diff --git a/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift index e57508f..09980a5 100644 --- a/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/KeyedInnerListDecoder.swift @@ -57,6 +57,9 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol { if type is Data.Type { let container = try self.decoder.singleValueContainer() return try container.decode(Data.self) as! T + } else if type is Decimal.Type { + let container = try self.decoder.singleValueContainer() + return try container.decode(Decimal.self) as! T } else { return try type.init(from: self.decoder) } diff --git a/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift index 6f0a2f7..0448bef 100644 --- a/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/KeyedItemDecoder.swift @@ -57,6 +57,9 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol { if type is Data.Type { let container = try self.decoder.singleValueContainer() return try container.decode(Data.self) as! T + } else if type is Decimal.Type { + let container = try self.decoder.singleValueContainer() + return try container.decode(Decimal.self) as! T } else { return try type.init(from: self.decoder) } diff --git a/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift index dc50d60..4b82262 100644 --- a/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/ParametersDecoder.swift @@ -52,6 +52,9 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol { if type is Data.Type { let container = try self.decoder.singleValueContainer() return try container.decode(Data.self) as! T + } else if type is Decimal.Type { + let container = try self.decoder.singleValueContainer() + return try container.decode(Decimal.self) as! T } else { return try type.init(from: self.decoder) } diff --git a/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift b/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift index 387b05f..7236de4 100644 --- a/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/StructuredFieldDecoder.swift @@ -102,6 +102,9 @@ extension StructuredFieldDecoder { if type is Data.Type { let container = try decoder.singleValueContainer() return try container.decode(Data.self) as! StructuredField + } else if type is Decimal.Type { + let container = try decoder.singleValueContainer() + return try container.decode(Decimal.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 0631e4b..03b3cd3 100644 --- a/Sources/CodableStructuredHeaders/Decoder/TopLevelListDecoder.swift +++ b/Sources/CodableStructuredHeaders/Decoder/TopLevelListDecoder.swift @@ -69,6 +69,9 @@ extension TopLevelListDecoder: UnkeyedDecodingContainer { if type is Data.Type { let container = try self.decoder.singleValueContainer() return try container.decode(Data.self) as! T + } else if type is Decimal.Type { + let container = try self.decoder.singleValueContainer() + return try container.decode(Decimal.self) as! T } else { return try type.init(from: self.decoder) } diff --git a/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift b/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift index c4fc1a3..d19c1b5 100644 --- a/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift +++ b/Sources/CodableStructuredHeaders/Encoder/StructuredFieldEncoder.swift @@ -128,13 +128,16 @@ class _StructuredFieldEncoder { fileprivate func encodeItemField(_ data: StructuredField) throws -> [UInt8] { self.push(key: .init(stringValue: ""), newStorage: .itemHeader) - // There's an awkward special hook here: if the outer type is `Data`, + // There's an awkward special hook here: if the outer type is `Data` or `Decimal`, // we skip the regular encoding path. This is because otherwise `Data` will - // ask for an unkeyed container and it all falls apart. + // ask for an unkeyed container and `Decimal` for a keyed one, + // and it all falls apart. // // Everything else goes through the normal flow. if let value = data as? Data { try self.encode(value) + } else if let value = data as? Decimal { + try self.encode(value) } else { try data.encode(to: self) } @@ -260,6 +263,16 @@ extension _StructuredFieldEncoder: SingleValueEncodingContainer { try self.currentStackEntry.storage.insertBareItem(.undecodedByteSequence(encoded)) } + func encode(_ data: Decimal) throws { + let significand = (data.significand as NSNumber).intValue // Yes, really. + guard let exponent = Int8(exactly: data.exponent) else { + throw StructuredHeaderError.invalidIntegerOrDecimal + } + + let pd = PseudoDecimal(mantissa: significand, exponent: Int(exponent)) + try self.currentStackEntry.storage.insertBareItem(.decimal(pd)) + } + func encode(_ value: T) throws where T : Encodable { switch value { case let value as UInt8: @@ -292,6 +305,8 @@ extension _StructuredFieldEncoder: SingleValueEncodingContainer { try self.encode(value) case let value as Data: try self.encode(value) + case let value as Decimal: + try self.encode(value) default: throw StructuredHeaderError.invalidTypeForItem } @@ -405,6 +420,16 @@ extension _StructuredFieldEncoder { try self.currentStackEntry.storage.appendBareItem(.undecodedByteSequence(value.base64EncodedData())) } + func append(_ value: Decimal) throws { + let significand = (value.significand as NSNumber).intValue // Yes, really. + guard let exponent = Int8(exactly: value.exponent) else { + throw StructuredHeaderError.invalidIntegerOrDecimal + } + + let pd = PseudoDecimal(mantissa: significand, exponent: Int(exponent)) + try self.currentStackEntry.storage.appendBareItem(.decimal(pd)) + } + func append(_ value: T) throws where T : Encodable { switch value { case let value as UInt8: @@ -437,6 +462,8 @@ extension _StructuredFieldEncoder { try self.append(value) case let value as Data: try self.append(value) + case let value as Decimal: + try self.append(value) default: // Some other codable type. switch self.currentStackEntry.storage { @@ -560,6 +587,16 @@ extension _StructuredFieldEncoder { try self.currentStackEntry.storage.insertBareItem(.undecodedByteSequence(value.base64EncodedData()), atKey: key) } + func encode(_ value: Decimal, forKey key: String) throws { + let significand = (value.significand as NSNumber).intValue // Yes, really. + guard let exponent = Int8(exactly: value.exponent) else { + throw StructuredHeaderError.invalidIntegerOrDecimal + } + + let pd = PseudoDecimal(mantissa: significand, exponent: Int(exponent)) + try self.currentStackEntry.storage.insertBareItem(.decimal(pd), atKey: key) + } + func encode(_ value: T, forKey key: String) throws where T: Encodable { let key = self.sanitizeKey(key) @@ -594,6 +631,8 @@ extension _StructuredFieldEncoder { try self.encode(value, forKey: key) case let value as Data: try self.encode(value, forKey: key) + case let value as Decimal: + 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. diff --git a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift index dfc6b2f..ec8a585 100644 --- a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift +++ b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift @@ -282,4 +282,86 @@ final class StructuredFieldDecoderTests: XCTestCase { try StructuredFieldDecoder().decodeDictionaryField(DictionaryField.self, from: Array(headerField.utf8)) ) } + + func testDecodingDecimalAsTopLevelData() throws { + let headerField = "987654321.123" + XCTAssertEqual( + Decimal(string: "987654321.123")!, + try StructuredFieldDecoder().decodeItemField(Decimal.self, from: Array(headerField.utf8)) + ) + } + + func testDecodingDecimalAsParameterisedData() throws { + struct Item: Codable, Equatable { + var item: Decimal + var parameters: [String: Float] + } + + let headerFieldNoParameters = "987654321.123" + let headerFieldParameters = "987654321.123;q=0.8" + + XCTAssertEqual( + Item(item: Decimal(string: "987654321.123")!, parameters: [:]), + try StructuredFieldDecoder().decodeItemField(Item.self, from: Array(headerFieldNoParameters.utf8)) + ) + + XCTAssertEqual( + Item(item: Decimal(string: "987654321.123")!, parameters: ["q": 0.8]), + try StructuredFieldDecoder().decodeItemField(Item.self, from: Array(headerFieldParameters.utf8)) + ) + } + + func testDecodingDecimalInParameterField() throws { + struct Item: Codable, Equatable { + var item: Int + var parameters: [String: Decimal] + } + + let headerField = "1;q=987654321.123" + XCTAssertEqual( + Item(item: 1, parameters: ["q": Decimal(string: "987654321.123")!]), + try StructuredFieldDecoder().decodeItemField(Item.self, from: Array(headerField.utf8)) + ) + } + + func testDecodingDecimalInOuterListRaw() throws { + let headerField = "987654321.123, 123456789.321" + XCTAssertEqual( + [Decimal(string: "987654321.123")!, Decimal(string: "123456789.321")!], + try StructuredFieldDecoder().decodeListField([Decimal].self, from: Array(headerField.utf8)) + ) + } + + func testDecodingDecimalInInnerListRaw() throws { + let headerField = "(987654321.123 123456789.321), (987654321.123 123456789.321)" + XCTAssertEqual( + Array(repeating: [Decimal(string: "987654321.123")!, Decimal(string: "123456789.321")!], count: 2), + try StructuredFieldDecoder().decodeListField([[Decimal]].self, from: Array(headerField.utf8)) + ) + } + + func testDecodingDecimalInInnerListKeyed() throws { + struct ListField: Codable, Equatable { + var items: [Decimal] + var parameters: [String: Bool] + } + let headerField = "(987654321.123 123456789.321);foo, (987654321.123 123456789.321);foo" + XCTAssertEqual( + Array(repeating: ListField(items: [Decimal(string: "987654321.123")!, Decimal(string: "123456789.321")!], parameters: ["foo": true]), count: 2), + try StructuredFieldDecoder().decodeListField([ListField].self, from: Array(headerField.utf8)) + ) + } + + func testDecodingDecimalInDictionaries() throws { + struct DictionaryField: Codable, Equatable { + var bin: Decimal + var box: Decimal + } + + let headerField = "bin=987654321.123, box=123456789.321" + XCTAssertEqual( + DictionaryField(bin: Decimal(string: "987654321.123")!, box: Decimal(string: "123456789.321")!), + try StructuredFieldDecoder().decodeDictionaryField(DictionaryField.self, from: Array(headerField.utf8)) + ) + } } diff --git a/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift b/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift index 2f5d0a4..d4f1d21 100644 --- a/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift +++ b/Tests/StructuredHeadersTests/StructuredFieldEncoderTests.swift @@ -37,6 +37,8 @@ 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))) + XCTAssertEqual(Array("987654321.123".utf8), try encoder.encodeItemField(Decimal(string: "987654321.123")!)) + XCTAssertEqual(Array("-123456789.321".utf8), try encoder.encodeItemField(Decimal(string: "-123456789.321")!)) // Binary Data XCTAssertEqual(Array(":AQIDBA==:".utf8), try encoder.encodeItemField(Data([1, 2, 3, 4]))) @@ -65,6 +67,8 @@ 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: [:]))) + XCTAssertEqual(Array("987654321.123;y=?0".utf8), try encoder.encodeItemField(KeyedItem(item: Decimal(string: "987654321.123")!, parameters: ["y": false]))) + XCTAssertEqual(Array("-123456789.321".utf8), try encoder.encodeItemField(KeyedItem(item: Decimal(string: "-123456789.321")!, parameters: [:]))) // Binary XCTAssertEqual(Array(":AQIDBA==:;y=?0".utf8), try encoder.encodeItemField(KeyedItem(item: Data([1, 2, 3, 4]), parameters: ["y": false]))) @@ -125,6 +129,7 @@ final class StructuredFieldEncoderTests: XCTestCase { // Decimal XCTAssertEqual(Array("102.2, -166.66".utf8), try encoder.encodeListField([Float(102.2), Float(-166.66)])) + XCTAssertEqual(Array("123456789.321, -987654321.123".utf8), try encoder.encodeListField([Decimal(string: "123456789.321")!, Decimal(string: "-987654321.123")!])) // Binary XCTAssertEqual(Array(":AQIDBA==:, :BQYHCA==:".utf8),