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

+10 -10
View File
@@ -18,30 +18,30 @@ let package = Package(
name: "swift-http-structured-headers",
products: [
.library(
name: "StructuredHeaders",
targets: ["StructuredHeaders"]
name: "StructuredFieldValues",
targets: ["StructuredFieldValues"]
),
.library(
name: "CodableStructuredHeaders",
targets: ["CodableStructuredHeaders"]
name: "RawStructuredFieldValues",
targets: ["RawStructuredFieldValues"]
),
],
targets: [
.target(
name: "StructuredHeaders",
name: "RawStructuredFieldValues",
dependencies: []
),
.target(
name: "CodableStructuredHeaders",
dependencies: ["StructuredHeaders"]
name: "StructuredFieldValues",
dependencies: ["RawStructuredFieldValues"]
),
.target(
name: "sh-parser",
dependencies: ["StructuredHeaders"]
dependencies: ["RawStructuredFieldValues"]
),
.testTarget(
name: "StructuredHeadersTests",
dependencies: ["StructuredHeaders", "CodableStructuredHeaders"]
name: "StructuredFieldValuesTests",
dependencies: ["RawStructuredFieldValues", "StructuredFieldValues"]
),
]
)
+37 -37
View File
@@ -1,30 +1,30 @@
# swift-http-structured-headers
A Swift implementation of the HTTP Structured Header Field specification.
A Swift implementation of the HTTP Structured Header Field Value specification.
Provides parsing and serialization facilities for structured header fields, as well as implementations of `Encoder` and `Decoder` to allow using `Codable` data types as the payloads of HTTP structured header fields.
Provides parsing and serialization facilities for structured header field values, as well as implementations of `Encoder` and `Decoder` to allow using `Codable` data types as the payloads of HTTP structured header fields.
## About Structured Header Fields
## About Structured Header Field Values
HTTP Structured Header fields are a HTTP extension recorded in [RFC 8941](https://www.rfc-editor.org/rfc/rfc8941.html) . They provide a set of data types and algorithms for handling HTTP header field values in a consistent way, allowing a single parser and serializer to handle a wide range of header field values.
HTTP Structured Header Field Values are a HTTP extension recorded in [RFC 8941](https://www.rfc-editor.org/rfc/rfc8941.html). They provide a set of data types and algorithms for handling HTTP header field values in a consistent way, allowing a single parser and serializer to handle a wide range of header field values.
## Swift HTTP Structured Header Fields
## Swift HTTP Structured Header Field Values
This package provides a parser and serializer that implement RFC 8941. They are entirely complete, able to handle all valid HTTP structured header fields. This package also provides `Encoder` and `Decoder` objects for working with Codable in Swift. This allows rapid prototyping and experimentation with HTTP structured header fields, as well as interaction with the wider Swift Codable community.
This package provides a parser and serializer that implement RFC 8941. They are entirely complete, able to handle all valid HTTP structured header field values. This package also provides `Encoder` and `Decoder` objects for working with Codable in Swift. This allows rapid prototyping and experimentation with HTTP structured header field values, as well as interaction with the wider Swift Codable community.
This package provides two top-level modules: `StructuredHeaders` and `CodableStructuredHeaders`.
This package provides two top-level modules: `StructuredFieldValues` and `RawStructuredFieldValues`.
The base module, `StructuredHeaders`, provides a low-level implementation of a serializer and parser. Both of these have been written to avoid using Foundation, making them suitable for a range of use-cases where Foundation is not available. They rely entirely on the Swift standard library and are implemented as generically as possible. One of the limitations due to the absence of Foundation is that this interface is not capable of performing Base64 encoding or decoding: users are free to bring whatever encoder and decoder they choose to use.
The base module, `RawStructuredFieldValues`, provides a low-level implementation of a serializer and parser. Both of these have been written to avoid using Foundation, making them suitable for a range of use-cases where Foundation is not available. They rely entirely on the Swift standard library and are implemented as generically as possible. One of the limitations due to the absence of Foundation is that this interface is not capable of performing Base64 encoding or decoding: users are free to bring whatever encoder and decoder they choose to use.
This API is low-level, exposing the raw parse tree as the format for the serializer and parser. This allows high-performance and high-flexibility parsing and serialization, at the cost of being verbose and complex. Users are required to understand the structured header format and to operate the slightly awkward types, but maximal fidelity is retained and the performance overhead is low.
The upper-level module, `CodableStructuredHeaders`, brings along the `Encoder` and `Decoder` and also adds a dependency on Foundation. This Foundation dependency is necessary to correctly handle the base64 formatting, as well as to provide a good natural container for binary data: `Data`. This interface is substantially friendlier and easier to work with, using Swift's `Codable` support to provide a great user experience.
The upper-level module, `StructuredFieldValues`, brings along the `Encoder` and `Decoder` and also adds a dependency on Foundation. This Foundation dependency is necessary to correctly handle the base64 formatting, as well as to provide a good natural container for binary data: `Data`. This interface is substantially friendlier and easier to work with, using Swift's `Codable` support to provide a great user experience.
In most cases users should prefer to use `CodableStructuredHeaders` unless they know they need the performance advantages of `StructuredHeaders`. The experience will be much better.
In most cases users should prefer to use `StructuredFieldValues` unless they know they need the performance advantages of `RawStructuredFieldValues`. The experience will be much better.
## Working with Structured Header Fields
## Working with Structured Header Field Values
`swift-http-structured-headers` has a simply, easy-to-use high-level API for working with structured header fields. To begin with, let's consider the [HTTP Client Hints specification](https://www.rfc-editor.org/rfc/rfc8942.html). This defines the following new header field:
`swift-http-structured-headers` has a simple, easy-to-use high-level API for working with structured header field values. To begin with, let's consider the [HTTP Client Hints specification](https://www.rfc-editor.org/rfc/rfc8942.html). This defines the following new header field:
> The Accept-CH response header field indicates server support for the hints indicated in its value. Servers wishing to receive user agent information through Client Hints SHOULD add Accept-CH response header to their responses as early as possible.
>
@@ -41,57 +41,57 @@ In most cases users should prefer to use `CodableStructuredHeaders` unless they
```swift
let field = Array("Sec-CH-Example, Sec-CH-Example-2".utf8)
struct AcceptCH: StructuredHeaderField {
static let structuredFiedType: StructuredHeaderFieldType = .list
struct AcceptCH: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .list
var items: [String]
}
// Decoding
let decoder = StructuredFieldDecoder()
let decoder = StructuredFieldValueDecoder()
let parsed = try decoder.decode(AcceptCH.self, from: field)
// Encoding
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let serialized = try encoder.encode(AcceptCH(items: ["Sec-CH-Example", "Sec-CH-Example-2"]))
```
However, structured header fields can be substantially more complex. Structured header fields can make use of 4 containers and 6 base item types. The containers are:
However, structured header field values can be substantially more complex. Structured header fields can make use of 4 containers and 6 base item types. The containers are:
1. Dictionaries. These are top-level elements and associate token keys with values. The values may be items, or may be inner lists, and each value may also have parameters associated with them. `CodableStructuredHeaders` can model dictionaries as either Swift objects (where the property names are dictionary keys).
2. Lists. These are top-level elements, providing a sequence of items or inner lists. Each item or inner list may have parameters associated with them. `CodableStructuredHeaders` models these as Swift objects with one key, `items`, that must be a collection of entries.
3. Inner Lists. These are lists that may be sub-entries of a dictionary or a list. The list entries are items, which may have parameters associated with them: additionally, an inner list may have parameters associated with itself as well. `CodableStructuredHeaders` models these as either Swift `Array`s _or_, if it's important to extract parameters, as a two-field Swift `struct` where one field is called `items` and contains an `Array`, and other field is called `parameters` and contains a dictionary.
4. Parameters. Parameters associated token keys with items without parameters. These are used to store metadata about objects within a field. `CodableStructuredHeaders` models these as either Swift objects (where the property names are the parameter keys) or as Swift dictionaries.
1. Dictionaries. These are top-level elements and associate token keys with values. The values may be items, or may be inner lists, and each value may also have parameters associated with them. `StructuredFieldValues` can model dictionaries as either Swift objects (where the property names are dictionary keys).
2. Lists. These are top-level elements, providing a sequence of items or inner lists. Each item or inner list may have parameters associated with them. `StructuredFieldValues` models these as Swift objects with one key, `items`, that must be a collection of entries.
3. Inner Lists. These are lists that may be sub-entries of a dictionary or a list. The list entries are items, which may have parameters associated with them: additionally, an inner list may have parameters associated with itself as well. `StructuredFieldValues` models these as either Swift `Array`s _or_, if it's important to extract parameters, as a two-field Swift `struct` where one field is called `items` and contains an `Array`, and other field is called `parameters` and contains a dictionary.
4. Parameters. Parameters associated token keys with items without parameters. These are used to store metadata about objects within a field. `StructuredFieldValues` models these as either Swift objects (where the property names are the parameter keys) or as Swift dictionaries.
The base types are:
1. Booleans. `CodableStructuredHeaders` models these as Swift's `Bool` type.
2. Integers. `CodableStructuredHeaders` models these as any fixed-width integer type.
3. Decimals. `CodableStructuredHeaders` models these as any floating-point type, or as Foundation's `Decimal`.
4. Tokens. `CodableStructuredHeaders` models these as Swift's `String` type, where the range of characters is restricted.
5. Strings. `CodableStructuredHeaders` models these as Swift's `String` type.
6. Binary data. `CodableStructuredHeaders` models this as Foundation's `Data` type.
1. Booleans. `StructuredFieldValues` models these as Swift's `Bool` type.
2. Integers. `StructuredFieldValues` models these as any fixed-width integer type.
3. Decimals. `StructuredFieldValues` models these as any floating-point type, or as Foundation's `Decimal`.
4. Tokens. `StructuredFieldValues` models these as Swift's `String` type, where the range of characters is restricted.
5. Strings. `StructuredFieldValues` models these as Swift's `String` type.
6. Binary data. `StructuredFieldValues` models this as Foundation's `Data` type.
For any Structured Header Field Item, the item may either be represented directly by the appropriate type, or by a Swift struct with two properties: `item` and `parameters`. This latter mode is how parameters on a given item may be captured.
For any Structured Header Field Value Item, the item may either be represented directly by the appropriate type, or by a Swift struct with two properties: `item` and `parameters`. This latter mode is how parameters on a given item may be captured.
The top-level structured header field must identify what kind of header field it corresponds to: `.item`, `.list`, or `.dictionary`. This is inherent in the type of the field and will be specified in the relevant field specification.
The top-level Structured Header Field Value must identify what kind of header field it corresponds to: `.item`, `.list`, or `.dictionary`. This is inherent in the type of the field and will be specified in the relevant field specification.
## Lower Levels
In some cases the Codable interface will not be either performant enough or powerful enough for the intended use-case. In cases like this, users can use the types in the `StructuredHeaders` module instead.
In some cases the Codable interface will not be either performant enough or powerful enough for the intended use-case. In cases like this, users can use the types in the `RawStructuredFieldValues` module instead.
There are two core types: `StructuredFieldParser` and `StructuredFieldSerializer`. Rather than work with high-level Swift objects, these two objects either produce or accept a Swift representation of the data tree for a given structured header field.
There are two core types: `StructuredFieldValueParser` and `StructuredFieldValueSerializer`. Rather than work with high-level Swift objects, these two objects either produce or accept a Swift representation of the data tree for a given structured header field.
This exposes the maximum amount of information about the header field. It allows users to handle situations where Codable cannot necessarily provide the relevant information, such in cases where dictionary ordering is semantic, or where it's necessary to control whether fields are tokens or strings more closely.
These APIs also have lower overhead than the `CodableStructuredHeaders` APIs.
These APIs also have lower overhead than the `StructuredFieldValues` APIs.
The cost is that the APIs are substantially more verbose. Consider the above header field, `Accept-CH`. To parse or serialize this in `StructuredHeaders` would look like this:
The cost is that the APIs are substantially more verbose. Consider the above header field, `Accept-CH`. To parse or serialize this in `RawStructuredFieldValues` would look like this:
```swift
let field = Array("Sec-CH-Example, Sec-CH-Example-2".utf8)
var parser = StructuredFieldParser(field)
let parsed = parser.parseListField()
var parser = StructuredFieldValueParser(field)
let parsed = parser.parseListFieldValue()
print(parsed)
// [
@@ -99,8 +99,8 @@ print(parsed)
// .item(Item(bareItem: .token("Sec-CH-Example-2"), parameters: [])),
// ]
var serializer = StructuredFieldSerializer()
let serialized = serializer.writeListHeader(parsed)
var serializer = StructuredFieldValueSerializer()
let serialized = serializer.writeListFieldValue(parsed)
```
Notice the substantially more verbose types involved in this operation. These types are highly generic, giving the opportunity for parsing and serializing that greatly reduces the runtime overhead. They also make it easier to distinguish between tokens and strings, and to observe the order of objects in dictionaries or parameters, which can be lost at the Codable level.
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,8 +12,8 @@
//
//===----------------------------------------------------------------------===//
/// A `StructuredFieldParser` is the basic parsing object for structured header fields.
public struct StructuredFieldParser<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
/// A `StructuredFieldValueParser` is the basic parsing object for structured header field values.
public struct StructuredFieldValueParser<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
// 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
@@ -25,22 +25,22 @@ public struct StructuredFieldParser<BaseData: RandomAccessCollection> where Base
}
}
extension StructuredFieldParser {
extension StructuredFieldValueParser {
// Helper typealiases to avoid the explosion of generic parameters
public typealias BareItem = StructuredHeaders.BareItem
public typealias Item = StructuredHeaders.Item
public typealias BareInnerList = StructuredHeaders.BareInnerList
public typealias InnerList = StructuredHeaders.InnerList
public typealias ItemOrInnerList = StructuredHeaders.ItemOrInnerList
public typealias BareItem = RawStructuredFieldValues.BareItem
public typealias Item = RawStructuredFieldValues.Item
public typealias BareInnerList = RawStructuredFieldValues.BareInnerList
public typealias InnerList = RawStructuredFieldValues.InnerList
public typealias ItemOrInnerList = RawStructuredFieldValues.ItemOrInnerList
public typealias Key = String
/// Parse the HTTP structured field as a list.
/// Parse the HTTP structured field value as a list.
///
/// This is a straightforward implementation of the parser in the spec.
///
/// - throws: If the field could not be parsed.
/// - throws: If the field value could not be parsed.
/// - returns: An array of items or inner lists.
public mutating func parseListField() throws -> [ItemOrInnerList] {
public mutating func parseListFieldValue() throws -> [ItemOrInnerList] {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
@@ -58,11 +58,11 @@ extension StructuredFieldParser {
return members
}
/// Parse the HTTP structured header field as a dictionary.
/// Parse the HTTP structured header field value as a dictionary.
///
/// - throws: If the field could not be parsed.
/// - throws: If the field value could not be parsed.
/// - returns: An `OrderedMap` corresponding to the entries in the dictionary.
public mutating func parseDictionaryField() throws -> OrderedMap<Key, ItemOrInnerList> {
public mutating func parseDictionaryFieldValue() throws -> OrderedMap<Key, ItemOrInnerList> {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
@@ -80,11 +80,11 @@ extension StructuredFieldParser {
return map
}
/// Parse the HTTP structured header field as an item.
/// Parse the HTTP structured header field value as an item.
///
/// - throws: If the field could not be parsed.
/// - throws: If the field value could not be parsed.
/// - returns: The `Item` in the field.
public mutating func parseItemField() throws -> Item {
public mutating func parseItemFieldValue() throws -> Item {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -14,8 +14,8 @@
private let validIntegerRange = Int64(-999_999_999_999_999) ... Int64(999_999_999_999_999)
/// A `StructuredFieldSerializer` is the basic parsing object for structured header fields.
public struct StructuredFieldSerializer {
/// A `StructuredFieldValueSerializer` is the basic parsing object for structured header field values.
public struct StructuredFieldValueSerializer {
private var data: [UInt8]
public init() {
@@ -23,14 +23,14 @@ public struct StructuredFieldSerializer {
}
}
extension StructuredFieldSerializer {
/// Writes a structured headers dictionary header field.
extension StructuredFieldValueSerializer {
/// Writes a structured dictionary header field value.
///
/// - parameters:
/// - root: The dictionary object.
/// - throws: If the dictionary could not be serialized.
/// - returns: The bytes of the serialized header field.
public mutating func writeDictionaryHeader(_ root: OrderedMap<String, ItemOrInnerList>) throws -> [UInt8] {
/// - returns: The bytes of the serialized header field value.
public mutating func writeDictionaryFieldValue(_ root: OrderedMap<String, ItemOrInnerList>) throws -> [UInt8] {
guard root.count > 0 else {
return []
}
@@ -42,13 +42,13 @@ extension StructuredFieldSerializer {
return self.data
}
/// Writes a structured headers list header field.
/// Writes a structured list header field value.
///
/// - parameters:
/// - root: The list object.
/// - throws: If the list could not be serialized.
/// - returns: The bytes of the serialized header field.
public mutating func writeListHeader(_ list: [ItemOrInnerList]) throws -> [UInt8] {
/// - returns: The bytes of the serialized header field value.
public mutating func writeListFieldValue(_ list: [ItemOrInnerList]) throws -> [UInt8] {
guard list.count > 0 else {
return []
}
@@ -60,13 +60,13 @@ extension StructuredFieldSerializer {
return self.data
}
/// Writes a structured headers item header field.
/// Writes a structured item header field value.
///
/// - parameters:
/// - root: The item.
/// - throws: If the item could not be serialized.
/// - returns: The bytes of the serialized header field.
public mutating func writeItemHeader(_ item: Item) throws -> [UInt8] {
/// - returns: The bytes of the serialized header field value.
public mutating func writeItemFieldValue(_ item: Item) throws -> [UInt8] {
defer {
self.data.removeAll(keepingCapacity: true)
}
@@ -75,7 +75,7 @@ extension StructuredFieldSerializer {
}
}
extension StructuredFieldSerializer {
extension StructuredFieldValueSerializer {
private mutating func serializeADictionary(_ dictionary: OrderedMap<String, ItemOrInnerList>) throws {
for (name, value) in dictionary {
try self.serializeAKey(name)
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
struct BareInnerListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var list: BareInnerList
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
struct BareItemDecoder {
private var item: BareItem
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
struct DictionaryKeyedContainer<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var dictionary: OrderedMap<String, ItemOrInnerList>
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
private let keyedInnerListDecoderSupportedKeys = ["items", "parameters"]
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
private let keyedItemDecoderSupportedKeys = ["item", "parameters"]
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
private let keyedTopLevelListDecoderSupportedKeys = ["items"]
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
struct ParametersDecoder<Key: CodingKey, BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var parameters: OrderedMap<String, BareItem>
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,18 +12,18 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
/// A `StructuredFieldDecoder` allows decoding `Decodable` objects from a HTTP
/// A `StructuredFieldValueDecoder` allows decoding `Decodable` objects from a HTTP
/// structured header field.
public struct StructuredFieldDecoder {
public struct StructuredFieldValueDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
public var keyDecodingStrategy: KeyDecodingStrategy?
public init() {}
}
extension StructuredFieldDecoder {
extension StructuredFieldValueDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
public struct KeyDecodingStrategy: Hashable {
fileprivate enum Base: Hashable {
@@ -38,7 +38,7 @@ extension StructuredFieldDecoder {
}
}
extension StructuredFieldDecoder {
extension StructuredFieldValueDecoder {
/// Attempt to decode an object from a structured header field.
///
/// - parameters:
@@ -46,7 +46,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 decode<StructuredField: StructuredHeaderField, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8 {
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)
@@ -65,7 +65,7 @@ extension StructuredFieldDecoder {
/// - 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 = StructuredFieldParser(data)
let parser = StructuredFieldValueParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseDictionaryField()
return try type.init(from: decoder)
@@ -79,7 +79,7 @@ extension StructuredFieldDecoder {
/// - 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 = StructuredFieldParser(data)
let parser = StructuredFieldValueParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseListField()
return try type.init(from: decoder)
@@ -93,7 +93,7 @@ extension StructuredFieldDecoder {
/// - 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 = StructuredFieldParser(data)
let parser = StructuredFieldValueParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseItemField()
@@ -112,15 +112,15 @@ extension StructuredFieldDecoder {
}
class _StructuredFieldDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var parser: StructuredFieldParser<BaseData>
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: StructuredFieldDecoder.KeyDecodingStrategy?
var keyDecodingStrategy: StructuredFieldValueDecoder.KeyDecodingStrategy?
init(_ parser: StructuredFieldParser<BaseData>, keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?) {
init(_ parser: StructuredFieldValueParser<BaseData>, keyDecodingStrategy: StructuredFieldValueDecoder.KeyDecodingStrategy?) {
self.parser = parser
self._codingStack = []
self.keyDecodingStrategy = keyDecodingStrategy
@@ -194,7 +194,7 @@ extension _StructuredFieldDecoder: Decoder {
func parseDictionaryField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseDictionaryField()
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)))
@@ -202,7 +202,7 @@ extension _StructuredFieldDecoder: Decoder {
func parseListField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseListField()
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)))
@@ -210,7 +210,7 @@ extension _StructuredFieldDecoder: Decoder {
func parseItemField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseItemField()
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)))
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -11,7 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import StructuredHeaders
import RawStructuredFieldValues
struct _StructuredHeaderCodingKey: CodingKey {
var stringValue: String
@@ -27,7 +27,7 @@ struct _StructuredHeaderCodingKey: CodingKey {
self.intValue = intValue
}
init<Key: CodingKey>(_ key: Key, keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?) {
init<Key: CodingKey>(_ key: Key, keyDecodingStrategy: StructuredFieldValueDecoder.KeyDecodingStrategy?) {
switch keyDecodingStrategy {
case .none:
self.stringValue = key.stringValue
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
struct TopLevelListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8 {
private var list: [ItemOrInnerList]
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -11,7 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import StructuredHeaders
import RawStructuredFieldValues
/// This object translates between the keys used by the encoder and the keys used by the encoding object.
///
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -11,7 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import StructuredHeaders
import RawStructuredFieldValues
/// This object translates between the unkeyed coding API and methods on the encoder.
///
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,17 +12,17 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
/// A `StructuredFieldEncoder` allows encoding `Encodable` objects to the format of a HTTP
/// A `StructuredFieldValueEncoder` allows encoding `Encodable` objects to the format of a HTTP
/// structured header field.
public struct StructuredFieldEncoder {
public struct StructuredFieldValueEncoder {
public var keyEncodingStrategy: KeyEncodingStrategy?
public init() {}
}
extension StructuredFieldEncoder {
extension StructuredFieldValueEncoder {
/// A strategy that should be used to map coding keys to wire format keys.
public struct KeyEncodingStrategy: Hashable {
fileprivate enum Base: Hashable {
@@ -37,14 +37,14 @@ extension StructuredFieldEncoder {
}
}
extension StructuredFieldEncoder {
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: StructuredHeaderField>(_ data: StructuredField) throws -> [UInt8] {
public func encode<StructuredField: StructuredFieldValue>(_ data: StructuredField) throws -> [UInt8] {
switch StructuredField.structuredFieldType {
case .item:
return try self.encodeItemField(data)
@@ -62,7 +62,7 @@ extension StructuredFieldEncoder {
/// - 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 = StructuredFieldSerializer()
let serializer = StructuredFieldValueSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeDictionaryField(data)
}
@@ -74,7 +74,7 @@ extension StructuredFieldEncoder {
/// - 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 = StructuredFieldSerializer()
let serializer = StructuredFieldValueSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeListField(data)
}
@@ -86,14 +86,14 @@ extension StructuredFieldEncoder {
/// - 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 = StructuredFieldSerializer()
let serializer = StructuredFieldValueSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeItemField(data)
}
}
class _StructuredFieldEncoder {
private var serializer: StructuredFieldSerializer
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.
@@ -101,9 +101,9 @@ class _StructuredFieldEncoder {
private var currentStackEntry: CodingStackEntry
internal var keyEncodingStrategy: StructuredFieldEncoder.KeyEncodingStrategy?
internal var keyEncodingStrategy: StructuredFieldValueEncoder.KeyEncodingStrategy?
init(_ serializer: StructuredFieldSerializer, keyEncodingStrategy: StructuredFieldEncoder.KeyEncodingStrategy?) {
init(_ serializer: StructuredFieldValueSerializer, keyEncodingStrategy: StructuredFieldValueEncoder.KeyEncodingStrategy?) {
self.serializer = serializer
self._codingPath = []
self.keyEncodingStrategy = keyEncodingStrategy
@@ -116,7 +116,7 @@ class _StructuredFieldEncoder {
switch self.currentStackEntry.storage {
case .dictionary(let map):
return try self.serializer.writeDictionaryHeader(map)
return try self.serializer.writeDictionaryFieldValue(map)
case .dictionaryHeader:
// No encoding happened.
return []
@@ -132,7 +132,7 @@ class _StructuredFieldEncoder {
switch self.currentStackEntry.storage {
case .list(let list):
return try self.serializer.writeListHeader(list)
return try self.serializer.writeListFieldValue(list)
case .listHeader:
// No encoding happened
return []
@@ -161,7 +161,7 @@ class _StructuredFieldEncoder {
switch self.currentStackEntry.storage {
case .item(let item):
return try self.serializer.writeItemHeader(Item(item))
return try self.serializer.writeItemFieldValue(Item(item))
case .itemHeader:
// No encoding happened
return []
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,17 +12,17 @@
//
//===----------------------------------------------------------------------===//
/// A `StructuredHeaderField` is a `Codable` representation of a HTTP Structured
/// 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 StructuredHeaderField: Codable {
static var structuredFieldType: StructuredHeaderFieldType { get }
public protocol StructuredFieldValue: Codable {
static var structuredFieldType: StructuredFieldType { get }
}
/// The kinds of header fields used in HTTP Structured Headers.
public enum StructuredHeaderFieldType {
public enum StructuredFieldType {
/// An item field consists of a single item, optionally with parameters.
case item
+6 -6
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -13,7 +13,7 @@
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
struct Flags {
var headerType: HeaderType
@@ -184,16 +184,16 @@ func main() {
}
}
data = data[...index]
var parser = StructuredFieldParser(data)
var parser = StructuredFieldValueParser(data)
let result: Header
switch flags.headerType {
case .dictionary:
result = .dictionary(try parser.parseDictionaryField())
result = .dictionary(try parser.parseDictionaryFieldValue())
case .list:
result = .list(try parser.parseListField())
result = .list(try parser.parseListFieldValue())
case .item:
result = .item(try parser.parseItemField())
result = .item(try parser.parseItemFieldValue())
}
result.prettyPrint()
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -11,9 +11,9 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CodableStructuredHeaders
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
import StructuredFieldValues
import XCTest
struct ListyDictionaryFieldParameters: Codable, Equatable {
@@ -31,8 +31,8 @@ struct ListyDictionaryParameterisedList: Codable, Equatable {
var parameters: ListyDictionaryFieldParameters
}
struct ItemField<Base: Codable & Equatable>: StructuredHeaderField, Equatable {
static var structuredFieldType: StructuredHeaderFieldType {
struct ItemField<Base: Codable & Equatable>: StructuredFieldValue, Equatable {
static var structuredFieldType: StructuredFieldType {
.item
}
@@ -43,8 +43,8 @@ struct ItemField<Base: Codable & Equatable>: StructuredHeaderField, Equatable {
}
}
struct List<Base: Codable & Equatable>: StructuredHeaderField, Equatable {
static var structuredFieldType: StructuredHeaderFieldType {
struct List<Base: Codable & Equatable>: StructuredFieldValue, Equatable {
static var structuredFieldType: StructuredFieldType {
.list
}
@@ -55,8 +55,8 @@ struct List<Base: Codable & Equatable>: StructuredHeaderField, Equatable {
}
}
struct DictionaryField<Key: Codable & Hashable, Value: Codable & Equatable>: StructuredHeaderField, Equatable {
static var structuredFieldType: StructuredHeaderFieldType {
struct DictionaryField<Key: Codable & Hashable, Value: Codable & Equatable>: StructuredFieldValue, Equatable {
static var structuredFieldType: StructuredFieldType {
.dictionary
}
@@ -78,8 +78,8 @@ struct DictionaryField<Key: Codable & Hashable, Value: Codable & Equatable>: Str
/// 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: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct ListyDictionaryField: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
var primary: ListyDictionaryParameterisedString
var secondary: ListyDictionaryParameterisedString
@@ -89,7 +89,7 @@ struct ListyDictionaryField: StructuredHeaderField, Equatable {
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 parsed = try StructuredFieldValueDecoder().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")),
@@ -99,15 +99,15 @@ final class StructuredFieldDecoderTests: XCTestCase {
}
func testCanDecodeParameterisedItemsWithoutParameters() throws {
struct ListyDictionaryNoParams: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct ListyDictionaryNoParams: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
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 parsed = try StructuredFieldValueDecoder().decode(ListyDictionaryNoParams.self, from: Array(headerField.utf8))
let expected = ListyDictionaryNoParams(primary: "bar", secondary: "baz", acceptablejurisdictions: ["AU", "GB", "FR"])
XCTAssertEqual(parsed, expected)
}
@@ -115,16 +115,16 @@ final class StructuredFieldDecoderTests: XCTestCase {
func testCanDecodeIntegersInVariousWays() throws {
let headerField = "5;bar=baz"
XCTAssertEqual(ItemField(UInt8(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int8(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt16(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int16(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt32(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int32(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt64(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int64(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int(5)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt8(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int8(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt16(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int16(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt32(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int32(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt64(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int64(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(UInt(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Int(5)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
}
func testOutOfRangeNumbersAreReported() throws {
@@ -135,44 +135,44 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "-999999999999999;bar=baz"
let expected = ItemField(Int64(-999_999_999_999_999))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt64>.self, from: Array(headerField.utf8)))
XCTAssertEqual(expected, try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt64>.self, from: Array(headerField.utf8)))
XCTAssertEqual(expected, try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
}
func testDoubleAndFloatInterchangeable() throws {
let headerField = "5.0;bar=baz"
XCTAssertEqual(ItemField(Float(5.0)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Double(5.0)), try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Float(5.0)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(ItemField(Double(5.0)), try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
}
func testAskingForTheWrongType() throws {
let headerField = "gzip"
let intField = "5"
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Int64>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<UInt64>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Double>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Float>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<Bool>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(ItemField<String>.self, from: Array(intField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt8>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt16>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt32>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Int64>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<UInt64>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Double>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Float>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<Bool>.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(ItemField<String>.self, from: Array(intField.utf8)))
}
func testDecodingTopLevelItemWithParameters() throws {
struct IntWithParams: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct IntWithParams: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int
var parameters: [String: String]
@@ -180,25 +180,25 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "5;bar=baz"
let expected = IntWithParams(item: 5, parameters: ["bar": "baz"])
XCTAssertEqual(expected, try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(expected, try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
}
func testDecodingTopLevelList() throws {
let headerField = "foo, bar, baz"
let expected = List(["foo", "bar", "baz"])
XCTAssertEqual(expected, try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
XCTAssertEqual(expected, try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8)))
}
func testDecodingLowercaseKeyStrategy() throws {
struct Camel: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct Camel: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
var hasHump: Bool
}
let headerField = "hashump"
let expected = Camel(hasHump: true)
var decoder = StructuredFieldDecoder()
var decoder = StructuredFieldValueDecoder()
decoder.keyDecodingStrategy = .lowercase
XCTAssertEqual(expected, try decoder.decode(from: Array(headerField.utf8)))
@@ -209,8 +209,8 @@ final class StructuredFieldDecoderTests: XCTestCase {
var hasHump: Bool
}
struct Camel: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Camel: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: String
var parameters: CamelParameters
@@ -218,43 +218,43 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "dromedary;hashump"
let expected = Camel(item: "dromedary", parameters: .init(hasHump: true))
var decoder = StructuredFieldDecoder()
var decoder = StructuredFieldValueDecoder()
decoder.keyDecodingStrategy = .lowercase
XCTAssertEqual(expected, try decoder.decode(from: Array(headerField.utf8)))
}
func testDecodingKeyMissingFromDictionary() throws {
struct MissingKey: StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct MissingKey: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .dictionary
var foo: Int
}
let headerField = "bar=baz"
XCTAssertThrowsError(try StructuredFieldDecoder().decode(MissingKey.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(MissingKey.self, from: Array(headerField.utf8)))
}
func testDecodingKeyAsItemWantedInnerList() throws {
struct MissingInnerList: StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct MissingInnerList: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .dictionary
var innerlist: [String]
}
let headerField = "innerlist=x"
XCTAssertThrowsError(try StructuredFieldDecoder().decode(MissingInnerList.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldValueDecoder().decode(MissingInnerList.self, from: Array(headerField.utf8)))
}
func testDecodingBinaryAsTopLevelData() throws {
let headerField = ":AQIDBA==:"
XCTAssertEqual(
ItemField(Data([1, 2, 3, 4])),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
func testDecodingBinaryAsParameterisedData() throws {
struct Item: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Item: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Data
var parameters: [String: Float]
}
@@ -264,18 +264,18 @@ final class StructuredFieldDecoderTests: XCTestCase {
XCTAssertEqual(
Item(item: Data([1, 2, 3, 4]), parameters: [:]),
try StructuredFieldDecoder().decode(Item.self, from: Array(headerFieldNoParameters.utf8))
try StructuredFieldValueDecoder().decode(Item.self, from: Array(headerFieldNoParameters.utf8))
)
XCTAssertEqual(
Item(item: Data([1, 2, 3, 4]), parameters: ["q": 0.8]),
try StructuredFieldDecoder().decode(Item.self, from: Array(headerFieldParameters.utf8))
try StructuredFieldValueDecoder().decode(Item.self, from: Array(headerFieldParameters.utf8))
)
}
func testDecodingBinaryInParameterField() throws {
struct Item: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Item: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int
var parameters: [String: Data]
}
@@ -283,7 +283,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "1;q=:AQIDBA==:"
XCTAssertEqual(
Item(item: 1, parameters: ["q": Data([1, 2, 3, 4])]),
try StructuredFieldDecoder().decode(Item.self, from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(Item.self, from: Array(headerField.utf8))
)
}
@@ -291,7 +291,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = ":AQIDBA==:, :BQYHCA==:"
XCTAssertEqual(
List([Data([1, 2, 3, 4]), Data([5, 6, 7, 8])]),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
@@ -299,7 +299,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = ":AQIDBA==:, :BQYHCA==:"
XCTAssertEqual(
List([Data([1, 2, 3, 4]), Data([5, 6, 7, 8])]),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
@@ -307,7 +307,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "(:AQIDBA==: :BQYHCA==:), (:AQIDBA==: :BQYHCA==:)"
XCTAssertEqual(
List(Array(repeating: [Data([1, 2, 3, 4]), Data([5, 6, 7, 8])], count: 2)),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
@@ -319,13 +319,13 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "(:AQIDBA==: :BQYHCA==:);foo, (:AQIDBA==: :BQYHCA==:);foo"
XCTAssertEqual(
List(Array(repeating: ListField(items: [Data([1, 2, 3, 4]), Data([5, 6, 7, 8])], parameters: ["foo": true]), count: 2)),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
func testDecodingBinaryInDictionaries() throws {
struct DictionaryField: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct DictionaryField: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
var bin: Data
var box: Data
}
@@ -333,7 +333,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "bin=:AQIDBA==:, box=:AQIDBA==:"
XCTAssertEqual(
DictionaryField(bin: Data([1, 2, 3, 4]), box: Data([1, 2, 3, 4])),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
@@ -341,13 +341,13 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "987654321.123"
XCTAssertEqual(
ItemField(Decimal(string: "987654321.123")!),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
func testDecodingDecimalAsParameterisedData() throws {
struct Item: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Item: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Decimal
var parameters: [String: Float]
}
@@ -357,18 +357,18 @@ final class StructuredFieldDecoderTests: XCTestCase {
XCTAssertEqual(
Item(item: Decimal(string: "987654321.123")!, parameters: [:]),
try StructuredFieldDecoder().decode(from: Array(headerFieldNoParameters.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerFieldNoParameters.utf8))
)
XCTAssertEqual(
Item(item: Decimal(string: "987654321.123")!, parameters: ["q": 0.8]),
try StructuredFieldDecoder().decode(from: Array(headerFieldParameters.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerFieldParameters.utf8))
)
}
func testDecodingDecimalInParameterField() throws {
struct Item: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Item: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int
var parameters: [String: Decimal]
}
@@ -376,7 +376,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "1;q=987654321.123"
XCTAssertEqual(
Item(item: 1, parameters: ["q": Decimal(string: "987654321.123")!]),
try StructuredFieldDecoder().decode(Item.self, from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(Item.self, from: Array(headerField.utf8))
)
}
@@ -384,7 +384,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "987654321.123, 123456789.321"
XCTAssertEqual(
List([Decimal(string: "987654321.123")!, Decimal(string: "123456789.321")!]),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
@@ -392,7 +392,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "(987654321.123 123456789.321), (987654321.123 123456789.321)"
XCTAssertEqual(
List(Array(repeating: [Decimal(string: "987654321.123")!, Decimal(string: "123456789.321")!], count: 2)),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
@@ -404,13 +404,13 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "(987654321.123 123456789.321);foo, (987654321.123 123456789.321);foo"
XCTAssertEqual(
List(Array(repeating: ListField(items: [Decimal(string: "987654321.123")!, Decimal(string: "123456789.321")!], parameters: ["foo": true]), count: 2)),
try StructuredFieldDecoder().decode(from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(from: Array(headerField.utf8))
)
}
func testDecodingDecimalInDictionaries() throws {
struct DictionaryField: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct DictionaryField: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
var bin: Decimal
var box: Decimal
}
@@ -418,7 +418,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
let headerField = "bin=987654321.123, box=123456789.321"
XCTAssertEqual(
DictionaryField(bin: Decimal(string: "987654321.123")!, box: Decimal(string: "123456789.321")!),
try StructuredFieldDecoder().decode(DictionaryField.self, from: Array(headerField.utf8))
try StructuredFieldValueDecoder().decode(DictionaryField.self, from: Array(headerField.utf8))
)
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -11,16 +11,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import CodableStructuredHeaders
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
import StructuredFieldValues
import XCTest
final class StructuredFieldEncoderTests: XCTestCase {
func testSimpleItemHeaderEncodeBareItem() throws {
// We're going to try encoding a few bare items as item headers to confirm
// that functions.
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
// Bool
XCTAssertEqual(Array("?1".utf8), try encoder.encode(ItemField(true)))
@@ -45,8 +45,8 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testEncodeKeyedItemHeader() throws {
struct KeyedItem<ItemType: Codable & Equatable>: Equatable, StructuredHeaderField {
static var structuredFieldType: StructuredHeaderFieldType {
struct KeyedItem<ItemType: Codable & Equatable>: Equatable, StructuredFieldValue {
static var structuredFieldType: StructuredFieldType {
.item
}
@@ -54,7 +54,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: [String: Bool]
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
// Bool
XCTAssertEqual(Array("?1;x".utf8), try encoder.encode(KeyedItem(item: true, parameters: ["x": true])))
@@ -85,13 +85,13 @@ final class StructuredFieldEncoderTests: XCTestCase {
var q: Float?
}
struct Field: Equatable, StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Field: Equatable, StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .item
var item: String
var parameters: Parameters
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertEqual(Array("gzip;x;q=0.8".utf8), try encoder.encode(Field(item: "gzip", parameters: Parameters(x: true, q: 0.8))))
XCTAssertEqual(Array("deflate;q=0.6".utf8), try encoder.encode(Field(item: "deflate", parameters: Parameters(x: nil, q: 0.6))))
@@ -99,10 +99,10 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testEncodeSimpleDictionary() throws {
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
struct DictionaryField: StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct DictionaryField: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .dictionary
var x: Bool
var y: Bool
}
@@ -118,19 +118,19 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: [String: Float]
}
struct DictionaryField: StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct DictionaryField: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .dictionary
var x: Field
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertEqual(Array("x=66;q=0.8".utf8),
try encoder.encode(DictionaryField(x: Field(item: 66, parameters: ["q": 0.8]))))
}
func testSimpleListField() throws {
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
// Bool
XCTAssertEqual(Array("?1, ?0, ?1".utf8),
@@ -158,7 +158,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
var item: String
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let header = [Item(parameters: ["q": 0.8], item: "gzip"),
Item(parameters: ["q": 0.6], item: "deflate")]
@@ -176,7 +176,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: Parameters
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let header = [Item(item: "gzip", parameters: Parameters(q: 0.8)),
Item(item: "deflate", parameters: Parameters(q: nil))]
@@ -185,7 +185,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testListFieldInnerListsBare() throws {
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let header = [[1, 2, 3], [4, 5, 6]]
XCTAssertEqual(Array("(1 2 3), (4 5 6)".utf8), try encoder.encode(List(header)))
}
@@ -196,7 +196,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: [String: String]
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let header = [Integers(items: [1, 2, 3], parameters: ["early": "yes"]),
Integers(items: [4, 5, 6], parameters: ["early": "no"])]
XCTAssertEqual(Array("(1 2 3);early=yes, (4 5 6);early=no".utf8), try encoder.encode(List(header)))
@@ -208,7 +208,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: [String: Bool]
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let header = [
[
Item(item: 1, parameters: ["odd": true]),
@@ -242,7 +242,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: FieldParams
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let header = [
Fields(
items: [
@@ -264,14 +264,14 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testDictionaryFieldWithSimpleInnerLists() throws {
struct Field: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct Field: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
var name: String
var color: String?
var intensity: [Float]
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertEqual(Array("name=red, intensity=(1.0 0.0 0.0)".utf8),
try encoder.encode(Field(name: "red", color: nil, intensity: [1.0, 0.0, 0.0])))
}
@@ -286,12 +286,12 @@ final class StructuredFieldEncoderTests: XCTestCase {
var parameters: ColorParameters
}
struct Field: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct Field: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .dictionary
var green: Color
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let field = Field(
green: Color(items: [0.0, 1.0, 0.0], parameters: ColorParameters(name: "green"))
)
@@ -300,37 +300,37 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testEmptyListField() throws {
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertEqual([], try encoder.encode(List([] as [Int])))
}
func testEmptyDictionaryField() throws {
struct Field: StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct Field: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .dictionary
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertEqual([], try encoder.encode(Field()))
}
func testEmptyItemField() throws {
struct Field: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Field: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int?
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertEqual([], try encoder.encode(Field(item: nil)))
XCTAssertThrowsError(try encoder.encode(List([Field(item: nil)])))
XCTAssertThrowsError(try encoder.encode(DictionaryField(["x": Field(item: nil)])))
}
func testForbidEmptyItemWithActualParameters() throws {
struct Field: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Field: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int?
var parameters: [String: Int]
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let badField = Field(item: nil, parameters: ["x": 0])
XCTAssertThrowsError(try encoder.encode(badField))
XCTAssertThrowsError(try encoder.encode(List([badField])))
@@ -338,14 +338,14 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testForbidItemWithExtraField() throws {
struct Field: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Field: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int
var parameters: [String: Int]
var other: Bool
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let badField = Field(item: 1, parameters: ["x": 0], other: true)
XCTAssertThrowsError(try encoder.encode(badField))
XCTAssertThrowsError(try encoder.encode(List([badField])))
@@ -353,12 +353,12 @@ final class StructuredFieldEncoderTests: XCTestCase {
}
func testForbidJustParameters() throws {
struct Field: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct Field: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var parameters: [String: Int]
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
let badField = Field(parameters: ["x": 0])
XCTAssertThrowsError(try encoder.encode(badField))
XCTAssertThrowsError(try encoder.encode(List([badField])))
@@ -369,18 +369,18 @@ final class StructuredFieldEncoderTests: XCTestCase {
struct Field: Codable, Equatable {
var items: Int?
}
let encoder = StructuredFieldEncoder()
let encoder = StructuredFieldValueEncoder()
XCTAssertThrowsError(try encoder.encode(List([Field(items: nil)])))
XCTAssertThrowsError(try encoder.encode(DictionaryField(["x": Field(items: nil)])))
}
func testLowercaseKeysOnDictionaries() throws {
struct DictionaryField: StructuredHeaderField {
static let structuredFieldType: StructuredHeaderFieldType = .dictionary
struct DictionaryField: StructuredFieldValue {
static let structuredFieldType: StructuredFieldType = .dictionary
var allowAll: Bool
}
let noStrategyEncoder = StructuredFieldEncoder()
let noStrategyEncoder = StructuredFieldValueEncoder()
XCTAssertThrowsError(try noStrategyEncoder.encode(DictionaryField(allowAll: false)))
var lowercaseEncoder = noStrategyEncoder
@@ -394,19 +394,19 @@ final class StructuredFieldEncoderTests: XCTestCase {
var allowAll: Bool
}
struct ItemField: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .item
struct ItemField: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .item
var item: Int
var parameters: Parameters
}
struct ListField: StructuredHeaderField, Equatable {
static let structuredFieldType: StructuredHeaderFieldType = .list
struct ListField: StructuredFieldValue, Equatable {
static let structuredFieldType: StructuredFieldType = .list
var items: [Int]
var parameters: Parameters
}
let noStrategyEncoder = StructuredFieldEncoder()
let noStrategyEncoder = StructuredFieldValueEncoder()
var lowercaseEncoder = noStrategyEncoder
lowercaseEncoder.keyEncodingStrategy = .lowercase
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
import XCTest
enum FixtureTestError: Error {
@@ -171,16 +171,16 @@ final class StructuredFieldParserTests: XCTestCase {
let joinedHeaders = Array(raw.joined(separator: ", ").utf8)
do {
var parser = StructuredFieldParser(joinedHeaders)
var parser = StructuredFieldValueParser(joinedHeaders)
let testResult: TestResult
switch fixture.headerType {
case "dictionary":
testResult = try .dictionary(parser.parseDictionaryField())
testResult = try .dictionary(parser.parseDictionaryFieldValue())
case "list":
testResult = try .list(parser.parseListField())
testResult = try .list(parser.parseListFieldValue())
case "item":
testResult = try .item(parser.parseItemField())
testResult = try .item(parser.parseItemFieldValue())
default:
XCTFail("\(fixture.name): Unexpected header type \(fixture.headerType)")
return
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import StructuredHeaders
import RawStructuredFieldValues
import XCTest
final class StructuredFieldSerializerTests: XCTestCase {
@@ -36,16 +36,16 @@ final class StructuredFieldSerializerTests: XCTestCase {
return
}
var serializer = StructuredFieldSerializer()
var serializer = StructuredFieldValueSerializer()
let result: [UInt8]
switch toSerialize {
case .dictionary(let dictionary):
result = try serializer.writeDictionaryHeader(dictionary)
result = try serializer.writeDictionaryFieldValue(dictionary)
case .list(let list):
result = try serializer.writeListHeader(list)
result = try serializer.writeListFieldValue(list)
case .item(let item):
result = try serializer.writeItemHeader(item)
result = try serializer.writeItemFieldValue(item)
}
if fixture.mustFail == true || fixture.canFail == true {
@@ -69,22 +69,22 @@ final class StructuredFieldSerializerTests: XCTestCase {
let joinedHeaders = Array(raw.joined(separator: ", ").utf8)
do {
var parser = StructuredFieldParser(joinedHeaders)
var parser = StructuredFieldValueParser(joinedHeaders)
let testResult: TestResult
switch fixture.headerType {
case "dictionary":
testResult = try .dictionary(parser.parseDictionaryField())
testResult = try .dictionary(parser.parseDictionaryFieldValue())
case "list":
testResult = try .list(parser.parseListField())
testResult = try .list(parser.parseListFieldValue())
case "item":
testResult = try .item(parser.parseItemField())
testResult = try .item(parser.parseItemFieldValue())
default:
XCTFail("\(fixture.name): Unexpected header type \(fixture.headerType)")
return
}
var serializer = StructuredFieldSerializer()
var serializer = StructuredFieldValueSerializer()
let serialized: [UInt8]
let canonicalJoinedHeaders: [UInt8]
@@ -96,11 +96,11 @@ final class StructuredFieldSerializerTests: XCTestCase {
switch testResult {
case .dictionary(let result):
serialized = try serializer.writeDictionaryHeader(result)
serialized = try serializer.writeDictionaryFieldValue(result)
case .list(let list):
serialized = try serializer.writeListHeader(list)
serialized = try serializer.writeListFieldValue(list)
case .item(let item):
serialized = try serializer.writeItemHeader(item)
serialized = try serializer.writeItemFieldValue(item)
}
XCTAssertEqual(canonicalJoinedHeaders, serialized, "\(fixture.name): Header serialization mismatch: expected \(String(decoding: canonicalJoinedHeaders, as: UTF8.self)), got \(String(decoding: serialized, as: UTF8.self))")
+2 -2
View File
@@ -3,7 +3,7 @@
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
## Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
@@ -17,7 +17,7 @@ set -eu
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
function replace_acceptable_years() {
# this needs to replace all acceptable forms with 'YEARS'
sed -e 's/2020/YEARS/'
sed -e 's/2020-2021/YEARS/' -e 's/202[01]/YEARS/'
}