From 49370cd8db1d4a0f936ad16264317eb326765411 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Sun, 5 Jul 2020 13:21:16 +0100 Subject: [PATCH] Initial basic Decoder implementation --- .../StructuredHeaders/ComponentTypes.swift | 147 ++++++++++++ .../Decoder/BareInnerListDecoder.swift | 109 +++++++++ .../Decoder/BareItemDecoder.swift | 159 +++++++++++++ .../Decoder/DictionaryKeyedContainer.swift | 77 ++++++ .../Decoder/KeyedInnerListDecoder.swift | 82 +++++++ .../Decoder/KeyedItemDecoder.swift | 82 +++++++ .../Decoder/ParametersDecoder.swift | 77 ++++++ .../Decoder/StructuredFieldDecoder.swift | 221 ++++++++++++++++++ .../Decoder/StructuredHeaderCodingKey.swift | 33 +++ Sources/StructuredHeaders/Errors.swift | 38 +-- Sources/StructuredHeaders/FieldParser.swift | 167 +++---------- Sources/StructuredHeaders/OrderedMap.swift | 32 +-- .../StructuredFieldDecoderTests.swift | 124 ++++++++++ .../StructuredHeadersTests.swift | 2 +- 14 files changed, 1186 insertions(+), 164 deletions(-) create mode 100644 Sources/StructuredHeaders/ComponentTypes.swift create mode 100644 Sources/StructuredHeaders/Decoder/BareInnerListDecoder.swift create mode 100644 Sources/StructuredHeaders/Decoder/BareItemDecoder.swift create mode 100644 Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift create mode 100644 Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift create mode 100644 Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift create mode 100644 Sources/StructuredHeaders/Decoder/ParametersDecoder.swift create mode 100644 Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift create mode 100644 Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift create mode 100644 Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift diff --git a/Sources/StructuredHeaders/ComponentTypes.swift b/Sources/StructuredHeaders/ComponentTypes.swift new file mode 100644 index 0000000..b98055f --- /dev/null +++ b/Sources/StructuredHeaders/ComponentTypes.swift @@ -0,0 +1,147 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// This file contains common, currency, component types. +// +// These types are used by the parser, the serializer, and by users of the direct encoding/decoding APIs. +// They are not used by those using the Codable interface. + +// MARK:- ItemOrInnerList +public enum ItemOrInnerList where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { + case item(Item) + case innerList(InnerList) +} + +extension ItemOrInnerList: Hashable { } + +// MARK:- BareItem +public enum BareItem where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { + case bool(Bool) + case integer(Int) + case decimal(Float64) // Not great, can we do better? + case string(String) + case undecodedByteSequence(BaseData) + case token(BaseData) +} + +extension BareItem: ExpressibleByBooleanLiteral { + public init(booleanLiteral value: Bool) { + self = .bool(value) + } +} + +extension BareItem: ExpressibleByIntegerLiteral { + public init(integerLiteral value: Int) { + self = .integer(value) + } +} + +extension BareItem: ExpressibleByFloatLiteral { + public init(floatLiteral value: Float64) { + self = .decimal(value) + } +} + +extension BareItem: ExpressibleByStringLiteral { + public init(stringLiteral value: StringLiteralType) { + self = .string(value) + } +} + +extension BareItem: Hashable { } + +// MARK:- Item +public struct Item where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { + public var bareItem: BareItem + public var parameters: OrderedMap> +} + +extension Item: Hashable { } + +// MARK:- BareInnerList +public struct BareInnerList: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { + private var items: [Item] + + public init() { + self.items = [] + } + + public mutating func append(_ item: Item) { + self.items.append(item) + } +} + +extension BareInnerList: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: Item...) { + self.items = elements + } +} + +// TODO: RangeReplaceableCollection I guess +extension BareInnerList: RandomAccessCollection, MutableCollection { + public struct Index { + fileprivate var baseIndex: Array>.Index + + init(_ baseIndex: Array>.Index) { + self.baseIndex = baseIndex + } + } + + public var count: Int { + return self.items.count + } + + public var startIndex: Index { + return Index(self.items.startIndex) + } + + public var endIndex: Index { + return Index(self.items.endIndex) + } + + public func index(after i: Index) -> Index { + return Index(self.items.index(after: i.baseIndex)) + } + + public func index(before i: Index) -> Index { + return Index(self.items.index(before: i.baseIndex)) + } + + public func index(_ i: Index, offsetBy offset: Int) -> Index { + return Index(self.items.index(i.baseIndex, offsetBy: offset)) + } + + public subscript(index: Index) -> Item { + get { + return self.items[index.baseIndex] + } + set { + self.items[index.baseIndex] = newValue + } + } +} + +extension BareInnerList.Index: Hashable { } + +extension BareInnerList.Index: Comparable { + public static func <(lhs: Self, rhs: Self) -> Bool { + return lhs.baseIndex < rhs.baseIndex + } +} + +// MARK:- InnerList +public struct InnerList: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { + public var bareInnerList: BareInnerList + public var parameters: OrderedMap> +} diff --git a/Sources/StructuredHeaders/Decoder/BareInnerListDecoder.swift b/Sources/StructuredHeaders/Decoder/BareInnerListDecoder.swift new file mode 100644 index 0000000..78124f6 --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/BareInnerListDecoder.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 BareInnerListDecoder where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var list: BareInnerList + + private var currentOffset: Int + + private var decoder: _StructuredFieldDecoder + + init(_ list: BareInnerList, decoder: _StructuredFieldDecoder) { + self.list = list + self.currentOffset = 0 + self.decoder = decoder + } +} + +extension BareInnerListDecoder: 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/Sources/StructuredHeaders/Decoder/BareItemDecoder.swift b/Sources/StructuredHeaders/Decoder/BareItemDecoder.swift new file mode 100644 index 0000000..8004dc8 --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/BareItemDecoder.swift @@ -0,0 +1,159 @@ +//===----------------------------------------------------------------------===// +// +// 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 BareItemDecoder where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { + private var item: BareItem + + private var _codingPath: [_StructuredHeaderCodingKey] + + init(_ item: BareItem, codingPath: [_StructuredHeaderCodingKey]) { + self.item = item + self._codingPath = codingPath + } +} + +extension BareItemDecoder: SingleValueDecodingContainer { + var codingPath: [CodingKey] { + return self._codingPath as [CodingKey] + } + + func decode(_ type: UInt8.Type) throws -> UInt8 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: Int8.Type) throws -> Int8 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: UInt16.Type) throws -> UInt16 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: Int16.Type) throws -> Int16 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: UInt32.Type) throws -> UInt32 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: Int32.Type) throws -> Int32 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: UInt64.Type) throws -> UInt64 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: Int64.Type) throws -> Int64 { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: UInt.Type) throws -> UInt { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: Int.Type) throws -> Int { + return try self._decodeFixedWidthInteger(type) + } + + func decode(_ type: Float.Type) throws -> Float { + return try self._decodeBinaryFloatingPoint(type) + } + + func decode(_ type: Double.Type) throws -> Double { + return try self._decodeBinaryFloatingPoint(type) + } + + func decode(_ type: String.Type) throws -> String { + switch item { + case .string(let string): + return string + case .token(let token): + return String(decoding: token, as: UTF8.self) + default: + throw StructuredHeaderError.invalidTypeForItem + } + } + + func decode(_ type: Bool.Type) throws -> Bool { + guard case .bool(let bool) = self.item else { + throw StructuredHeaderError.invalidTypeForItem + } + + return bool + } + + func decodeNil() -> Bool { + // Items are never nil. + return false + } + + func decode(_ type: T.Type) throws -> T where T: Decodable { + switch type { + case is UInt8.Type: + return try self.decode(UInt8.self) as! T + case is Int8.Type: + return try self.decode(Int8.self) as! T + case is UInt16.Type: + return try self.decode(UInt16.self) as! T + case is Int16.Type: + return try self.decode(Int16.self) as! T + case is UInt32.Type: + return try self.decode(UInt32.self) as! T + case is Int32.Type: + return try self.decode(Int32.self) as! T + case is UInt64.Type: + return try self.decode(UInt64.self) as! T + case is Int64.Type: + return try self.decode(Int64.self) as! T + case is UInt.Type: + return try self.decode(UInt.self) as! T + case is Int.Type: + return try self.decode(Int.self) as! T + case is Float.Type: + return try self.decode(Float.self) as! T + case is Double.Type: + return try self.decode(Double.self) as! T + case is String.Type: + return try self.decode(String.self) as! T + case is Bool.Type: + return try self.decode(Bool.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 + } + } + + private func _decodeBinaryFloatingPoint(_ type: T.Type) throws -> T { + guard case .decimal(let decimal) = self.item else { + throw StructuredHeaderError.invalidTypeForItem + } + + return T(decimal) + } + + private func _decodeFixedWidthInteger(_ type: T.Type) throws -> T { + guard case .integer(let int) = self.item else { + throw StructuredHeaderError.invalidTypeForItem + } + + guard let result = T(exactly: int) else { + throw StructuredHeaderError.integerOutOfRange + } + + return result + } +} diff --git a/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift b/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift new file mode 100644 index 0000000..07c8970 --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/DictionaryKeyedContainer.swift @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// 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 DictionaryKeyedContainer where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var dictionary: OrderedMap> + + private var decoder: _StructuredFieldDecoder + + init(_ dictionary: OrderedMap>, decoder: _StructuredFieldDecoder) { + self.dictionary = dictionary + self.decoder = decoder + } +} + +extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol { + var codingPath: [CodingKey] { + return self.decoder.codingPath + } + + var allKeys: [Key] { + return self.dictionary.compactMap { Key(stringValue: String(decoding: $0.0, as: UTF8.self)) } + } + + func contains(_ key: Key) -> Bool { + return self.dictionary.contains(where: { $0.0.elementsEqual(key.stringValue.utf8) }) + } + + func decodeNil(forKey key: Key) throws -> Bool { + // We will decode nil if the key is not present. + return !self.contains(key) + } + + func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try type.init(from: self.decoder) + } + + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.container(keyedBy: type) + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.unkeyedContainer() + } + + func superDecoder() throws -> Decoder { + // Dictionary headers never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } + + func superDecoder(forKey key: Key) throws -> Decoder { + // Dictionary headers never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } +} diff --git a/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift b/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift new file mode 100644 index 0000000..1cad401 --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/KeyedInnerListDecoder.swift @@ -0,0 +1,82 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +private let keyedInnerListDecoderSupportedKeys = ["items", "parameters"] + +/// Used when someone has requested a keyed decoder for a property of inner list type. +/// +/// There are only two valid keys for this: "items" and "parameters". +struct KeyedInnerListDecoder where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var innerList: InnerList + + private var decoder: _StructuredFieldDecoder + + init(_ innerList: InnerList, decoder: _StructuredFieldDecoder) { + self.innerList = innerList + self.decoder = decoder + } +} + +extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol { + var codingPath: [CodingKey] { + return self.decoder.codingPath + } + + var allKeys: [Key] { + return keyedInnerListDecoderSupportedKeys.compactMap { Key(stringValue: $0) } + } + + func contains(_ key: Key) -> Bool { + return keyedInnerListDecoderSupportedKeys.contains(key.stringValue) + } + + func decodeNil(forKey key: Key) throws -> Bool { + // Keys are never nil for this type. + return false + } + + func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try type.init(from: self.decoder) + } + + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.container(keyedBy: type) + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.unkeyedContainer() + } + + func superDecoder() throws -> Decoder { + // Items never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } + + func superDecoder(forKey key: Key) throws -> Decoder { + // Items never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } +} diff --git a/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift b/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift new file mode 100644 index 0000000..1a93bed --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/KeyedItemDecoder.swift @@ -0,0 +1,82 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +private let keyedItemDecoderSupportedKeys = ["item", "parameters"] + +/// Used when someone has requested a keyed decoder for a property of item type. +/// +/// There are only two valid keys for this: "item" and "parameters". +struct KeyedItemDecoder where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var item: Item + + private var decoder: _StructuredFieldDecoder + + init(_ item: Item, decoder: _StructuredFieldDecoder) { + self.item = item + self.decoder = decoder + } +} + +extension KeyedItemDecoder: KeyedDecodingContainerProtocol { + var codingPath: [CodingKey] { + return self.decoder.codingPath + } + + var allKeys: [Key] { + return keyedItemDecoderSupportedKeys.compactMap { Key(stringValue: $0) } + } + + func contains(_ key: Key) -> Bool { + return keyedItemDecoderSupportedKeys.contains(key.stringValue) + } + + func decodeNil(forKey key: Key) throws -> Bool { + // Keys are never nil for this type. + return false + } + + func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try type.init(from: self.decoder) + } + + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.container(keyedBy: type) + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.unkeyedContainer() + } + + func superDecoder() throws -> Decoder { + // Items never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } + + func superDecoder(forKey key: Key) throws -> Decoder { + // Items never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } +} diff --git a/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift b/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift new file mode 100644 index 0000000..be62256 --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/ParametersDecoder.swift @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// 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 ParametersDecoder where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var parameters: OrderedMap> + + private var decoder: _StructuredFieldDecoder + + init(_ parameters: OrderedMap>, decoder: _StructuredFieldDecoder) { + self.parameters = parameters + self.decoder = decoder + } +} + +extension ParametersDecoder: KeyedDecodingContainerProtocol { + var codingPath: [CodingKey] { + return self.decoder.codingPath + } + + var allKeys: [Key] { + return self.parameters.compactMap { Key(stringValue: String(decoding: $0.0, as: UTF8.self)) } + } + + func contains(_ key: Key) -> Bool { + return self.parameters.contains(where: { $0.0.elementsEqual(key.stringValue.utf8) }) + } + + func decodeNil(forKey key: Key) throws -> Bool { + // We will decode nil if the key is not present. + return !self.contains(key) + } + + func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try type.init(from: self.decoder) + } + + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.container(keyedBy: type) + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { + try self.decoder.push(_StructuredHeaderCodingKey(key)) + defer { + self.decoder.pop() + } + return try self.decoder.unkeyedContainer() + } + + func superDecoder() throws -> Decoder { + // Parameters never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } + + func superDecoder(forKey key: Key) throws -> Decoder { + // Parameters never support inherited types. + throw StructuredHeaderError.invalidTypeForItem + } +} diff --git a/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift b/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift new file mode 100644 index 0000000..bccb995 --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/StructuredFieldDecoder.swift @@ -0,0 +1,221 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +public struct StructuredFieldDecoder { + public init() { } +} + +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) + return try type.init(from: decoder) + } +} + +class _StructuredFieldDecoder where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { + private var parser: StructuredFieldParser + + // For now we use a stack here because the CoW operations on Array would stuck. Ideally I'd just have us decode + // our way down with values, but doing that is a CoWy nightmare from which we cannot escape. + private var _codingStack: [CodingStackEntry] + + init(_ parser: StructuredFieldParser) { + self.parser = parser + self._codingStack = [] + } +} + +extension _StructuredFieldDecoder: Decoder { + var codingPath: [CodingKey] { + return self._codingStack.map { $0.key as CodingKey } + } + + var userInfo: [CodingUserInfoKey : Any] { + [:] + } + + func push(_ codingKey: _StructuredHeaderCodingKey) throws { + // This force-unwrap is safe: we cannot create containers without having first + // produced the base element, which will always be present. + let nextElement = try self.currentElement!.innerElement(for: codingKey) + self._codingStack.append(CodingStackEntry(key: codingKey, element: nextElement)) + } + + func pop() { + self._codingStack.removeLast() + } + + 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))) + } + + switch self.currentElement! { + case .dictionary(let dictionary): + return KeyedDecodingContainer(DictionaryKeyedContainer(dictionary, decoder: self)) + case .item(let item): + return KeyedDecodingContainer(KeyedItemDecoder(item, decoder: self)) + case .innerList(let innerList): + return KeyedDecodingContainer(KeyedInnerListDecoder(innerList, decoder: self)) + case .parameters(let parameters): + return KeyedDecodingContainer(ParametersDecoder(parameters, decoder: self)) + case .bareItem, .bareInnerList, .list: + // No keyed container for these types. + throw StructuredHeaderError.invalidTypeForItem + } + } + + 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))) + } + + // We have unkeyed containers for lists, inner lists, and bare inner lists. + switch self.currentElement! { + case .list(let items): + fatalError("Not yet implemented") + case .innerList(let innerList): + return BareInnerListDecoder(innerList.bareInnerList, decoder: self) + case .bareInnerList(let bareInnerList): + return BareInnerListDecoder(bareInnerList, decoder: self) + case .dictionary, .item, .bareItem, .parameters: + // No unkeyed container for these types. + throw StructuredHeaderError.invalidTypeForItem + } + } + + 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))) + } + + // We have single value containers for items and bareItems. + switch self.currentElement! { + case .item(let item): + return BareItemDecoder(item.bareItem, codingPath: self._codingStack.map { $0.key }) + case .bareItem(let bareItem): + return BareItemDecoder(bareItem, codingPath: self._codingStack.map { $0.key }) + case .dictionary, .list, .innerList, .bareInnerList, .parameters: + throw StructuredHeaderError.invalidTypeForItem + } + } +} + +extension _StructuredFieldDecoder { + /// The basic elements that make up a Structured Header + fileprivate enum Element { + case dictionary(OrderedMap>) + case list([ItemOrInnerList]) + case item(Item) + case innerList(InnerList) + case bareItem(BareItem) + case bareInnerList(BareInnerList) + case parameters(OrderedMap>) + + func innerElement(for key: _StructuredHeaderCodingKey) throws -> Element { + switch self { + case .dictionary(let dictionary): + guard let element = dictionary.first(where: { $0.0.elementsEqual(key.stringValue.utf8) }) else { + throw StructuredHeaderError.invalidTypeForItem + } + switch element.1 { + case .item(let item): + return .item(item) + case .innerList(let innerList): + return .innerList(innerList) + } + case .list(let list): + guard let offset = key.intValue, offset < list.count else { + throw StructuredHeaderError.invalidTypeForItem + } + let index = list.index(list.startIndex, offsetBy: offset) + switch list[index] { + case .item(let item): + return .item(item) + case .innerList(let innerList): + return .innerList(innerList) + } + case .item(let item): + // Two keys, "item" and "parameters". + switch key.stringValue { + case "item": + return .bareItem(item.bareItem) + case "parameters": + return .parameters(item.parameters) + default: + throw StructuredHeaderError.invalidTypeForItem + } + case .innerList(let innerList): + // Quick check: is this an integer key? If it is, treat this like a bare inner list. Otherwise + // there are two string keys: "items" and "parameters" + if key.intValue != nil { + return try Element.bareInnerList(innerList.bareInnerList).innerElement(for: key) + } + + switch key.stringValue { + case "items": + return .bareInnerList(innerList.bareInnerList) + case "parameters": + return .parameters(innerList.parameters) + default: + throw StructuredHeaderError.invalidTypeForItem + } + case .bareItem: + // Bare items may never be parsed through. + throw StructuredHeaderError.invalidTypeForItem + case .bareInnerList(let innerList): + guard let offset = key.intValue, offset < innerList.count else { + throw StructuredHeaderError.invalidTypeForItem + } + let index = innerList.index(innerList.startIndex, offsetBy: offset) + return .item(innerList[index]) + case .parameters(let params): + guard let element = params.first(where: { $0.0.elementsEqual(key.stringValue.utf8) }) else { + throw StructuredHeaderError.invalidTypeForItem + } + return .bareItem(element.1) + } + } + } +} + +extension _StructuredFieldDecoder { + /// An entry in the coding stack for _StructuredFieldDecoder. + /// + /// This is used to keep track of where we are in the decode. + private struct CodingStackEntry { + var key: _StructuredHeaderCodingKey + var element: Element + } + + /// The element at the current head of the coding stack. + private var currentElement: Element? { + return self._codingStack.last.map { $0.element } + } +} diff --git a/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift b/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift new file mode 100644 index 0000000..7bdc75b --- /dev/null +++ b/Sources/StructuredHeaders/Decoder/StructuredHeaderCodingKey.swift @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// 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 _StructuredHeaderCodingKey : CodingKey { + var stringValue: String + var intValue: Int? + + init(stringValue: String) { + self.stringValue = stringValue + self.intValue = nil + } + + init(intValue: Int) { + self.stringValue = "\(intValue)" + self.intValue = intValue + } + + init(_ key: Key) { + self.stringValue = key.stringValue + self.intValue = key.intValue + } +} diff --git a/Sources/StructuredHeaders/Errors.swift b/Sources/StructuredHeaders/Errors.swift index 3e92de7..f15e4a9 100644 --- a/Sources/StructuredHeaders/Errors.swift +++ b/Sources/StructuredHeaders/Errors.swift @@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// -public struct StructuredHeaderParsingError: Error { +public struct StructuredHeaderError: Error { private enum _BaseError: Hashable { case invalidTrailingBytes case invalidInnerList @@ -25,6 +25,10 @@ public struct StructuredHeaderParsingError: Error { case invalidToken case invalidList case invalidDictionary + case missingKey + case invalidTypeForItem + case integerOutOfRange + case indexOutOfRange } private var base: _BaseError @@ -34,23 +38,27 @@ public struct StructuredHeaderParsingError: Error { } } -extension StructuredHeaderParsingError { - public static let invalidTrailingBytes = StructuredHeaderParsingError(.invalidTrailingBytes) - public static let invalidInnerList = StructuredHeaderParsingError(.invalidInnerList) - public static let invalidItem = StructuredHeaderParsingError(.invalidItem) - public static let invalidKey = StructuredHeaderParsingError(.invalidKey) - public static let invalidIntegerOrDecimal = StructuredHeaderParsingError(.invalidIntegerOrDecimal) - public static let invalidString = StructuredHeaderParsingError(.invalidString) - public static let invalidByteSequence = StructuredHeaderParsingError(.invalidByteSequence) - public static let invalidBoolean = StructuredHeaderParsingError(.invalidBoolean) - public static let invalidToken = StructuredHeaderParsingError(.invalidToken) - public static let invalidList = StructuredHeaderParsingError(.invalidList) - public static let invalidDictionary = StructuredHeaderParsingError(.invalidDictionary) +extension StructuredHeaderError { + public static let invalidTrailingBytes = StructuredHeaderError(.invalidTrailingBytes) + public static let invalidInnerList = StructuredHeaderError(.invalidInnerList) + public static let invalidItem = StructuredHeaderError(.invalidItem) + public static let invalidKey = StructuredHeaderError(.invalidKey) + public static let invalidIntegerOrDecimal = StructuredHeaderError(.invalidIntegerOrDecimal) + public static let invalidString = StructuredHeaderError(.invalidString) + public static let invalidByteSequence = StructuredHeaderError(.invalidByteSequence) + public static let invalidBoolean = StructuredHeaderError(.invalidBoolean) + public static let invalidToken = StructuredHeaderError(.invalidToken) + public static let invalidList = StructuredHeaderError(.invalidList) + public static let invalidDictionary = StructuredHeaderError(.invalidDictionary) + public static let missingKey = StructuredHeaderError(.missingKey) + public static let invalidTypeForItem = StructuredHeaderError(.invalidTypeForItem) + public static let integerOutOfRange = StructuredHeaderError(.integerOutOfRange) + public static let indexOutOfRange = StructuredHeaderError(.indexOutOfRange) } -extension StructuredHeaderParsingError: Hashable { } +extension StructuredHeaderError: Hashable { } -extension StructuredHeaderParsingError: CustomStringConvertible { +extension StructuredHeaderError: CustomStringConvertible { public var description: String { return String(describing: self.base) } diff --git a/Sources/StructuredHeaders/FieldParser.swift b/Sources/StructuredHeaders/FieldParser.swift index b851fb7..ad6ca58 100644 --- a/Sources/StructuredHeaders/FieldParser.swift +++ b/Sources/StructuredHeaders/FieldParser.swift @@ -51,31 +51,31 @@ fileprivate let asciiCapitals = asciiCapitalA...asciiCapitalZ fileprivate let asciiLowercases = asciiLowerA...asciiLowerZ /// A FieldParser is the basic parsing object for structured header fields represented as lists. -struct StructuredFieldParser where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { +public struct StructuredFieldParser where BaseData.Element == UInt8, BaseData.SubSequence: Hashable { // Right now I'm on the fence about whether this should be generic. It's convenient, // and makes it really easy for us to express the parsing over a wide range of data types. // But it risks code size in a really nasty way! We should validate that we don't pay too // much for this flexibility. private var underlyingData: BaseData.SubSequence - init(_ data: BaseData) { + public init(_ data: BaseData) { self.underlyingData = data[...] } } extension StructuredFieldParser { // Helper typealiases to avoid the explosion of generic parameters - typealias BareItem = StructuredHeaders.BareItem - typealias Item = StructuredHeaders.Item - typealias BareInnerList = StructuredHeaders.BareInnerList - typealias InnerList = StructuredHeaders.InnerList - typealias ItemOrInnerList = StructuredHeaders.ItemOrInnerList - typealias Key = BaseData.SubSequence + public typealias BareItem = StructuredHeaders.BareItem + public typealias Item = StructuredHeaders.Item + public typealias BareInnerList = StructuredHeaders.BareInnerList + public typealias InnerList = StructuredHeaders.InnerList + public typealias ItemOrInnerList = StructuredHeaders.ItemOrInnerList + public typealias Key = BaseData.SubSequence /// Parse the HTTP structured field as a list. /// /// This is a straightforward implementation of the parser in the draft spec. - mutating func parseListField() throws -> [ItemOrInnerList] { + public mutating func parseListField() throws -> [ItemOrInnerList] { // Step one, strip leading spaces. self.underlyingData.stripLeadingSpaces() @@ -87,14 +87,14 @@ extension StructuredFieldParser { // The data is _required_ to be empty now, if it isn't we fail. guard self.underlyingData.count == 0 else { - throw StructuredHeaderParsingError.invalidTrailingBytes + throw StructuredHeaderError.invalidTrailingBytes } return members } /// Parse the HTTP structured header field as a dictionary. - mutating func parseDictionaryField() throws -> OrderedMap { + public mutating func parseDictionaryField() throws -> OrderedMap { // Step one, strip leading spaces. self.underlyingData.stripLeadingSpaces() @@ -106,14 +106,14 @@ extension StructuredFieldParser { // The data is _required_ to be empty now, if it isn't we fail. guard self.underlyingData.count == 0 else { - throw StructuredHeaderParsingError.invalidTrailingBytes + throw StructuredHeaderError.invalidTrailingBytes } return map } /// Parse the HTTP structured header field as an item. - mutating func parseItemField() throws -> Item { + public mutating func parseItemField() throws -> Item { // Step one, strip leading spaces. self.underlyingData.stripLeadingSpaces() @@ -125,7 +125,7 @@ extension StructuredFieldParser { // The data is _required_ to be empty now, if it isn't we fail. guard self.underlyingData.count == 0 else { - throw StructuredHeaderParsingError.invalidTrailingBytes + throw StructuredHeaderError.invalidTrailingBytes } return item @@ -145,12 +145,12 @@ extension StructuredFieldParser { // Otherwise, the next character needs to be a comma. guard next == asciiComma else { - throw StructuredHeaderParsingError.invalidList + throw StructuredHeaderError.invalidList } self.underlyingData.stripLeadingOWS() guard self.underlyingData.count > 0 else { // Trailing comma! - throw StructuredHeaderParsingError.invalidList + throw StructuredHeaderError.invalidList } } @@ -177,13 +177,13 @@ extension StructuredFieldParser { break loop } guard next == asciiComma else { - throw StructuredHeaderParsingError.invalidDictionary + throw StructuredHeaderError.invalidDictionary } self.underlyingData.stripLeadingOWS() guard self.underlyingData.count > 0 else { // Trailing comma! - throw StructuredHeaderParsingError.invalidList + throw StructuredHeaderError.invalidList } } @@ -217,12 +217,12 @@ extension StructuredFieldParser { let nextChar = self.underlyingData.first guard nextChar == asciiSpace || nextChar == asciiCloseParenthesis else { - throw StructuredHeaderParsingError.invalidInnerList + throw StructuredHeaderError.invalidInnerList } } // If we got here, we never got the close character for the list. Not good! This is an error. - throw StructuredHeaderParsingError.invalidInnerList + throw StructuredHeaderError.invalidInnerList } private mutating func _parseAnItem() throws -> Item { @@ -233,7 +233,7 @@ extension StructuredFieldParser { private mutating func _parseABareItem() throws -> BareItem { guard let first = self.underlyingData.first else { - throw StructuredHeaderParsingError.invalidItem + throw StructuredHeaderError.invalidItem } switch first { @@ -248,7 +248,7 @@ extension StructuredFieldParser { case asciiCapitals, asciiLowercases, asciiAsterisk: return try self._parseAToken() default: - throw StructuredHeaderParsingError.invalidItem + throw StructuredHeaderError.invalidItem } } @@ -262,7 +262,7 @@ extension StructuredFieldParser { } guard let first = self.underlyingData.first, asciiDigits.contains(first) else { - throw StructuredHeaderParsingError.invalidIntegerOrDecimal + throw StructuredHeaderError.invalidIntegerOrDecimal } var index = self.underlyingData.startIndex @@ -276,7 +276,7 @@ extension StructuredFieldParser { // If input_number contains more than 12 characters, fail parsing. Otherwise, // set type to decimal and consume. if self.underlyingData.distance(from: self.underlyingData.startIndex, to: index) > 12 { - throw StructuredHeaderParsingError.invalidIntegerOrDecimal + throw StructuredHeaderError.invalidIntegerOrDecimal } type = .decimal default: @@ -293,11 +293,11 @@ extension StructuredFieldParser { switch type { case .integer: if count > 15 { - throw StructuredHeaderParsingError.invalidIntegerOrDecimal + throw StructuredHeaderError.invalidIntegerOrDecimal } case .decimal: if count > 16 { - throw StructuredHeaderParsingError.invalidIntegerOrDecimal + throw StructuredHeaderError.invalidIntegerOrDecimal } } } @@ -318,7 +318,7 @@ extension StructuredFieldParser { let periodIndexDistance = integerBytes.distance(from: periodIndex, to: integerBytes.endIndex) if periodIndexDistance == 1 || periodIndexDistance > 4 { // Period may not be last, or have more than three characters after it. - throw StructuredHeaderParsingError.invalidIntegerOrDecimal + throw StructuredHeaderError.invalidIntegerOrDecimal } // Same notes here as above @@ -362,11 +362,11 @@ extension StructuredFieldParser { case asciiBackslash: self.underlyingData.formIndex(after: &index) if index == endIndex { - throw StructuredHeaderParsingError.invalidString + throw StructuredHeaderError.invalidString } let next = self.underlyingData[index] guard next == asciiDquote || next == asciiBackslash else { - throw StructuredHeaderParsingError.invalidString + throw StructuredHeaderError.invalidString } escapes += 1 @@ -376,7 +376,7 @@ extension StructuredFieldParser { break loop case 0x00...0x1f, 0x7f...: // Forbidden bytes in string: string must be VCHAR and SP. - throw StructuredHeaderParsingError.invalidString + throw StructuredHeaderError.invalidString default: // Allowed, unescape, uncontrol byte. () @@ -387,7 +387,7 @@ extension StructuredFieldParser { // Oops, fell off the back of the string. if endIndex == self.underlyingData.endIndex { - throw StructuredHeaderParsingError.invalidString + throw StructuredHeaderError.invalidString } let stringSlice = self.underlyingData[self.underlyingData.startIndex.. BareItem { @@ -445,7 +445,7 @@ extension StructuredFieldParser { return false default: // Whoops! - throw StructuredHeaderParsingError.invalidBoolean + throw StructuredHeaderError.invalidBoolean } } @@ -508,7 +508,7 @@ extension StructuredFieldParser { private mutating func _parseAKey() throws -> BaseData.SubSequence { guard let first = self.underlyingData.first, asciiLowercases.contains(first) || first == asciiAsterisk else { - throw StructuredHeaderParsingError.invalidKey + throw StructuredHeaderError.invalidKey } let key = self.underlyingData.prefix(while: { @@ -524,103 +524,6 @@ extension StructuredFieldParser { } } -enum ItemOrInnerList where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { - case item(Item) - case innerList(InnerList) -} - -enum BareItem where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { - case bool(Bool) - case integer(Int) - case decimal(Float64) // Not great, can we do better? - case string(String) - case undecodedByteSequence(BaseData) - case token(BaseData) -} - -extension BareItem: ExpressibleByBooleanLiteral { - init(booleanLiteral value: Bool) { - self = .bool(value) - } -} - -extension BareItem: Hashable { } - -struct Item where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { - var bareItem: BareItem - var parameters: OrderedMap> -} - -extension Item: Hashable { } - -struct BareInnerList: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { - private var items: [Item] - - init() { - self.items = [] - } - - fileprivate mutating func append(_ item: Item) { - self.items.append(item) - } -} - -extension BareInnerList: RandomAccessCollection, MutableCollection { - struct Index { - fileprivate var baseIndex: Array>.Index - - init(_ baseIndex: Array>.Index) { - self.baseIndex = baseIndex - } - } - - var count: Int { - return self.items.count - } - - var startIndex: Index { - return Index(self.items.startIndex) - } - - var endIndex: Index { - return Index(self.items.endIndex) - } - - func index(after i: Index) -> Index { - return Index(self.items.index(after: i.baseIndex)) - } - - func index(before i: Index) -> Index { - return Index(self.items.index(before: i.baseIndex)) - } - - func index(_ i: Index, offsetBy offset: Int) -> Index { - return Index(self.items.index(i.baseIndex, offsetBy: offset)) - } - - subscript(index: Index) -> Item { - get { - return self.items[index.baseIndex] - } - set { - self.items[index.baseIndex] = newValue - } - } -} - -extension BareInnerList.Index: Hashable { } - -extension BareInnerList.Index: Comparable { - static func <(lhs: Self, rhs: Self) -> Bool { - return lhs.baseIndex < rhs.baseIndex - } -} - -struct InnerList: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable { - var bareInnerList: BareInnerList - var parameters: OrderedMap> -} - fileprivate enum IntegerOrDecimal { case integer case decimal diff --git a/Sources/StructuredHeaders/OrderedMap.swift b/Sources/StructuredHeaders/OrderedMap.swift index 43895ac..0aac68c 100644 --- a/Sources/StructuredHeaders/OrderedMap.swift +++ b/Sources/StructuredHeaders/OrderedMap.swift @@ -19,17 +19,17 @@ /// maps in structured headers are small (fewer than 20 elements), and so the /// distinction between hashing and linear search is not really a concern. However, for /// future implementation flexibility, we continue to require that keys be hashable. -struct OrderedMap where Key: Hashable { +public struct OrderedMap where Key: Hashable { private var backing: [Entry] - init() { + public init() { self.backing = [] } /// Look up the value for a given key. /// /// Warning! Unlike a regular dictionary, we do not promise this will be O(1)! - subscript(key: Key) -> Value? { + public subscript(key: Key) -> Value? { get { return self.backing.first(where: { $0.key == key }).map { $0.value } } @@ -61,7 +61,7 @@ extension OrderedMap { // MARK:- Collection conformances extension OrderedMap: RandomAccessCollection, MutableCollection { - struct Index { + public struct Index { fileprivate var baseIndex: Array<(Key, Value)>.Index fileprivate init(_ baseIndex: Array<(Key, Value)>.Index) { @@ -69,19 +69,19 @@ extension OrderedMap: RandomAccessCollection, MutableCollection { } } - var startIndex: Index { + public var startIndex: Index { return Index(self.backing.startIndex) } - var endIndex: Index { + public var endIndex: Index { return Index(self.backing.endIndex) } - var count: Int { + public var count: Int { return self.backing.count } - subscript(position: Index) -> (Key, Value) { + public subscript(position: Index) -> (Key, Value) { get { let element = self.backing[position.baseIndex] return (element.key, element.value) @@ -91,15 +91,15 @@ extension OrderedMap: RandomAccessCollection, MutableCollection { } } - func index(_ i: Index, offsetBy distance: Int) -> Index { + public func index(_ i: Index, offsetBy distance: Int) -> Index { return Index(self.backing.index(i.baseIndex, offsetBy: distance)) } - func index(after i: Index) -> Index { + public func index(after i: Index) -> Index { return self.index(i, offsetBy: 1) } - func index(before i: Index) -> Index { + public func index(before i: Index) -> Index { return self.index(i, offsetBy: -1) } } @@ -107,30 +107,30 @@ extension OrderedMap: RandomAccessCollection, MutableCollection { extension OrderedMap.Index: Hashable { } extension OrderedMap.Index: Comparable { - static func < (lhs: Self, rhs: Self) -> Bool { + public static func < (lhs: Self, rhs: Self) -> Bool { return lhs.baseIndex < rhs.baseIndex } } extension OrderedMap.Index: Strideable { - func advanced(by n: Int) -> Self { + public func advanced(by n: Int) -> Self { return Self(self.baseIndex.advanced(by: n)) } - func distance(to other: Self) -> Int { + public func distance(to other: Self) -> Int { return self.baseIndex.distance(to: other.baseIndex) } } // MARK:- Helper conformances extension OrderedMap: ExpressibleByDictionaryLiteral { - init(dictionaryLiteral elements: (Key, Value)...) { + public init(dictionaryLiteral elements: (Key, Value)...) { self.backing = elements.map { Entry(key: $0.0, value: $0.1) } } } extension OrderedMap: CustomDebugStringConvertible { - var debugDescription: String { + public var debugDescription: String { let backingRepresentation = self.backing.map { "\($0.key): \($0.value)" }.joined(separator: ", ") return "[\(backingRepresentation)]" } diff --git a/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift new file mode 100644 index 0000000..88906d8 --- /dev/null +++ b/Tests/StructuredHeadersTests/StructuredFieldDecoderTests.swift @@ -0,0 +1,124 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +import Foundation +import XCTest +import StructuredHeaders + +struct ListyDictionaryFieldParameters: Codable, Equatable { + var q: Double? + var fallback: String? +} + +struct ListyDictionaryParameterisedString: Codable, Equatable { + var item: String + var parameters: ListyDictionaryFieldParameters +} + +struct ListyDictionaryParameterisedList: Codable, Equatable { + var items: [ListyDictionaryParameterisedString] + var parameters: ListyDictionaryFieldParameters +} + + +/// An example ListyDictionary structured header field. +/// +/// An example of this field is: 'primary=bar;q=1.0, secondary=baz;q=0.5;fallback=last, acceptablejurisdictions=(AU;q=1.0 GB;q=0.9 FR);fallback=primary' +struct ListyDictionaryField: Codable, Equatable { + var primary: ListyDictionaryParameterisedString + var secondary: ListyDictionaryParameterisedString + var acceptablejurisdictions: ListyDictionaryParameterisedList +} + +final class StructuredFieldDecoderTests: XCTestCase { + func testSimpleCodableDecode() throws { + let headerField = "primary=bar;q=1.0, secondary=baz;q=0.5;fallback=last, acceptablejurisdictions=(AU;q=1.0 GB;q=0.9 FR);fallback=\"primary\"" + let parsed = try StructuredFieldDecoder().decode(ListyDictionaryField.self, from: Array(headerField.utf8)) + let expected = ListyDictionaryField( + primary: .init(item: "bar", parameters: .init(q: 1, fallback: nil)), + secondary: .init(item: "baz", parameters: .init(q: 0.5, fallback: "last")), + acceptablejurisdictions: .init(items: [.init(item: "AU", parameters: .init(q: 1, fallback: nil)), .init(item: "GB", parameters: .init(q: 0.9, fallback: nil)), .init(item: "FR", parameters: .init(q: nil, fallback: nil))], parameters: .init(q: nil, fallback: "primary")) + ) + XCTAssertEqual(parsed, expected) + } + + func testCanDecodeParameterisedItemsWithoutParameters() throws { + struct ListyDictionaryNoParams: Codable, Equatable { + var primary: String + var secondary: String + var acceptablejurisdictions: [String] + } + let headerField = "primary=bar;q=1.0, secondary=baz;q=0.5;fallback=last, acceptablejurisdictions=(AU;q=1.0 GB;q=0.9 FR);fallback=\"primary\"" + let parsed = try StructuredFieldDecoder().decode(ListyDictionaryNoParams.self, from: Array(headerField.utf8)) + let expected = ListyDictionaryNoParams(primary: "bar", secondary: "baz", acceptablejurisdictions: ["AU", "GB", "FR"]) + XCTAssertEqual(parsed, expected) + } + + func testCanDecodeIntegersInVariousWays() throws { + let headerField = "5;bar=baz" + + XCTAssertEqual(UInt8(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(Int8(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(UInt16(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(Int16(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(UInt32(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(Int32(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(UInt64(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(Int64(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(UInt(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(Int(5), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + } + + func testOutOfRangeNumbersAreReported() throws { + // Most-negative supported integer value is -999,999,999,999,999. This will fit into a + // 64-bit integer, but no other integer type. Let's validate that this throws errors + // rather than crashing for all non-Int64 types. (Ignoring Int/UInt due to their platform + // dependence) + let headerField = "-999999999999999;bar=baz" + let expected = Int64(-999999999999999) + + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int8.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt8.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int16.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt16.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int32.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt32.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt64.self, from: Array(headerField.utf8))) + XCTAssertEqual(expected, try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + } + + func testDoubleAndFloatInterchangeable() throws { + let headerField = "5.0;bar=baz" + + XCTAssertEqual(Float(5.0), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + XCTAssertEqual(Double(5.0), try StructuredFieldDecoder().decode(from: Array(headerField.utf8))) + } + + func testAskingForTheWrongType() throws { + let headerField = "gzip" + let intField = "5" + + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int8.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt8.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int16.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt16.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int32.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt32.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int64.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt64.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Double.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Float.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(Bool.self, from: Array(headerField.utf8))) + XCTAssertThrowsError(try StructuredFieldDecoder().decode(String.self, from: Array(intField.utf8))) + } +} diff --git a/Tests/StructuredHeadersTests/StructuredHeadersTests.swift b/Tests/StructuredHeadersTests/StructuredHeadersTests.swift index a07a3fa..65320ca 100644 --- a/Tests/StructuredHeadersTests/StructuredHeadersTests.swift +++ b/Tests/StructuredHeadersTests/StructuredHeadersTests.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import Foundation import XCTest -@testable import StructuredHeaders +import StructuredHeaders enum FixtureTestError: Error { case base64DecodingFailed