Add docs and license

This commit is contained in:
Cory Benfield committed 2020-07-16 16:34:38 +01:00
1 parent b797a6ff50
commit e12def54da
10 files changed
+420 -7

No files matched your search

+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1 -1
View File
@@ -15,7 +15,7 @@
import PackageDescription
let package = Package(
name: "swift-structured-headers",
name: "swift-http-structured-headers",
products: [
.library(
name: "StructuredHeaders",
+99 -2
View File
@@ -1,3 +1,100 @@
# swift-structured-headers
# swift-http-structured-headers
A description of this package.
A Swift implementation of the HTTP Structured Header Field 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.
## About Structured Header Fields
HTTP Structured Header fields are [a draft specification](https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-19) being worked on by the IETF. 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
This package provides a parser and serializer that match draft 19 of the working group's draft specification. 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 two top-level modules: `StructuredHeaders` and `CodableStructuredHeaders`.
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.
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.
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.
## Working with Structured Header Fields
`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 draft specification](https://tools.ietf.org/html/draft-ietf-httpbis-client-hints-15). 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.
>
> Accept-CH is a Structured Header. Its value MUST be an sf-list whose members are tokens. Its ABNF is:
>
> Accept-CH = sf-list
>
> For example:
>
> Accept-CH: Sec-CH-Example, Sec-CH-Example-2
`swift-http-structured-headers` can parse and serialize this field very simply:
```swift
let field = Array("Sec-CH-Example, Sec-CH-Example-2".utf8)
// Decoding
let decoder = StructuredFieldDecoder()
let parsed = try decoder.decodeListField([String].self, from: field)
// Encoding
let encoder = StructuredFieldEncoder()
let serialized = try encoder.encodeListField(["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:
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), or as Swift dictionaries.
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 `Array`s where the entries are items of some kind.
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.
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.
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.
## 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.
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.
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.
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:
```swift
let field = Array("Sec-CH-Example, Sec-CH-Example-2".utf8)
var parser = StructuredFieldParser(field)
let parsed = parser.parseListField()
print(parsed)
// [
// .item(Item(bareItem: .token("Sec-CH-Example"), parameters: [])),
// .item(Item(bareItem: .token("Sec-CH-Example-2"), parameters: [])),
// ]
var serializer = StructuredFieldSerializer()
let serialized = serializer.writeListHeader(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.
In general, users should consider this API only when they are confident they need either the flexibility or the performance. This may be valuable for header fields that do not evolve often, or that are highly dynamic.
@@ -14,13 +14,17 @@
import Foundation
import StructuredHeaders
/// A `StructuredFieldDecoder` allows decoding `Decodable` objects from a HTTP
/// structured header field.
public struct StructuredFieldDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
public var keyDecodingStrategy: KeyDecodingStrategy?
public init() { }
}
extension StructuredFieldDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
public struct KeyDecodingStrategy: Hashable {
fileprivate enum Base: Hashable {
case lowercase
@@ -35,12 +39,31 @@ extension StructuredFieldDecoder {
}
extension StructuredFieldDecoder {
/// Attempt to decode an object from a structured header field.
///
/// This method will attempt to guess what kind of structured header field is being
/// parsed based on the structure of `type`. This is useful for quick prototyping, but
/// generally this method should be avoided in favour of one of the other `decode`
/// methods on this type.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
public func decode<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
return try type.init(from: decoder)
}
/// Attempt to decode an object from a structured header dictionary field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
public func decodeDictionaryField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
@@ -48,6 +71,13 @@ extension StructuredFieldDecoder {
return try type.init(from: decoder)
}
/// Attempt to decode an object from a structured header list field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
public func decodeListField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
@@ -55,6 +85,13 @@ extension StructuredFieldDecoder {
return try type.init(from: decoder)
}
/// Attempt to decode an object from a structured header item field.
///
/// - parameters:
/// - type: The type of the object to decode.
/// - data: The bytes of the structured header field.
/// - throws: If the header field could not be parsed, or could not be decoded.
/// - returns: An object of type `StructuredField`.
public func decodeItemField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
@@ -14,6 +14,8 @@
import Foundation
import StructuredHeaders
/// A `StructuredFieldEncoder` allows encoding `Encodable` objects to the format of a HTTP
/// structured header field.
public struct StructuredFieldEncoder {
public var keyEncodingStrategy: KeyEncodingStrategy?
@@ -21,6 +23,7 @@ public struct StructuredFieldEncoder {
}
extension StructuredFieldEncoder {
/// A strategy that should be used to map coding keys to wire format keys.
public struct KeyEncodingStrategy: Hashable {
fileprivate enum Base: Hashable {
case lowercase
@@ -35,18 +38,36 @@ extension StructuredFieldEncoder {
}
extension StructuredFieldEncoder {
/// Attempt to encode an object into a structured header dictionary field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
public func encodeDictionaryField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
let serializer = StructuredFieldSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeDictionaryField(data)
}
/// Attempt to encode an object into a structured header list field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
public func encodeListField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
let serializer = StructuredFieldSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
return try encoder.encodeListField(data)
}
/// Attempt to encode an object into a structured header item field.
///
/// - parameters:
/// - data: The object to encode.
/// - throws: If the header field could not be encoded, or could not be serialized.
/// - returns: The bytes representing the HTTP structured header field.
public func encodeItemField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
let serializer = StructuredFieldSerializer()
let encoder = _StructuredFieldEncoder(serializer, keyEncodingStrategy: self.keyEncodingStrategy)
@@ -18,6 +18,8 @@
// They are not used by those using the Codable interface.
// MARK:- ItemOrInnerList
/// `ItemOrInnerList` represents the values in a structured header dictionary, or the
/// entries in a structured header list.
public enum ItemOrInnerList<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
case item(Item<BaseData>)
case innerList(InnerList<BaseData>)
@@ -26,12 +28,26 @@ public enum ItemOrInnerList<BaseData: RandomAccessCollection> where BaseData.Ele
extension ItemOrInnerList: Hashable { }
// MARK:- BareItem
/// `BareItem` is a representation of the base data types at the bottom of a structured
/// header field. These types are not parameterised: they are raw data.
public enum BareItem<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
/// A boolean item.
case bool(Bool)
/// An integer item.
case integer(Int)
/// A decimal item.
case decimal(PseudoDecimal)
/// A string item.
case string(String)
/// A byte sequence. This case must contain base64-encoded data, as
/// `StructuredHeaders` does not do base64 encoding or decoding.
case undecodedByteSequence(BaseData)
/// A token item.
case token(String)
}
@@ -66,8 +82,13 @@ extension BareItem: ExpressibleByStringLiteral {
extension BareItem: Hashable { }
// MARK:- Item
/// `Item` represents a structured header field item: a combination of a `bareItem`
/// and some parameters.
public struct Item<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
/// The `BareItem` that this `Item` contains.
public var bareItem: BareItem<BaseData>
/// The parameters associated with `bareItem`
public var parameters: OrderedMap<String, BareItem<BaseData>>
public init(bareItem: BareItem<BaseData>, parameters: OrderedMap<String, BareItem<BaseData>>) {
@@ -79,6 +100,8 @@ public struct Item<BaseData: RandomAccessCollection> where BaseData.Element == U
extension Item: Hashable { }
// MARK:- BareInnerList
/// A `BareInnerList` represents the items contained within an `InnerList`, without
/// the associated parameters.
public struct BareInnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
private var items: [Item<BaseData>]
@@ -150,8 +173,12 @@ extension BareInnerList.Index: Comparable {
}
// MARK:- InnerList
/// An `InnerList` is a list of items, with some associated parameters.
public struct InnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
/// The items contained within this inner list.
public var bareInnerList: BareInnerList<BaseData>
/// The parameters associated with the `bareInnerList`.
public var parameters: OrderedMap<String, BareItem<BaseData>>
public init(bareInnerList: BareInnerList<BaseData>, parameters: OrderedMap<String, BareItem<BaseData>>) {
@@ -161,6 +188,8 @@ public struct InnerList<BaseData: RandomAccessCollection>: Hashable where BaseDa
}
extension String {
/// Whether this string is a valid structured headers token, or whether it would
/// need to be stored in a structured headers string.
public var structuredHeadersIsValidToken: Bool {
let view = self.utf8
+1
View File
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
// MARK:- StructuredHeaderError
/// Errors that may be encountered when working with structured headers.
public struct StructuredHeaderError: Error {
private enum _BaseError: Hashable {
case invalidTrailingBytes
+10 -1
View File
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
/// A FieldParser is the basic parsing object for structured header fields represented as lists.
/// A `StructuredFieldParser` is the basic parsing object for structured header fields.
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.
@@ -37,6 +37,9 @@ extension StructuredFieldParser {
/// Parse the HTTP structured field as a list.
///
/// This is a straightforward implementation of the parser in the draft spec.
///
/// - throws: If the field could not be parsed.
/// - returns: An array of items or inner lists.
public mutating func parseListField() throws -> [ItemOrInnerList] {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
@@ -56,6 +59,9 @@ extension StructuredFieldParser {
}
/// Parse the HTTP structured header field as a dictionary.
///
/// - throws: If the field could not be parsed.
/// - returns: An `OrderedMap` corresponding to the entries in the dictionary.
public mutating func parseDictionaryField() throws -> OrderedMap<Key, ItemOrInnerList> {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
@@ -75,6 +81,9 @@ extension StructuredFieldParser {
}
/// Parse the HTTP structured header field as an item.
///
/// - throws: If the field could not be parsed.
/// - returns: The `Item` in the field.
public mutating func parseItemField() throws -> Item {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
@@ -14,8 +14,8 @@
fileprivate let validIntegerRange = Int64(-999999999999999)...Int64(999999999999999)
/// A `StructuredFieldSerializer` is the basic parsing object for structured header fields.
public struct StructuredFieldSerializer {
// TODO: Allow users to choose this.
private var data: [UInt8]
public init() {
@@ -24,7 +24,12 @@ public struct StructuredFieldSerializer {
}
extension StructuredFieldSerializer {
// TODO: decide if this is the best API, it forces allocations.
/// Writes a structured headers dictionary header field.
///
/// - 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<BaseData: RandomAccessCollection>(_ root: OrderedMap<String, ItemOrInnerList<BaseData>>) throws -> [UInt8] where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
guard root.count > 0 else {
return []
@@ -37,6 +42,12 @@ extension StructuredFieldSerializer {
return self.data
}
/// Writes a structured headers list header field.
///
/// - 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<BaseData: RandomAccessCollection>(_ list: [ItemOrInnerList<BaseData>]) throws -> [UInt8] where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
guard list.count > 0 else {
return []
@@ -49,6 +60,12 @@ extension StructuredFieldSerializer {
return self.data
}
/// Writes a structured headers item header field.
///
/// - parameters:
/// - root: The item.
/// - throws: If the item could not be serialized.
/// - returns: The bytes of the serialized header field.
public mutating func writeItemHeader<BaseData: RandomAccessCollection>(_ item: Item<BaseData>) throws -> [UInt8] where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
defer {
self.data.removeAll(keepingCapacity: true)
+1 -1
View File
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
/// OrderedMap is a data type that has associative-array properties, but that
/// `OrderedMap` is a data type that has associative-array properties, but that
/// maintains insertion order.
///
/// Our initial implementation takes advantage of the fact that the vast majority of