From e6e0c68cafe6f9561f7d794b9137054aa0077ee2 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Sun, 5 Jul 2020 17:11:02 +0100 Subject: [PATCH] Additional testing --- .../Decoder/DictionaryKeyedContainer.swift | 6 +- .../Decoder/KeyedInnerListDecoder.swift | 6 +- .../Decoder/KeyedItemDecoder.swift | 6 +- .../Decoder/ParametersDecoder.swift | 6 +- .../Decoder/StructuredFieldDecoder.swift | 91 ++++++++++++--- .../Decoder/StructuredHeaderCodingKey.swift | 12 +- .../Decoder/TopLevelListDecoder.swift | 109 ++++++++++++++++++ .../StructuredFieldDecoderTests.swift | 67 +++++++++++ 8 files changed, 271 insertions(+), 32 deletions(-) create mode 100644 Sources/StructuredHeaders/Decoder/TopLevelListDecoder.swift diff --git a/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift b/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift index 07c8970..a51c010 100644 --- a/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift +++ b/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift @@ -42,7 +42,7 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol { } func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -50,7 +50,7 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol { } func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -58,7 +58,7 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol { } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } diff --git a/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift b/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift index 1cad401..c60c0b6 100644 --- a/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift +++ b/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift @@ -47,7 +47,7 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol { } func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -55,7 +55,7 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol { } func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -63,7 +63,7 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol { } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } diff --git a/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift b/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift index 1a93bed..ced2307 100644 --- a/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift +++ b/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift @@ -47,7 +47,7 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol { } func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -55,7 +55,7 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol { } func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -63,7 +63,7 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol { } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } diff --git a/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift b/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift index be62256..a5d64d4 100644 --- a/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift +++ b/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift @@ -42,7 +42,7 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol { } func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -50,7 +50,7 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol { } func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } @@ -58,7 +58,7 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol { } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { - try self.decoder.push(_StructuredHeaderCodingKey(key)) + try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy)) defer { self.decoder.pop() } diff --git a/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift b/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift index bccb995..7dff622 100644 --- a/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift +++ b/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift @@ -13,13 +13,50 @@ //===----------------------------------------------------------------------===// public struct StructuredFieldDecoder { + public var keyDecodingStrategy: KeyDecodingStrategy? + public init() { } } +extension StructuredFieldDecoder { + public struct KeyDecodingStrategy: Hashable { + fileprivate enum Base: Hashable { + case lowercase + } + + fileprivate var base: Base + + /// Lowercase all coding keys before searching for them in keyed containers such as + /// dictionaries or parameters. + public static let lowercase = KeyDecodingStrategy(base: .lowercase) + } +} + extension StructuredFieldDecoder { public func decode(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { let parser = StructuredFieldParser(data) - let decoder = _StructuredFieldDecoder(parser) + let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy) + return try type.init(from: decoder) + } + + public func decodeDictionaryField(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + let parser = StructuredFieldParser(data) + let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy) + try decoder.parseDictionaryField() + return try type.init(from: decoder) + } + + public func decodeListField(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + let parser = StructuredFieldParser(data) + let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy) + try decoder.parseListField() + return try type.init(from: decoder) + } + + public func decodeItemField(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + let parser = StructuredFieldParser(data) + let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy) + try decoder.parseItemField() return try type.init(from: decoder) } } @@ -31,9 +68,12 @@ class _StructuredFieldDecoder where BaseData.E // our way down with values, but doing that is a CoWy nightmare from which we cannot escape. private var _codingStack: [CodingStackEntry] - init(_ parser: StructuredFieldParser) { + var keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy? + + init(_ parser: StructuredFieldParser, keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?) { self.parser = parser self._codingStack = [] + self.keyDecodingStrategy = keyDecodingStrategy } } @@ -59,13 +99,10 @@ extension _StructuredFieldDecoder: Decoder { func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { if self.currentElement == nil { - // First parse, this is a dictionary. - // TODO: This assumption is wrong. Item and List headers may appear here if users want - // their parameters. We have to check for those cases. - let parsed = try self.parser.parseDictionaryField() - - // We unconditionally add to the base of the coding stack here. This element is never popped off. - self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .dictionary(parsed))) + // First parse. This may be a dictionary, but depending on the keys this may also be list or item. + // We can't really detect this (Key isn't caseiterable) so we just kinda have to hope. Users can tell + // us with alternative methods if we're wrong. + try self.parseDictionaryField() } switch self.currentElement! { @@ -86,16 +123,13 @@ extension _StructuredFieldDecoder: Decoder { func unkeyedContainer() throws -> UnkeyedDecodingContainer { if self.currentElement == nil { // First parse, this is a list header. - let parsed = try self.parser.parseListField() - - // We unconditionally add to the base of the coding stack here. This element is never popped off. - self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .list(parsed))) + try self.parseListField() } // We have unkeyed containers for lists, inner lists, and bare inner lists. switch self.currentElement! { case .list(let items): - fatalError("Not yet implemented") + return TopLevelListDecoder(items, decoder: self) case .innerList(let innerList): return BareInnerListDecoder(innerList.bareInnerList, decoder: self) case .bareInnerList(let bareInnerList): @@ -109,10 +143,7 @@ extension _StructuredFieldDecoder: Decoder { func singleValueContainer() throws -> SingleValueDecodingContainer { if self.currentElement == nil { // First parse, this is a an item header. - let parsed = try self.parser.parseItemField() - - // We unconditionally add to the base of the coding stack here. This element is never popped off. - self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .item(parsed))) + try self.parseItemField() } // We have single value containers for items and bareItems. @@ -125,6 +156,30 @@ extension _StructuredFieldDecoder: Decoder { throw StructuredHeaderError.invalidTypeForItem } } + + func parseDictionaryField() throws { + precondition(self._codingStack.isEmpty) + let parsed = try self.parser.parseDictionaryField() + + // We unconditionally add to the base of the coding stack here. This element is never popped off. + self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .dictionary(parsed))) + } + + func parseListField() throws { + precondition(self._codingStack.isEmpty) + let parsed = try self.parser.parseListField() + + // We unconditionally add to the base of the coding stack here. This element is never popped off. + self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .list(parsed))) + } + + func parseItemField() throws { + precondition(self._codingStack.isEmpty) + let parsed = try self.parser.parseItemField() + + // We unconditionally add to the base of the coding stack here. This element is never popped off. + self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .item(parsed))) + } } extension _StructuredFieldDecoder { diff --git a/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift b/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift index 7bdc75b..a10d594 100644 --- a/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift +++ b/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift @@ -26,8 +26,16 @@ struct _StructuredHeaderCodingKey : CodingKey { self.intValue = intValue } - init(_ key: Key) { - self.stringValue = key.stringValue + init(_ key: Key, keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?) { + switch keyDecodingStrategy { + case .none: + self.stringValue = key.stringValue + case .some(.lowercase): + self.stringValue = key.stringValue.lowercased() + default: + preconditionFailure("Invalid key decoding strategy") + } + self.intValue = key.intValue } } diff --git a/Sources/StructuredHeaders/Decoder/TopLevelListDecoder.swift b/Sources/StructuredHeaders/Decoder/TopLevelListDecoder.swift new file mode 100644 index 0000000..5c5e5ec --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/TopLevelListDecoder.swift @@ -0,0 +1,109 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +struct TopLevelListDecoder where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var list: [ItemOrInnerList] + + private var currentOffset: Int + + private var decoder: _StructuredFieldDecoder + + init(_ list: [ItemOrInnerList], decoder: _StructuredFieldDecoder) { + self.list = list + self.currentOffset = 0 + self.decoder = decoder + } +} + +extension TopLevelListDecoder: UnkeyedDecodingContainer { + var codingPath: [CodingKey] { + return self.decoder.codingPath + } + + var count: Int? { + return self.list.count + } + + var isAtEnd: Bool { + return self.currentOffset == self.list.count + } + + var currentIndex: Int { + return self.currentOffset + } + + mutating func decodeNil() throws -> Bool { + // We never decode nil. + return false + } + + mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + // This is a request to decode a scalar. We decode the next entry and increment the index. + guard !self.isAtEnd else { + throw StructuredHeaderError.indexOutOfRange + } + + let codingKey = _StructuredHeaderCodingKey(intValue: self.currentOffset) + defer { + self.currentOffset += 1 + } + + try self.decoder.push(codingKey) + defer { + self.decoder.pop() + } + return try type.init(from: self.decoder) + } + + mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + // This is a request to decode a full item. We decode the next entry and increment the index. + guard !self.isAtEnd else { + throw StructuredHeaderError.indexOutOfRange + } + + let codingKey = _StructuredHeaderCodingKey(intValue: self.currentOffset) + defer { + self.currentOffset += 1 + } + + try self.decoder.push(codingKey) + defer { + self.decoder.pop() + } + return try self.decoder.container(keyedBy: type) + } + + mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { + guard !self.isAtEnd else { + throw StructuredHeaderError.indexOutOfRange + } + + let codingKey = _StructuredHeaderCodingKey(intValue: self.currentOffset) + defer { + self.currentOffset += 1 + } + + try self.decoder.push(codingKey) + defer { + self.decoder.pop() + } + return try self.decoder.unkeyedContainer() + } + + mutating func superDecoder() throws -> Decoder { + // No inheritance here folks + throw StructuredHeaderError.invalidTypeForItem + } + +} diff --git a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift index 88906d8..266156a 100644 --- a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift +++ b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift @@ -121,4 +121,71 @@ final class StructuredFieldDecoderTests: XCTestCase { XCTAssertThrowsError(try StructuredFieldDecoder().decode(Bool.self, from: Array(headerField.utf8))) XCTAssertThrowsError(try StructuredFieldDecoder().decode(String.self, from: Array(intField.utf8))) } + + func testDecodingTopLevelItemWithParameters() throws { + struct IntWithParams: Codable, Equatable { + var item: Int + var parameters: [String: String] + } + + let headerField = "5;bar=baz" + let expected = IntWithParams(item: 5, parameters: ["bar": "baz"]) + XCTAssertEqual(expected, try StructuredFieldDecoder().decodeItemField(from: Array(headerField.utf8))) + } + + func testDecodingTopLevelList() throws { + let headerField = "foo, bar, baz" + let expected = ["foo", "bar", "baz"] + XCTAssertEqual(expected, try StructuredFieldDecoder().decodeListField(from: Array(headerField.utf8))) + XCTAssertEqual(expected, try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + } + + func testDecodingLowercaseKeyStrategy() throws { + struct Camel: Codable, Equatable { + var hasHump: Bool + } + + let headerField = "hashump" + let expected = Camel(hasHump: true) + var decoder = StructuredFieldDecoder() + decoder.keyDecodingStrategy = .lowercase + + XCTAssertEqual(expected, try decoder.decodeDictionaryField(from: Array(headerField.utf8))) + } + + func testDecodingLowercaseKeyStrategyParameters() throws { + struct CamelParameters: Codable, Equatable { + var hasHump: Bool + } + + struct Camel: Codable, Equatable { + var item: String + var parameters: CamelParameters + } + + let headerField = "dromedary;hashump" + let expected = Camel(item: "dromedary", parameters: .init(hasHump: true)) + var decoder = StructuredFieldDecoder() + decoder.keyDecodingStrategy = .lowercase + + XCTAssertEqual(expected, try decoder.decodeItemField(from: Array(headerField.utf8))) + } + + func testDecodingKeyMissingFromDictionary() throws { + struct MissingKey: Codable { + var foo: Int + } + + let headerField = "bar=baz" + XCTAssertThrowsError(try StructuredFieldDecoder().decodeDictionaryField(MissingKey.self, from: Array(headerField.utf8))) + } + + func testDecodingKeyAsItemWantedInnerList() throws { + struct MissingInnerList: Codable { + var innerlist: [String] + } + + let headerField = "innerlist=x" + XCTAssertThrowsError(try StructuredFieldDecoder().decodeDictionaryField(MissingInnerList.self, from: Array(headerField.utf8))) + } }