mirror of
https://github.com/apple/swift-http-structured-headers
synced 2026-11-25 04:47:48 +00:00
Introduce StructuredHeaderField protocol.
Motivation: We had a proliferation of decode/encode methods that required users to tell us how to encode their structured header field. This is a bit annoying for two reasons: firstly, it requires users to encode this piece of information separately from their header field; secondly, it makes it very hard to offer a generic interface to load something as a structured header field! Modifications: - Add a new StructuredHeaderField protocol that refines Codable and expresses what type of header field is used. - Remove the fancy encode/decode methods. Result: Simpler interfaces.
This commit is contained in:
1 parent
6a2b13e370
commit
101dec0a99
4 files changed
+278
-119
No files matched your search
@@ -0,0 +1,93 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 StructuredHeaders
|
||||
|
||||
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, BaseData.SubSequence: Hashable {
|
||||
private var list: [ItemOrInnerList<BaseData.SubSequence>]
|
||||
|
||||
private var decoder: _StructuredFieldDecoder<BaseData>
|
||||
|
||||
init(_ list: [ItemOrInnerList<BaseData.SubSequence>], 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
|
||||
}
|
||||
}
|
||||
@@ -41,20 +41,20 @@ extension StructuredFieldDecoder {
|
||||
extension StructuredFieldDecoder {
|
||||
/// Attempt to decode an object from a structured header field.
|
||||
///
|
||||
/// This method will attempt to guess what kind of structured header field is being
|
||||
/// parsed based on the structure of `type`. This is useful for quick prototyping, but
|
||||
/// generally this method should be avoided in favour of one of the other `decode`
|
||||
/// methods on this type.
|
||||
///
|
||||
/// - 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: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
let parser = StructuredFieldParser(data)
|
||||
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
|
||||
return try type.init(from: decoder)
|
||||
public func decode<StructuredField: StructuredHeaderField, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
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.
|
||||
@@ -64,7 +64,7 @@ extension StructuredFieldDecoder {
|
||||
/// - 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 decodeDictionaryField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private func decodeDictionaryField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
let parser = StructuredFieldParser(data)
|
||||
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
|
||||
try decoder.parseDictionaryField()
|
||||
@@ -78,7 +78,7 @@ extension StructuredFieldDecoder {
|
||||
/// - 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 decodeListField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private func decodeListField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
let parser = StructuredFieldParser(data)
|
||||
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
|
||||
try decoder.parseListField()
|
||||
@@ -92,7 +92,7 @@ extension StructuredFieldDecoder {
|
||||
/// - 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 decodeItemField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private func decodeItemField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
let parser = StructuredFieldParser(data)
|
||||
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
|
||||
try decoder.parseItemField()
|
||||
@@ -148,34 +148,24 @@ extension _StructuredFieldDecoder: Decoder {
|
||||
}
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
|
||||
if self.currentElement == nil {
|
||||
// First parse. This may be a dictionary, but depending on the keys this may also be list or item.
|
||||
// We can't really detect this (Key isn't caseiterable) so we just kinda have to hope. Users can tell
|
||||
// us with alternative methods if we're wrong.
|
||||
try self.parseDictionaryField()
|
||||
}
|
||||
|
||||
switch self.currentElement! {
|
||||
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, .list:
|
||||
case .bareItem, .bareInnerList:
|
||||
// No keyed container for these types.
|
||||
throw StructuredHeaderError.invalidTypeForItem
|
||||
}
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
if self.currentElement == nil {
|
||||
// First parse, this is a list header.
|
||||
try self.parseListField()
|
||||
}
|
||||
|
||||
// We have unkeyed containers for lists, inner lists, and bare inner lists.
|
||||
switch self.currentElement! {
|
||||
case .list(let items):
|
||||
@@ -191,11 +181,6 @@ extension _StructuredFieldDecoder: Decoder {
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
if self.currentElement == nil {
|
||||
// First parse, this is a an item header.
|
||||
try self.parseItemField()
|
||||
}
|
||||
|
||||
// We have single value containers for items and bareItems.
|
||||
switch self.currentElement! {
|
||||
case .item(let item):
|
||||
@@ -256,16 +241,24 @@ extension _StructuredFieldDecoder {
|
||||
return .innerList(innerList)
|
||||
}
|
||||
case .list(let list):
|
||||
guard let offset = key.intValue, offset < list.count else {
|
||||
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
|
||||
}
|
||||
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 {
|
||||
|
||||
Reference in new issue
Block a user