mirror of
https://github.com/apple/swift-http-structured-headers
synced 2026-11-27 05:04:20 +00:00
Initial basic Decoder implementation
This commit is contained in:
1 parent
68a2409ef9
commit
49370cd8db
14 files changed
+1186
-164
No files matched your search
@@ -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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
case item(Item<BaseData>)
|
||||
case innerList(InnerList<BaseData>)
|
||||
}
|
||||
|
||||
extension ItemOrInnerList: Hashable { }
|
||||
|
||||
// MARK:- BareItem
|
||||
public enum BareItem<BaseData: RandomAccessCollection> 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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
public var bareItem: BareItem<BaseData>
|
||||
public var parameters: OrderedMap<BaseData, BareItem<BaseData>>
|
||||
}
|
||||
|
||||
extension Item: Hashable { }
|
||||
|
||||
// MARK:- BareInnerList
|
||||
public struct BareInnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
private var items: [Item<BaseData>]
|
||||
|
||||
public init() {
|
||||
self.items = []
|
||||
}
|
||||
|
||||
public mutating func append(_ item: Item<BaseData>) {
|
||||
self.items.append(item)
|
||||
}
|
||||
}
|
||||
|
||||
extension BareInnerList: ExpressibleByArrayLiteral {
|
||||
public init(arrayLiteral elements: Item<BaseData>...) {
|
||||
self.items = elements
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: RangeReplaceableCollection I guess
|
||||
extension BareInnerList: RandomAccessCollection, MutableCollection {
|
||||
public struct Index {
|
||||
fileprivate var baseIndex: Array<Item<BaseData>>.Index
|
||||
|
||||
init(_ baseIndex: Array<Item<BaseData>>.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<BaseData> {
|
||||
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<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
public var bareInnerList: BareInnerList<BaseData>
|
||||
public var parameters: OrderedMap<BaseData, BareItem<BaseData>>
|
||||
}
|
||||
@@ -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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private var list: BareInnerList<BaseData.SubSequence>
|
||||
|
||||
private var currentOffset: Int
|
||||
|
||||
private var decoder: _StructuredFieldDecoder<BaseData>
|
||||
|
||||
init(_ list: BareInnerList<BaseData.SubSequence>, decoder: _StructuredFieldDecoder<BaseData>) {
|
||||
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<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()
|
||||
}
|
||||
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,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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
private var item: BareItem<BaseData>
|
||||
|
||||
private var _codingPath: [_StructuredHeaderCodingKey]
|
||||
|
||||
init(_ item: BareItem<BaseData>, 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<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
|
||||
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<T: BinaryFloatingPoint>(_ type: T.Type) throws -> T {
|
||||
guard case .decimal(let decimal) = self.item else {
|
||||
throw StructuredHeaderError.invalidTypeForItem
|
||||
}
|
||||
|
||||
return T(decimal)
|
||||
}
|
||||
|
||||
private func _decodeFixedWidthInteger<T: FixedWidthInteger>(_ 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
|
||||
}
|
||||
}
|
||||
@@ -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<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private var dictionary: OrderedMap<BaseData.SubSequence, ItemOrInnerList<BaseData.SubSequence>>
|
||||
|
||||
private var decoder: _StructuredFieldDecoder<BaseData>
|
||||
|
||||
init(_ dictionary: OrderedMap<BaseData.SubSequence, ItemOrInnerList<BaseData.SubSequence>>, decoder: _StructuredFieldDecoder<BaseData>) {
|
||||
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<T>(_ 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<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private var innerList: InnerList<BaseData.SubSequence>
|
||||
|
||||
private var decoder: _StructuredFieldDecoder<BaseData>
|
||||
|
||||
init(_ innerList: InnerList<BaseData.SubSequence>, decoder: _StructuredFieldDecoder<BaseData>) {
|
||||
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<T>(_ 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<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private var item: Item<BaseData.SubSequence>
|
||||
|
||||
private var decoder: _StructuredFieldDecoder<BaseData>
|
||||
|
||||
init(_ item: Item<BaseData.SubSequence>, decoder: _StructuredFieldDecoder<BaseData>) {
|
||||
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<T>(_ 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<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private var parameters: OrderedMap<BaseData.SubSequence, BareItem<BaseData.SubSequence>>
|
||||
|
||||
private var decoder: _StructuredFieldDecoder<BaseData>
|
||||
|
||||
init(_ parameters: OrderedMap<BaseData.SubSequence, BareItem<BaseData.SubSequence>>, decoder: _StructuredFieldDecoder<BaseData>) {
|
||||
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<T>(_ 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<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<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)
|
||||
return try type.init(from: decoder)
|
||||
}
|
||||
}
|
||||
|
||||
class _StructuredFieldDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
private var parser: StructuredFieldParser<BaseData>
|
||||
|
||||
// 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<BaseData>) {
|
||||
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<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> 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<BaseData.SubSequence, ItemOrInnerList<BaseData.SubSequence>>)
|
||||
case list([ItemOrInnerList<BaseData.SubSequence>])
|
||||
case item(Item<BaseData.SubSequence>)
|
||||
case innerList(InnerList<BaseData.SubSequence>)
|
||||
case bareItem(BareItem<BaseData.SubSequence>)
|
||||
case bareInnerList(BareInnerList<BaseData.SubSequence>)
|
||||
case parameters(OrderedMap<BaseData.SubSequence, BareItem<BaseData.SubSequence>>)
|
||||
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -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: CodingKey>(_ key: Key) {
|
||||
self.stringValue = key.stringValue
|
||||
self.intValue = key.intValue
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
public struct StructuredFieldParser<BaseData: RandomAccessCollection> 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<BaseData.SubSequence>
|
||||
typealias Item = StructuredHeaders.Item<BaseData.SubSequence>
|
||||
typealias BareInnerList = StructuredHeaders.BareInnerList<BaseData.SubSequence>
|
||||
typealias InnerList = StructuredHeaders.InnerList<BaseData.SubSequence>
|
||||
typealias ItemOrInnerList = StructuredHeaders.ItemOrInnerList<BaseData.SubSequence>
|
||||
typealias Key = BaseData.SubSequence
|
||||
public typealias BareItem = StructuredHeaders.BareItem<BaseData.SubSequence>
|
||||
public typealias Item = StructuredHeaders.Item<BaseData.SubSequence>
|
||||
public typealias BareInnerList = StructuredHeaders.BareInnerList<BaseData.SubSequence>
|
||||
public typealias InnerList = StructuredHeaders.InnerList<BaseData.SubSequence>
|
||||
public typealias ItemOrInnerList = StructuredHeaders.ItemOrInnerList<BaseData.SubSequence>
|
||||
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<Key, ItemOrInnerList> {
|
||||
public mutating func parseDictionaryField() throws -> OrderedMap<Key, ItemOrInnerList> {
|
||||
// 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..<index]
|
||||
self.underlyingData.formIndex(after: &index)
|
||||
@@ -424,12 +424,12 @@ extension StructuredFieldParser {
|
||||
self.underlyingData.formIndex(after: &index)
|
||||
default:
|
||||
// Invalid character
|
||||
throw StructuredHeaderParsingError.invalidByteSequence
|
||||
throw StructuredHeaderError.invalidByteSequence
|
||||
}
|
||||
}
|
||||
|
||||
// Whoops, got to the end, invalid byte sequence.
|
||||
throw StructuredHeaderParsingError.invalidByteSequence
|
||||
throw StructuredHeaderError.invalidByteSequence
|
||||
}
|
||||
|
||||
private mutating func _parseABoolean() throws -> 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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
case item(Item<BaseData>)
|
||||
case innerList(InnerList<BaseData>)
|
||||
}
|
||||
|
||||
enum BareItem<BaseData: RandomAccessCollection> 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<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
var bareItem: BareItem<BaseData>
|
||||
var parameters: OrderedMap<BaseData, BareItem<BaseData>>
|
||||
}
|
||||
|
||||
extension Item: Hashable { }
|
||||
|
||||
struct BareInnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
private var items: [Item<BaseData>]
|
||||
|
||||
init() {
|
||||
self.items = []
|
||||
}
|
||||
|
||||
fileprivate mutating func append(_ item: Item<BaseData>) {
|
||||
self.items.append(item)
|
||||
}
|
||||
}
|
||||
|
||||
extension BareInnerList: RandomAccessCollection, MutableCollection {
|
||||
struct Index {
|
||||
fileprivate var baseIndex: Array<Item<BaseData>>.Index
|
||||
|
||||
init(_ baseIndex: Array<Item<BaseData>>.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<BaseData> {
|
||||
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<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
var bareInnerList: BareInnerList<BaseData>
|
||||
var parameters: OrderedMap<BaseData, BareItem<BaseData>>
|
||||
}
|
||||
|
||||
fileprivate enum IntegerOrDecimal {
|
||||
case integer
|
||||
case decimal
|
||||
|
||||
@@ -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<Key, Value> where Key: Hashable {
|
||||
public struct OrderedMap<Key, Value> 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)]"
|
||||
}
|
||||
|
||||
@@ -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)))
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import StructuredHeaders
|
||||
import StructuredHeaders
|
||||
|
||||
enum FixtureTestError: Error {
|
||||
case base64DecodingFailed
|
||||
|
||||
Reference in new issue
Block a user