Rename a number of types and modules. (#13)

Motivation:

In general we should try to be specific about what we're referring to.
"Structured headers" is not really an accurate description of what this
module works with: "Structured Header Field Values", or "Structured
Field Value" is usually better. To that end this change adjusts our
naming to be closer to what we want. It also changes our module names to
prioritise the use of the Codable-based one.

Modifications:

- Renamed CodableStructuredHeaders to StructuredFieldValues.
- Renamed StructuredHeaders to RawStructuredFieldValues.
- Renamed a number of types from Field to FieldValue.
- Renamed a number of types from Header to Field or FieldValue.
- Renamed some functions along the above lines.

Result:

Better and more consistent terminology will be used.
This commit is contained in:
Cory Benfield authored and GitHub committed 2021-07-02 11:48:41 +01:00
1 parent f881e6c41b
commit 27e163f96a
31 files changed
+313 -313

No files matched your search

@@ -0,0 +1,119 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
struct BareInnerListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var list: BareInnerList
private var currentOffset: Int
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ list: BareInnerList, decoder: _StructuredFieldDecoder<BaseData>) {
self.list = list
self.currentOffset = 0
self.decoder = decoder
}
}
extension BareInnerListDecoder: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var count: Int? {
self.list.count
}
var isAtEnd: Bool {
self.currentOffset == self.list.count
}
var currentIndex: Int {
self.currentOffset
}
mutating func decodeNil() throws -> Bool {
// We never decode nil.
false
}
mutating func decode<T>(_ 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()
}
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)
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> 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
}
}
@@ -0,0 +1,186 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
struct BareItemDecoder {
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] {
self._codingPath as [CodingKey]
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int8.Type) throws -> Int8 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int16.Type) throws -> Int16 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int32.Type) throws -> Int32 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int64.Type) throws -> Int64 {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt.Type) throws -> UInt {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int.Type) throws -> Int {
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Float.Type) throws -> Float {
try self._decodeBinaryFloatingPoint(type)
}
func decode(_ type: Double.Type) throws -> Double {
try self._decodeBinaryFloatingPoint(type)
}
func decode(_: String.Type) throws -> String {
switch self.item {
case .string(let string):
return string
case .token(let token):
return token
default:
throw StructuredHeaderError.invalidTypeForItem
}
}
func decode(_: Bool.Type) throws -> Bool {
guard case .bool(let bool) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
return bool
}
func decode(_: Data.Type) throws -> Data {
guard case .undecodedByteSequence(let data) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
guard let decoded = Data(base64Encoded: data) else {
throw StructuredHeaderError.invalidByteSequence
}
return decoded
}
func decode(_: 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.
false
}
func decode<T>(_ 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
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:
throw StructuredHeaderError.invalidTypeForItem
}
}
private func _decodeBinaryFloatingPoint<T: BinaryFloatingPoint>(_: T.Type) throws -> T {
guard case .decimal(let decimal) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
// Going via Double is a bit sad. Swift Numerics would help here.
return T(Double(decimal))
}
private func _decodeFixedWidthInteger<T: FixedWidthInteger>(_: 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
}
}
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
struct DictionaryKeyedContainer<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var dictionary: OrderedMap<String, ItemOrInnerList>
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ dictionary: OrderedMap<String, ItemOrInnerList>, decoder: _StructuredFieldDecoder<BaseData>) {
self.dictionary = dictionary
self.decoder = decoder
}
}
extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var allKeys: [Key] {
self.dictionary.compactMap { Key(stringValue: $0.0) }
}
func contains(_ key: Key) -> Bool {
self.dictionary.contains(where: { $0.0 == key.stringValue })
}
func decodeNil(forKey key: Key) throws -> Bool {
// We will decode nil if the key is not present.
!self.contains(key)
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
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)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
return try self.decoder.container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
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
}
}
@@ -0,0 +1,93 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
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<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var innerList: InnerList
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ innerList: InnerList, decoder: _StructuredFieldDecoder<BaseData>) {
self.innerList = innerList
self.decoder = decoder
}
}
extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var allKeys: [Key] {
keyedInnerListDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
keyedInnerListDecoderSupportedKeys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
// Keys are never nil for this type.
false
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
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)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
return try self.decoder.container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
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
}
}
@@ -0,0 +1,93 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
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<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var item: Item
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ item: Item, decoder: _StructuredFieldDecoder<BaseData>) {
self.item = item
self.decoder = decoder
}
}
extension KeyedItemDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var allKeys: [Key] {
keyedItemDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
keyedItemDecoderSupportedKeys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
// Keys are never nil for this type.
false
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
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)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
return try self.decoder.container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
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
}
}
@@ -0,0 +1,93 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
private let keyedTopLevelListDecoderSupportedKeys = ["items"]
/// Used when someone has requested a keyed decoder for a property of list type.
///
/// There is only one valid key for this: "items".
struct KeyedTopLevelListDecoder<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var list: [ItemOrInnerList]
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ list: [ItemOrInnerList], decoder: _StructuredFieldDecoder<BaseData>) {
self.list = list
self.decoder = decoder
}
}
extension KeyedTopLevelListDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var allKeys: [Key] {
keyedTopLevelListDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
keyedTopLevelListDecoderSupportedKeys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
// Keys are never nil for this type.
false
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
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)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
return try self.decoder.container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
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
}
}
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
struct ParametersDecoder<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var parameters: OrderedMap<String, BareItem>
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ parameters: OrderedMap<String, BareItem>, decoder: _StructuredFieldDecoder<BaseData>) {
self.parameters = parameters
self.decoder = decoder
}
}
extension ParametersDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var allKeys: [Key] {
self.parameters.compactMap { Key(stringValue: $0.0) }
}
func contains(_ key: Key) -> Bool {
self.parameters.contains(where: { $0.0 == key.stringValue })
}
func decodeNil(forKey key: Key) throws -> Bool {
// We will decode nil if the key is not present.
!self.contains(key)
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
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)
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
return try self.decoder.container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
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
}
}
@@ -0,0 +1,319 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
/// A `StructuredFieldValueDecoder` allows decoding `Decodable` objects from a HTTP
/// structured header field.
public struct StructuredFieldValueDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
public var keyDecodingStrategy: KeyDecodingStrategy?
public init() {}
}
extension StructuredFieldValueDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
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 StructuredFieldValueDecoder {
/// Attempt to decode an object from a structured header field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
public func decode<StructuredField: StructuredFieldValue, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8 {
switch StructuredField.structuredFieldType {
case .item:
return try self.decodeItemField(from: data)
case .list:
return try self.decodeListField(from: data)
case .dictionary:
return try self.decodeDictionaryField(from: data)
}
}
/// Attempt to decode an object from a structured header dictionary field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
private func decodeDictionaryField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8 {
let parser = StructuredFieldValueParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseDictionaryField()
return try type.init(from: decoder)
}
/// Attempt to decode an object from a structured header list field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
private func decodeListField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8 {
let parser = StructuredFieldValueParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseListField()
return try type.init(from: decoder)
}
/// Attempt to decode an object from a structured header item field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
private func decodeItemField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8 {
let parser = StructuredFieldValueParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseItemField()
// An escape hatch here for top-level data: if we don't do this, it'll ask for
// an unkeyed container and get very confused.
if type is Data.Type {
let container = try decoder.singleValueContainer()
return try container.decode(Data.self) as! StructuredField
} else 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)
}
}
}
class _StructuredFieldDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var parser: StructuredFieldValueParser<BaseData>
// For now we use a stack here because the CoW operations on Array would suck. 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]
var keyDecodingStrategy: StructuredFieldValueDecoder.KeyDecodingStrategy?
init(_ parser: StructuredFieldValueParser<BaseData>, keyDecodingStrategy: StructuredFieldValueDecoder.KeyDecodingStrategy?) {
self.parser = parser
self._codingStack = []
self.keyDecodingStrategy = keyDecodingStrategy
}
}
extension _StructuredFieldDecoder: Decoder {
var codingPath: [CodingKey] {
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<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
switch self.currentElement! {
case .dictionary(let dictionary):
return KeyedDecodingContainer(DictionaryKeyedContainer(dictionary, decoder: self))
case .item(let item):
return KeyedDecodingContainer(KeyedItemDecoder(item, decoder: self))
case .list(let list):
return KeyedDecodingContainer(KeyedTopLevelListDecoder(list, 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:
// No keyed container for these types.
throw StructuredHeaderError.invalidTypeForItem
}
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
// We have unkeyed containers for lists, inner lists, and bare inner lists.
switch self.currentElement! {
case .list(let items):
return TopLevelListDecoder(items, decoder: self)
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 {
// 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
}
}
func parseDictionaryField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseDictionaryFieldValue()
// 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.parseListFieldValue()
// 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.parseItemFieldValue()
// 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 {
/// The basic elements that make up a Structured Header
fileprivate enum Element {
case dictionary(OrderedMap<String, ItemOrInnerList>)
case list([ItemOrInnerList])
case item(Item)
case innerList(InnerList)
case bareItem(BareItem)
case bareInnerList(BareInnerList)
case parameters(OrderedMap<String, BareItem>)
func innerElement(for key: _StructuredHeaderCodingKey) throws -> Element {
switch self {
case .dictionary(let dictionary):
guard let element = dictionary.first(where: { $0.0 == key.stringValue }) 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):
if let offset = key.intValue {
guard 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)
}
} else if key.stringValue == "items" {
// Oh, the outer layer is keyed. That's fine, just put ourselves
// back on the stack.
return .list(list)
} else {
throw StructuredHeaderError.invalidTypeForItem
}
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 == key.stringValue }) 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? {
self._codingStack.last.map { $0.element }
}
}
@@ -0,0 +1,42 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
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: CodingKey>(_ key: Key, keyDecodingStrategy: StructuredFieldValueDecoder.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
}
}
@@ -0,0 +1,119 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
struct TopLevelListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var list: [ItemOrInnerList]
private var currentOffset: Int
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ list: [ItemOrInnerList], decoder: _StructuredFieldDecoder<BaseData>) {
self.list = list
self.currentOffset = 0
self.decoder = decoder
}
}
extension TopLevelListDecoder: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
self.decoder.codingPath
}
var count: Int? {
self.list.count
}
var isAtEnd: Bool {
self.currentOffset == self.list.count
}
var currentIndex: Int {
self.currentOffset
}
mutating func decodeNil() throws -> Bool {
// We never decode nil.
false
}
mutating func decode<T>(_ 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()
}
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)
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> 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
}
}
@@ -0,0 +1,111 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
/// This object translates between the keys used by the encoder and the keys used by the encoding object.
///
/// All methods here call back to similar methods on the encoder.
struct StructuredFieldKeyedEncodingContainer<Key: CodingKey> {
private var encoder: _StructuredFieldEncoder
init(encoder: _StructuredFieldEncoder) {
self.encoder = encoder
}
}
extension StructuredFieldKeyedEncodingContainer: KeyedEncodingContainerProtocol {
var codingPath: [CodingKey] {
self.encoder.codingPath
}
mutating func encodeNil(forKey key: Key) throws {
// Nil has no representation in structured headers
}
mutating func encode(_ value: Bool, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: String, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Double, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Float, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Int, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Int8, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Int16, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Int32, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: Int64, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: UInt, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: UInt8, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: UInt16, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: UInt32, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode(_ value: UInt64, forKey key: Key) throws {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
return self.encoder.container(keyedBy: keyType)
}
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
self.encoder.unkeyedContainer()
}
mutating func superEncoder() -> Encoder {
self.encoder
}
mutating func superEncoder(forKey key: Key) -> Encoder {
self.encoder
}
}
@@ -0,0 +1,111 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
/// This object translates between the unkeyed coding API and methods on the encoder.
///
/// All methods here call back to similar methods on the encoder.
struct StructuredFieldUnkeyedEncodingContainer {
private var encoder: _StructuredFieldEncoder
init(encoder: _StructuredFieldEncoder) {
self.encoder = encoder
}
}
extension StructuredFieldUnkeyedEncodingContainer: UnkeyedEncodingContainer {
var codingPath: [CodingKey] {
self.encoder.codingPath
}
var count: Int {
self.encoder.count
}
func encodeNil() throws {
try self.encoder.appendNil()
}
func encode(_ value: Bool) throws {
try self.encoder.append(value)
}
func encode(_ value: String) throws {
try self.encoder.append(value)
}
func encode(_ value: Double) throws {
try self.encoder.append(value)
}
func encode(_ value: Float) throws {
try self.encoder.append(value)
}
func encode(_ value: Int) throws {
try self.encoder.append(value)
}
func encode(_ value: Int8) throws {
try self.encoder.append(value)
}
func encode(_ value: Int16) throws {
try self.encoder.append(value)
}
func encode(_ value: Int32) throws {
try self.encoder.append(value)
}
func encode(_ value: Int64) throws {
try self.encoder.append(value)
}
func encode(_ value: UInt) throws {
try self.encoder.append(value)
}
func encode(_ value: UInt8) throws {
try self.encoder.append(value)
}
func encode(_ value: UInt16) throws {
try self.encoder.append(value)
}
func encode(_ value: UInt32) throws {
try self.encoder.append(value)
}
func encode(_ value: UInt64) throws {
try self.encoder.append(value)
}
func encode<T>(_ value: T) throws where T: Encodable {
try self.encoder.append(value)
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
return self.encoder.container(keyedBy: keyType)
}
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
self.encoder.unkeyedContainer()
}
mutating func superEncoder() -> Encoder {
self.encoder
}
}
@@ -0,0 +1,931 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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 RawStructuredFieldValues
/// A `StructuredFieldValueEncoder` allows encoding `Encodable` objects to the format of a HTTP
/// structured header field.
public struct StructuredFieldValueEncoder {
public var keyEncodingStrategy: KeyEncodingStrategy?
public init() {}
}
extension StructuredFieldValueEncoder {
/// A strategy that should be used to map coding keys to wire format keys.
public struct KeyEncodingStrategy: Hashable {
fileprivate enum Base: Hashable {
case lowercase
}
fileprivate var base: Base
/// Lowercase all coding keys before encoding them in keyed containers such as
/// dictionaries or parameters.
public static let lowercase = KeyEncodingStrategy(base: .lowercase)
}
}
extension StructuredFieldValueEncoder {
/// Attempt to encode an object into a structured header field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
public func encode<StructuredField: StructuredFieldValue>(_ data: StructuredField) throws -> [UInt8] {
switch StructuredField.structuredFieldType {
case .item:
return try self.encodeItemField(data)
case .list:
return try self.encodeListField(data)
case .dictionary:
return try self.encodeDictionaryField(data)
}
}
/// Attempt to encode an object into a structured header dictionary field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
private func encodeDictionaryField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
let serializer = StructuredFieldValueSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeDictionaryField(data)
}
/// Attempt to encode an object into a structured header list field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
private func encodeListField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
let serializer = StructuredFieldValueSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeListField(data)
}
/// Attempt to encode an object into a structured header item field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
private func encodeItemField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
let serializer = StructuredFieldValueSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeItemField(data)
}
}
class _StructuredFieldEncoder {
private var serializer: StructuredFieldValueSerializer
// 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 _codingPath: [CodingStackEntry]
private var currentStackEntry: CodingStackEntry
internal var keyEncodingStrategy: StructuredFieldValueEncoder.KeyEncodingStrategy?
init(_ serializer: StructuredFieldValueSerializer, keyEncodingStrategy: StructuredFieldValueEncoder.KeyEncodingStrategy?) {
self.serializer = serializer
self._codingPath = []
self.keyEncodingStrategy = keyEncodingStrategy
self.currentStackEntry = CodingStackEntry(key: .init(stringValue: ""), storage: .itemHeader) // This default doesn't matter right now.
}
fileprivate func encodeDictionaryField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
self.push(key: .init(stringValue: ""), newStorage: .dictionaryHeader)
try data.encode(to: self)
switch self.currentStackEntry.storage {
case .dictionary(let map):
return try self.serializer.writeDictionaryFieldValue(map)
case .dictionaryHeader:
// No encoding happened.
return []
case .listHeader, .list, .itemHeader, .item, .bareInnerList, .innerList,
.parameters, .itemOrInnerList:
throw StructuredHeaderError.invalidTypeForItem
}
}
fileprivate func encodeListField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
self.push(key: .init(stringValue: ""), newStorage: .listHeader)
try data.encode(to: self)
switch self.currentStackEntry.storage {
case .list(let list):
return try self.serializer.writeListFieldValue(list)
case .listHeader:
// No encoding happened
return []
case .dictionaryHeader, .dictionary, .itemHeader, .item, .bareInnerList, .innerList,
.parameters, .itemOrInnerList:
throw StructuredHeaderError.invalidTypeForItem
}
}
fileprivate func encodeItemField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
self.push(key: .init(stringValue: ""), newStorage: .itemHeader)
// 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 `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)
}
switch self.currentStackEntry.storage {
case .item(let item):
return try self.serializer.writeItemFieldValue(Item(item))
case .itemHeader:
// No encoding happened
return []
case .dictionaryHeader, .dictionary, .listHeader, .list, .bareInnerList, .innerList,
.parameters, .itemOrInnerList:
throw StructuredHeaderError.invalidTypeForItem
}
}
}
extension _StructuredFieldEncoder: Encoder {
var codingPath: [CodingKey] {
self._codingPath.map { $0.key as CodingKey }
}
var userInfo: [CodingUserInfoKey: Any] {
[:]
}
func push(key: _StructuredHeaderCodingKey, newStorage: NodeType) {
self._codingPath.append(self.currentStackEntry)
self.currentStackEntry = .init(key: key, storage: newStorage)
}
func pop() throws {
// This is called when we've completed the storage in the current container.
// We can pop the value at the base of the stack, then "insert" the current one
// into it, and save the new value as the new current.
let current = self.currentStackEntry
var newCurrent = self._codingPath.removeLast()
try newCurrent.storage.insert(current.storage, atKey: current.key)
self.currentStackEntry = newCurrent
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
return KeyedEncodingContainer(StructuredFieldKeyedEncodingContainer(encoder: self))
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
StructuredFieldUnkeyedEncodingContainer(encoder: self)
}
func singleValueContainer() -> SingleValueEncodingContainer {
self
}
}
extension _StructuredFieldEncoder: SingleValueEncodingContainer {
func encodeNil() throws {
// bare items are never nil.
throw StructuredHeaderError.invalidTypeForItem
}
func encode(_ value: Bool) throws {
try self.currentStackEntry.storage.insertBareItem(.bool(value))
}
func encode(_ value: String) throws {
if value.structuredHeadersIsValidToken {
try self.currentStackEntry.storage.insertBareItem(.token(value))
} else {
try self.currentStackEntry.storage.insertBareItem(.string(value))
}
}
func encode(_ value: Double) throws {
try self._encodeBinaryFloatingPoint(value)
}
func encode(_ value: Float) throws {
try self._encodeBinaryFloatingPoint(value)
}
func encode(_ value: Int) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: Int8) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: Int16) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: Int32) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: Int64) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: UInt) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: UInt8) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: UInt16) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: UInt32) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ value: UInt64) throws {
try self._encodeFixedWidthInteger(value)
}
func encode(_ data: Data) throws {
let encoded = data.base64EncodedString()
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<T>(_ value: T) throws where T: Encodable {
switch value {
case let value as UInt8:
try self.encode(value)
case let value as Int8:
try self.encode(value)
case let value as UInt16:
try self.encode(value)
case let value as Int16:
try self.encode(value)
case let value as UInt32:
try self.encode(value)
case let value as Int32:
try self.encode(value)
case let value as UInt64:
try self.encode(value)
case let value as Int64:
try self.encode(value)
case let value as Int:
try self.encode(value)
case let value as UInt:
try self.encode(value)
case let value as Float:
try self.encode(value)
case let value as Double:
try self.encode(value)
case let value as String:
try self.encode(value)
case let value as Bool:
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
}
}
private func _encodeBinaryFloatingPoint<T: BinaryFloatingPoint>(_ value: T) throws {
// We go via double and encode it as a decimal.
let pseudoDecimal = try PseudoDecimal(Double(value))
try self.currentStackEntry.storage.insertBareItem(.decimal(pseudoDecimal))
}
private func _encodeFixedWidthInteger<T: FixedWidthInteger>(_ value: T) throws {
guard let base = Int(exactly: value) else {
throw StructuredHeaderError.integerOutOfRange
}
try self.currentStackEntry.storage.insertBareItem(.integer(base))
}
}
extension _StructuredFieldEncoder {
// This extension sort-of corresponds to the unkeyed encoding container: all of
// these methods are called from there.
var count: Int {
switch self.currentStackEntry.storage {
case .bareInnerList(let list):
return list.count
case .innerList(let list):
return list.bareInnerList.count
case .itemOrInnerList:
return 0
case .list(let list):
return list.count
case .listHeader:
return 0
case .dictionaryHeader, .dictionary, .itemHeader, .item, .parameters:
fatalError("Cannot have unkeyed container at \(self.currentStackEntry)")
}
}
func appendNil() throws {
// list entries are never nil.
throw StructuredHeaderError.invalidTypeForItem
}
func append(_ value: Bool) throws {
try self.currentStackEntry.storage.appendBareItem(.bool(value))
}
func append(_ value: String) throws {
if value.structuredHeadersIsValidToken {
try self.currentStackEntry.storage.appendBareItem(.token(value))
} else {
try self.currentStackEntry.storage.appendBareItem(.string(value))
}
}
func append(_ value: Double) throws {
try self._appendBinaryFloatingPoint(value)
}
func append(_ value: Float) throws {
try self._appendBinaryFloatingPoint(value)
}
func append(_ value: Int) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: Int8) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: Int16) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: Int32) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: Int64) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: UInt) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: UInt8) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: UInt16) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: UInt32) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: UInt64) throws {
try self._appendFixedWidthInteger(value)
}
func append(_ value: Data) throws {
try self.currentStackEntry.storage.appendBareItem(.undecodedByteSequence(value.base64EncodedString()))
}
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<T>(_ value: T) throws where T: Encodable {
switch value {
case let value as UInt8:
try self.append(value)
case let value as Int8:
try self.append(value)
case let value as UInt16:
try self.append(value)
case let value as Int16:
try self.append(value)
case let value as UInt32:
try self.append(value)
case let value as Int32:
try self.append(value)
case let value as UInt64:
try self.append(value)
case let value as Int64:
try self.append(value)
case let value as Int:
try self.append(value)
case let value as UInt:
try self.append(value)
case let value as Float:
try self.append(value)
case let value as Double:
try self.append(value)
case let value as String:
try self.append(value)
case let value as Bool:
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 {
case .listHeader, .list:
// This may be an item or inner list.
self.push(key: .init(intValue: self.count), newStorage: .itemOrInnerList([:]))
try value.encode(to: self)
try self.pop()
case .itemOrInnerList(let params):
// This is an inner list.
self.currentStackEntry.storage = .innerList(InnerList(bareInnerList: [], parameters: params))
fallthrough
case .innerList, .bareInnerList:
// This may only be an item.
self.push(key: .init(intValue: self.count), newStorage: .item(.init(bareItem: nil, parameters: [:])))
try value.encode(to: self)
try self.pop()
case .dictionaryHeader, .dictionary, .itemHeader, .item, .parameters:
throw StructuredHeaderError.invalidTypeForItem
}
}
}
private func _appendBinaryFloatingPoint<T: BinaryFloatingPoint>(_ value: T) throws {
// We go via double and encode it as a decimal.
let pseudoDecimal = try PseudoDecimal(Double(value))
try self.currentStackEntry.storage.appendBareItem(.decimal(pseudoDecimal))
}
private func _appendFixedWidthInteger<T: FixedWidthInteger>(_ value: T) throws {
guard let base = Int(exactly: value) else {
throw StructuredHeaderError.integerOutOfRange
}
try self.currentStackEntry.storage.appendBareItem(.integer(base))
}
}
extension _StructuredFieldEncoder {
// This extension sort-of corresponds to the keyed encoding container: all of
// these methods are called from there. All our keyed encoding containers use
// string keys.
func encode(_ value: Bool, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self.currentStackEntry.storage.insertBareItem(.bool(value), atKey: key)
}
func encode(_ value: String, forKey key: String) throws {
let key = self.sanitizeKey(key)
if value.structuredHeadersIsValidToken {
try self.currentStackEntry.storage.insertBareItem(.token(value), atKey: key)
} else {
try self.currentStackEntry.storage.insertBareItem(.string(value), atKey: key)
}
}
func encode(_ value: Double, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeBinaryFloatingPoint(value, forKey: key)
}
func encode(_ value: Float, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeBinaryFloatingPoint(value, forKey: key)
}
func encode(_ value: Int, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: Int8, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: Int16, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: Int32, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: Int64, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: UInt, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: UInt8, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: UInt16, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: UInt32, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: UInt64, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self._encodeFixedWidthInteger(value, forKey: key)
}
func encode(_ value: Data, forKey key: String) throws {
let key = self.sanitizeKey(key)
try self.currentStackEntry.storage.insertBareItem(.undecodedByteSequence(value.base64EncodedString()), 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<T>(_ value: T, forKey key: String) throws where T: Encodable {
let key = self.sanitizeKey(key)
switch value {
case let value as UInt8:
try self.encode(value, forKey: key)
case let value as Int8:
try self.encode(value, forKey: key)
case let value as UInt16:
try self.encode(value, forKey: key)
case let value as Int16:
try self.encode(value, forKey: key)
case let value as UInt32:
try self.encode(value, forKey: key)
case let value as Int32:
try self.encode(value, forKey: key)
case let value as UInt64:
try self.encode(value, forKey: key)
case let value as Int64:
try self.encode(value, forKey: key)
case let value as Int:
try self.encode(value, forKey: key)
case let value as UInt:
try self.encode(value, forKey: key)
case let value as Float:
try self.encode(value, forKey: key)
case let value as Double:
try self.encode(value, forKey: key)
case let value as String:
try self.encode(value, forKey: key)
case let value as Bool:
try self.encode(value, forKey: key)
case let value as Data:
try self.encode(value, forKey: key)
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 lists, or for inner lists.
switch self.currentStackEntry.storage {
case .dictionaryHeader:
// Ah, this is a dictionary, good to know. Initialize the storage, keep going.
self.currentStackEntry.storage = .dictionary([:])
fallthrough
case .dictionary:
// This must be an item or inner list.
self.push(key: .init(stringValue: key), newStorage: .itemOrInnerList([:]))
try value.encode(to: self)
try self.pop()
case .item:
guard key == "parameters" else {
throw StructuredHeaderError.invalidTypeForItem
}
self.push(key: .init(stringValue: key), newStorage: .parameters([:]))
try value.encode(to: self)
try self.pop()
case .innerList:
switch key {
case "items":
self.push(key: .init(stringValue: key), newStorage: .bareInnerList([]))
try value.encode(to: self)
try self.pop()
case "parameters":
self.push(key: .init(stringValue: key), newStorage: .parameters([:]))
try value.encode(to: self)
try self.pop()
default:
throw StructuredHeaderError.invalidTypeForItem
}
case .itemOrInnerList(let params):
switch key {
case "items":
// We're a list!
self.currentStackEntry.storage = .innerList(InnerList(bareInnerList: [], parameters: params))
self.push(key: .init(stringValue: key), newStorage: .bareInnerList([]))
try value.encode(to: self)
try self.pop()
case "parameters":
self.push(key: .init(stringValue: key), newStorage: .parameters([:]))
try value.encode(to: self)
try self.pop()
default:
throw StructuredHeaderError.invalidTypeForItem
}
case .listHeader:
switch key {
case "items":
// Ok, we're a list. Good to know.
self.push(key: .init(stringValue: key), newStorage: .list([]))
try value.encode(to: self)
try self.pop()
default:
throw StructuredHeaderError.invalidTypeForItem
}
case .list, .itemHeader, .bareInnerList,
.parameters:
throw StructuredHeaderError.invalidTypeForItem
}
}
}
private func _encodeFixedWidthInteger<T: FixedWidthInteger>(_ value: T, forKey key: String) throws {
guard let base = Int(exactly: value) else {
throw StructuredHeaderError.integerOutOfRange
}
try self.currentStackEntry.storage.insertBareItem(.integer(base), atKey: key)
}
private func _encodeBinaryFloatingPoint<T: BinaryFloatingPoint>(_ value: T, forKey key: String) throws {
let pseudoDecimal = try PseudoDecimal(Double(value))
try self.currentStackEntry.storage.insertBareItem(.decimal(pseudoDecimal), atKey: key)
}
private func sanitizeKey(_ key: String) -> String {
if self.keyEncodingStrategy == .lowercase {
return key.lowercased()
} else {
return key
}
}
}
extension _StructuredFieldEncoder {
/// An entry in the coding stack for _StructuredFieldEncoder.
///
/// This is used to keep track of where we are in the encode.
private struct CodingStackEntry {
var key: _StructuredHeaderCodingKey
var storage: NodeType
}
/// The type of the node at the current level of the encoding hierarchy.
/// This controls what container types are allowed, and is where partial
/// encodes are stored.
///
/// Note that we never have a bare item here. This is deliberate: bare items
/// are not a container for anything else, and so can never appear.
internal enum NodeType {
case dictionaryHeader
case listHeader
case itemHeader
case dictionary(OrderedMap<String, ItemOrInnerList>)
case list([ItemOrInnerList])
case innerList(InnerList)
case item(PartialItem)
case bareInnerList(BareInnerList)
case parameters(OrderedMap<String, BareItem>)
case itemOrInnerList(OrderedMap<String, BareItem>)
/// A helper struct used to tolerate the fact that we need partial items,
/// but our `Item` struct doesn't like that much.
struct PartialItem {
var bareItem: BareItem?
var parameters: OrderedMap<String, BareItem>
}
/// This is called when a complete object has been built.
mutating func insert(_ childData: NodeType, atKey key: _StructuredHeaderCodingKey) throws {
// Only some things can be inside other things, and often that relies on
// the specifics of the key.
switch (self, childData) {
case (.item(var item), .parameters(let params)) where key.stringValue == "parameters":
// Oh cool, parameters. Love it. Save it.
item.parameters = params
self = .item(item)
case (.innerList(var list), .parameters(let params)) where key.stringValue == "parameters":
list.parameters = params
self = .innerList(list)
case (.innerList(var list), .bareInnerList(let bare)) where key.stringValue == "items":
list.bareInnerList = bare
self = .innerList(list)
case (.innerList(var list), .item(let item)) where key.intValue != nil:
list.bareInnerList.append(Item(item))
self = .innerList(list)
case (.bareInnerList(var list), .item(let item)):
precondition(key.intValue == list.count)
list.append(Item(item))
self = .bareInnerList(list)
case (.itemOrInnerList, .parameters(let params)) where key.stringValue == "parameters":
self = .itemOrInnerList(params)
case (.itemOrInnerList, .item(let item)):
self = .item(item)
case (.itemOrInnerList, .innerList(let list)):
self = .innerList(list)
case (.dictionary(var map), .innerList(let innerList)):
map[key.stringValue] = .innerList(innerList)
self = .dictionary(map)
case (.dictionary(var map), .item(let item)):
map[key.stringValue] = .item(Item(item))
self = .dictionary(map)
case (.listHeader, .list(let list)) where key.stringValue == "items":
self = .list(list)
case (.listHeader, .innerList(let innerList)) where key.intValue != nil:
self = .list([.innerList(innerList)])
case (.listHeader, .item(let item)) where key.intValue != nil:
self = .list([.item(Item(item))])
case (.list(var list), .innerList(let innerList)) where key.intValue != nil:
list.append(.innerList(innerList))
self = .list(list)
case (.list(var list), .item(let item)) where key.intValue != nil:
list.append(.item(Item(item)))
self = .list(list)
default:
throw StructuredHeaderError.invalidTypeForItem
}
}
/// Called to insert a bare item at a given level of the hierarchy.
///
/// If the key is missing we will require the type to be `item`, in which case
/// this will be for the "item" key.
mutating func insertBareItem(_ bareItem: BareItem, atKey key: String? = nil) throws {
switch self {
case .itemHeader:
guard key == nil || key == "item" else {
throw StructuredHeaderError.invalidTypeForItem
}
self = .item(PartialItem(bareItem: bareItem, parameters: [:]))
case .item(var partial):
if key == nil || key == "item" {
partial.bareItem = bareItem
self = .item(partial)
} else {
throw StructuredHeaderError.invalidTypeForItem
}
case .itemOrInnerList(let params):
// Key can only be item: if we have a key, we must have asked for a keyed
// container, which would have disambiguated what we were getting.
if key == "item" {
self = .item(PartialItem(bareItem: bareItem, parameters: params))
} else {
throw StructuredHeaderError.invalidTypeForItem
}
case .dictionaryHeader:
// Ok cool, this is a dictionary.
var map = OrderedMap<String, ItemOrInnerList>()
// Bare item here means item, no parameters.
map[key!] = .item(.init(bareItem: bareItem, parameters: [:]))
self = .dictionary(map)
case .dictionary(var map):
// Bare item here means item, no parameters.
map[key!] = .item(.init(bareItem: bareItem, parameters: [:]))
self = .dictionary(map)
case .parameters(var map):
map[key!] = bareItem
self = .parameters(map)
case .listHeader, .list, .innerList, .bareInnerList:
throw StructuredHeaderError.invalidTypeForItem
}
}
/// Appends a bare item to the given container. This must be a list-type
/// container that stores either bare items, or items.
mutating func appendBareItem(_ bareItem: BareItem) throws {
switch self {
case .listHeader:
self = .list([.item(Item(bareItem: bareItem, parameters: [:]))])
case .list(var list):
list.append(.item(Item(bareItem: bareItem, parameters: [:])))
self = .list(list)
case .innerList(var list):
list.bareInnerList.append(Item(bareItem: bareItem, parameters: [:]))
self = .innerList(list)
case .bareInnerList(var list):
list.append(Item(bareItem: bareItem, parameters: [:]))
self = .bareInnerList(list)
case .itemOrInnerList(let params):
// This is an inner list.
self = .innerList(InnerList(bareInnerList: [Item(bareItem: bareItem, parameters: [:])], parameters: params))
case .dictionaryHeader, .dictionary, .itemHeader, .item,
.parameters:
throw StructuredHeaderError.invalidTypeForItem
}
}
}
}
extension Item {
fileprivate init(_ partialItem: _StructuredFieldEncoder.NodeType.PartialItem) {
self.init(bareItem: partialItem.bareItem!, parameters: partialItem.parameters)
}
}
@@ -0,0 +1,34 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 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
//
//===----------------------------------------------------------------------===//
/// A `StructuredFieldValue` is a `Codable` representation of a HTTP Structured
/// Header Field.
///
/// This protocol is a helper protocol that refines `Codable` to indicate what kind
/// of header field a given field uses.
public protocol StructuredFieldValue: Codable {
static var structuredFieldType: StructuredFieldType { get }
}
/// The kinds of header fields used in HTTP Structured Headers.
public enum StructuredFieldType {
/// An item field consists of a single item, optionally with parameters.
case item
/// A list field consists of a list made up of inner lists or items.
case list
/// A dictionary field is an ordered collection of key-value pairs.
case dictionary
}