Merge pull request #23 from guoye-zhang/codable

Support Codable
This commit is contained in:
Guoye Zhang authored and GitHub committed 2023-08-17 15:37:47 -07:00
commit bd06898009
6 files changed
+315 -10

No files matched your search

+51 -6
View File
@@ -20,19 +20,33 @@ public struct HTTPField: Sendable, Hashable {
/// The strategy for whether the field is indexed in the HPACK or QPACK dynamic table.
public struct DynamicTableIndexingStrategy: Sendable, Hashable {
/// Default strategy.
public static var automatic: Self { .init(rawValue: 0) }
public static var automatic: Self { .init(uncheckedValue: 0) }
/// Always put this field in the dynamic table if possible.
public static var prefer: Self { .init(rawValue: 1) }
public static var prefer: Self { .init(uncheckedValue: 1) }
/// Don't put this field in the dynamic table.
public static var avoid: Self { .init(rawValue: 2) }
public static var avoid: Self { .init(uncheckedValue: 2) }
/// Don't put this field in the dynamic table, and set a flag to disallow intermediaries to
/// index this field.
public static var disallow: Self { .init(rawValue: 3) }
public static var disallow: Self { .init(uncheckedValue: 3) }
private let rawValue: UInt8
fileprivate let rawValue: UInt8
private static let maxRawValue: UInt8 = 3
private init(uncheckedValue: UInt8) {
assert(uncheckedValue <= Self.maxRawValue)
self.rawValue = uncheckedValue
}
fileprivate init?(rawValue: UInt8) {
if rawValue > Self.maxRawValue {
return nil
}
self.rawValue = rawValue
}
}
/// Create an HTTP field from a name and a value.
@@ -181,8 +195,39 @@ extension HTTPField: CustomPlaygroundDisplayConvertible {
}
}
extension HTTPField: Codable {
enum CodingKeys: String, CodingKey {
case name
case value
case indexingStrategy
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.name, forKey: .name)
try container.encode(self.rawValue._storage, forKey: .value)
if self.indexingStrategy != .automatic {
try container.encode(self.indexingStrategy.rawValue, forKey: .indexingStrategy)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let name = try container.decode(Name.self, forKey: .name)
let value = try container.decode(String.self, forKey: .value)
guard Self.isValidValue(value) else {
throw DecodingError.dataCorruptedError(forKey: .value, in: container, debugDescription: "HTTP field value \"\(value)\" contains invalid characters")
}
self.init(name: name, uncheckedValue: ISOLatin1String(unchecked: value))
if let indexingStrategyValue = try container.decodeIfPresent(UInt8.self, forKey: .indexingStrategy),
let indexingStrategy = DynamicTableIndexingStrategy(rawValue: indexingStrategyValue) {
self.indexingStrategy = indexingStrategy
}
}
}
extension HTTPField {
static func isValidToken(_ token: String) -> Bool {
static func isValidToken(_ token: some StringProtocol) -> Bool {
!token.isEmpty && token.utf8.allSatisfy {
switch $0 {
case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E:
+28
View File
@@ -52,6 +52,10 @@ extension HTTPField {
self.rawName = rawName
self.canonicalName = canonicalName
}
var isPseudo: Bool {
self.rawName.hasPrefix(":")
}
}
}
@@ -77,6 +81,30 @@ extension HTTPField.Name: CustomPlaygroundDisplayConvertible {
}
}
extension HTTPField.Name: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawName)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let nameString = try container.decode(String.self)
if nameString.hasPrefix(":") {
guard nameString.lowercased() == nameString,
HTTPField.isValidToken(nameString.dropFirst()) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "HTTP pseudo field name \"\(nameString)\" contains invalid characters")
}
self.init(rawName: nameString, canonicalName: nameString)
} else {
guard let name = Self(nameString) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "HTTP field name \"\(nameString)\" contains invalid characters")
}
self = name
}
}
}
extension HTTPField.Name {
static var method: Self { .init(rawName: ":method", canonicalName: ":method") }
static var scheme: Self { .init(rawName: ":scheme", canonicalName: ":scheme") }
+33 -2
View File
@@ -134,6 +134,7 @@ public struct HTTPFields: Sendable, Hashable {
}
func append(field: HTTPField) {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
let name = field.name.canonicalName
if var index = self.index?[name] {
while true {
@@ -146,6 +147,7 @@ public struct HTTPFields: Sendable, Hashable {
self.index?[name] = UInt16(self.fields.count)
}
self.fields.append((field, .max))
precondition(self.fields.count < UInt16.max, "Too many fields")
}
}
@@ -254,8 +256,10 @@ public struct HTTPFields: Sendable, Hashable {
extension HTTPFields: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (HTTPField.Name, String)...) {
for (name, value) in elements {
precondition(!name.isPseudo, "Pseudo header field \"\(name)\" disallowed")
self._storage.append(field: HTTPField(name: name, value: value))
}
precondition(self.count < UInt16.max, "Too many fields")
}
}
@@ -293,6 +297,7 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
self._storage = self._storage.copy()
}
if newValue.name != self._storage.fields[position].0.name {
precondition(!newValue.name.isPseudo, "Pseudo header field \"\(newValue.name)\" disallowed")
self._storage.index = nil
}
self._storage.fields[position].0 = newValue
@@ -303,13 +308,18 @@ extension HTTPFields: RangeReplaceableCollection, RandomAccessCollection, Mutabl
if !isKnownUniquelyReferenced(&self._storage) {
self._storage = self._storage.copy()
}
if subrange.startIndex == count {
if subrange.startIndex == self.count {
for field in newElements {
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
self._storage.append(field: field)
}
} else {
self._storage.index = nil
self._storage.fields.replaceSubrange(subrange, with: newElements.lazy.map { ($0, 0) })
self._storage.fields.replaceSubrange(subrange, with: newElements.lazy.map { field in
precondition(!field.name.isPseudo, "Pseudo header field \"\(field.name)\" disallowed")
return (field, 0)
})
precondition(self.count < UInt16.max, "Too many fields")
}
}
@@ -328,6 +338,27 @@ extension HTTPFields: CustomDebugStringConvertible {
}
}
extension HTTPFields: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(contentsOf: self)
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
if let count = container.count {
self.reserveCapacity(count)
}
while !container.isAtEnd {
let field = try container.decode(HTTPField.self)
guard !field.name.isPseudo else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Pseudo header field \"\(field)\" disallowed")
}
self.append(field)
}
}
}
extension Array {
// `removalIndices` must be ordered.
mutating func remove(at removalIndices: some Sequence<Index>) {
+91 -2
View File
@@ -43,7 +43,7 @@ public struct HTTPRequest: Sendable, Hashable {
self.init(rawValue)
}
private init(unchecked: String) {
fileprivate init(unchecked: String) {
self.rawValue = unchecked
}
@@ -57,7 +57,7 @@ public struct HTTPRequest: Sendable, Hashable {
/// A convenient way to access the value of the ":method" pseudo header field.
public var method: Method {
get {
Method(self.pseudoHeaderFields.method.rawValue._storage)!
Method(unchecked: self.pseudoHeaderFields.method.rawValue._storage)
}
set {
self.pseudoHeaderFields.method.rawValue = ISOLatin1String(unchecked: newValue.rawValue)
@@ -224,6 +224,95 @@ extension HTTPRequest: CustomDebugStringConvertible {
}
}
extension HTTPRequest.PseudoHeaderFields: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.method)
if let scheme = self.scheme {
try container.encode(scheme)
}
if let authority = self.authority {
try container.encode(authority)
}
if let path = self.path {
try container.encode(path)
}
if let extendedConnectProtocol = self.extendedConnectProtocol {
try container.encode(extendedConnectProtocol)
}
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var method: HTTPField?
var scheme: HTTPField?
var authority: HTTPField?
var path: HTTPField?
var extendedConnectProtocol: HTTPField?
while !container.isAtEnd {
let field = try container.decode(HTTPField.self)
switch field.name {
case .method:
guard method == nil else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Multiple \":method\" pseudo header fields")
}
method = field
case .scheme:
guard scheme == nil else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Multiple \":scheme\" pseudo header fields")
}
scheme = field
case .authority:
guard authority == nil else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Multiple \":authority\" pseudo header fields")
}
authority = field
case .path:
guard path == nil else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Multiple \":path\" pseudo header fields")
}
path = field
case .protocol:
guard extendedConnectProtocol == nil else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Multiple \":protocol\" pseudo header fields")
}
extendedConnectProtocol = field
default:
guard field.name.rawName.hasPrefix(":") else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "\"\(field)\" is not a pseudo header field")
}
}
}
guard let method else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "\":method\" pseudo header field is missing")
}
guard HTTPField.isValidToken(method.rawValue._storage) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "\"\(method.rawValue._storage)\" is not a valid method")
}
self.init(method: method, scheme: scheme, authority: authority, path: path,
extendedConnectProtocol: extendedConnectProtocol)
}
}
extension HTTPRequest: Codable {
enum CodingKeys: String, CodingKey {
case pseudoHeaderFields
case headerFields
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.pseudoHeaderFields, forKey: .pseudoHeaderFields)
try container.encode(self.headerFields, forKey: .headerFields)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.pseudoHeaderFields = try container.decode(PseudoHeaderFields.self, forKey: .pseudoHeaderFields)
self.headerFields = try container.decode(HTTPFields.self, forKey: .headerFields)
}
}
extension HTTPRequest.Method {
/// GET
public static var get: Self { .init(unchecked: "GET") }
+63
View File
@@ -205,6 +205,69 @@ extension HTTPResponse: CustomDebugStringConvertible {
}
}
extension HTTPResponse.PseudoHeaderFields: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.status)
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var status: HTTPField?
while !container.isAtEnd {
let field = try container.decode(HTTPField.self)
switch field.name {
case .status:
guard status == nil else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Multiple \":status\" pseudo header fields")
}
status = field
default:
guard field.name.rawName.hasPrefix(":") else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "\"\(field)\" is not a pseudo header field")
}
}
}
guard let status else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "\":status\" pseudo header field is missing")
}
guard HTTPResponse.Status.isValidStatus(status.rawValue._storage) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "\"\(status.rawValue._storage)\" is not a valid status code")
}
self.init(status: status)
}
}
extension HTTPResponse: Codable {
enum CodingKeys: String, CodingKey {
case pseudoHeaderFields
case headerFields
case reasonPhrase
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.pseudoHeaderFields, forKey: .pseudoHeaderFields)
try container.encode(self.reasonPhrase, forKey: .reasonPhrase)
try container.encode(self.headerFields, forKey: .headerFields)
}
private enum DecodingError: Error {
case invalidReasonPhrase(String)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.pseudoHeaderFields = try container.decode(PseudoHeaderFields.self, forKey: .pseudoHeaderFields)
let reasonPhrase = try container.decode(String.self, forKey: .reasonPhrase)
guard Status.isValidReasonPhrase(reasonPhrase) else {
throw DecodingError.invalidReasonPhrase(reasonPhrase)
}
self.reasonPhrase = reasonPhrase
self.headerFields = try container.decode(HTTPFields.self, forKey: .headerFields)
}
}
extension HTTPResponse.Status {
// MARK: 1xx
+49
View File
@@ -142,4 +142,53 @@ final class HTTPTypesTests: XCTestCase {
XCTAssertTrue(isSendable(status))
XCTAssertTrue(isSendable(responsePseudoHeaderFields))
}
func testRequestCoding() throws {
let request = HTTPRequest(method: .put, scheme: "https", authority: "www.example.com", path: "/upload", headerFields: [
.acceptEncoding: "br",
.acceptEncoding: "gzip",
.contentLength: "1024",
])
let encoded = try JSONEncoder().encode(request)
let json = try JSONSerialization.jsonObject(with: encoded)
XCTAssertEqual(json as? NSDictionary, [
"pseudoHeaderFields": [
["name": ":method", "value": "PUT"],
["name": ":scheme", "value": "https"],
["name": ":authority", "value": "www.example.com"],
["name": ":path", "value": "/upload"],
],
"headerFields": [
["name": "Accept-Encoding", "value": "br"],
["name": "Accept-Encoding", "value": "gzip"],
["name": "Content-Length", "value": "1024"],
]
])
let decoded = try JSONDecoder().decode(HTTPRequest.self, from: encoded)
XCTAssertEqual(request, decoded)
}
func testResponseCoding() throws {
var response = HTTPResponse(status: .noContent, headerFields: [
.server: "HTTPServer/1.0",
])
response.headerFields[0].indexingStrategy = .prefer
let encoded = try JSONEncoder().encode(response)
let json = try JSONSerialization.jsonObject(with: encoded)
XCTAssertEqual(json as? NSDictionary, [
"pseudoHeaderFields": [
["name": ":status", "value": "204"],
],
"reasonPhrase": "No Content",
"headerFields": [
["name": "Server", "value": "HTTPServer/1.0", "indexingStrategy": 1],
]
])
let decoded = try JSONDecoder().decode(HTTPResponse.self, from: encoded)
XCTAssertEqual(response, decoded)
}
}