mirror of
https://github.com/apple/swift-http-structured-headers
synced 2026-11-24 04:37:50 +00:00
Motivation: Early on in the design of Structured Headers I made a conscious effort to try to avoid transforming types in the low-level API. This design was built on the assumption that strings, tokens, and some other data types could be built entirely as slices of the backing data. Unfortunately, this isn't true: because of the need to escape chars in Strings, it became necessary to start using more complex types in Item. Eventually, we ended up in a place where the only field in Item that actually stored backing data was `.undecodedByteSequence`. This field forced almost the entire set of types in the StructuredHeaders module to be generic, just for the sake of carrying this one slice type around. This prevented powerful optimisations, bloated code size, and forced additional unnecessary heap allocations. It also forced us to constrain the types used in the parser to those where the subsequence type was Hashable, which excluded some really important types (like `String.UTF8View`). Fundamentally, this genericism was hurting more than it helped at this point, so I bit the bullet and replaced the slice type with `String` for `undecodedByteSequence`. This led to a huge cascading removal of generic type parameters for a wide range of types, as well as the removal of the "must have hashable subsequence" constraints on the parser data type. This lifts an enormous amount of complexity out of the module at the extremely minor cost of forcing an allocation whenever we have a lot of undecoded binary data: not a huge cost, in my view, and well worth what we got back in return. Modifications: - Remove generic type parameter in BaseItem. - Remove generic types everywhere else. - Remove hashable constraint. Result: Better, faster, simpler code.
207 lines
5.5 KiB
Swift
207 lines
5.5 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
import Foundation
|
|
import StructuredHeaders
|
|
|
|
struct Flags {
|
|
var headerType: HeaderType
|
|
|
|
init() {
|
|
// Default to item
|
|
self.headerType = .item
|
|
|
|
for argument in CommandLine.arguments.dropFirst() {
|
|
switch argument {
|
|
case "--dictionary":
|
|
self.headerType = .dictionary
|
|
|
|
case "--list":
|
|
self.headerType = .list
|
|
|
|
case "--item":
|
|
self.headerType = .item
|
|
|
|
default:
|
|
Self.helpAndExit()
|
|
}
|
|
}
|
|
}
|
|
|
|
private static func helpAndExit() -> Never {
|
|
print("Flags:")
|
|
print("")
|
|
print("\t--dictionary: Parse as dictionary field")
|
|
print("\t--list: Parse as list field")
|
|
print("\t--item: Parse as item field (default)")
|
|
exit(2)
|
|
}
|
|
}
|
|
|
|
extension Flags {
|
|
enum HeaderType {
|
|
case dictionary
|
|
case list
|
|
case item
|
|
}
|
|
}
|
|
|
|
enum Header {
|
|
case dictionary(OrderedMap<String, ItemOrInnerList>)
|
|
case list([ItemOrInnerList])
|
|
case item(Item)
|
|
|
|
func prettyPrint() {
|
|
switch self {
|
|
case .dictionary(let dict):
|
|
print("- dictionary (\(dict.count) entries):")
|
|
dict.prettyPrint(depth: 1)
|
|
case .list(let list):
|
|
print("- list (\(list.count) entries):")
|
|
list.prettyPrint(depth: 1)
|
|
case .item(let item):
|
|
print("- item:")
|
|
item.prettyPrint(depth: 1)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Array where Element == ItemOrInnerList {
|
|
func prettyPrint(depth: Int) {
|
|
let tabs = String(repeating: "\t", count: depth)
|
|
for (offset, element) in self.enumerated() {
|
|
print("\(tabs)- [\(offset)]:")
|
|
element.prettyPrint(depth: depth + 1)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension OrderedMap where Key == String, Value == ItemOrInnerList {
|
|
func prettyPrint(depth: Int) {
|
|
let tabs = String(repeating: "\t", count: depth)
|
|
for (key, value) in self {
|
|
print("\(tabs)- \(key):")
|
|
value.prettyPrint(depth: depth + 1)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension OrderedMap where Key == String, Value == BareItem {
|
|
func prettyPrint(depth: Int) {
|
|
let tabs = String(repeating: "\t", count: depth)
|
|
|
|
for (key, value) in self {
|
|
print("\(tabs)- \(key): \(value.prettyFormat())")
|
|
}
|
|
}
|
|
}
|
|
|
|
extension ItemOrInnerList {
|
|
func prettyPrint(depth: Int) {
|
|
switch self {
|
|
case .item(let item):
|
|
item.prettyPrint(depth: depth)
|
|
case .innerList(let list):
|
|
list.prettyPrint(depth: depth)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Item {
|
|
func prettyPrint(depth: Int) {
|
|
let tabs = String(repeating: "\t", count: depth)
|
|
|
|
print("\(tabs)- item: \(self.bareItem.prettyFormat())")
|
|
print("\(tabs)- parameters (\(parameters.count) entries):")
|
|
self.parameters.prettyPrint(depth: depth + 1)
|
|
}
|
|
}
|
|
|
|
extension InnerList {
|
|
func prettyPrint(depth: Int) {
|
|
let tabs = String(repeating: "\t", count: depth)
|
|
|
|
print("\(tabs)- innerList (\(parameters.count) entries):")
|
|
self.bareInnerList.prettyPrint(depth: depth + 1)
|
|
print("\(tabs)- parameters (\(parameters.count) entries):")
|
|
self.parameters.prettyPrint(depth: depth + 1)
|
|
}
|
|
}
|
|
|
|
extension BareInnerList {
|
|
func prettyPrint(depth: Int) {
|
|
let tabs = String(repeating: "\t", count: depth)
|
|
for (offset, element) in self.enumerated() {
|
|
print("\(tabs)- [\(offset)]:")
|
|
element.prettyPrint(depth: depth + 1)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension BareItem {
|
|
func prettyFormat() -> String {
|
|
switch self {
|
|
case .bool(let bool):
|
|
return "boolean \(bool)"
|
|
case .integer(let int):
|
|
return "integer \(int)"
|
|
case .string(let string):
|
|
return "string \"\(string)\""
|
|
case .token(let token):
|
|
return "token \(token)"
|
|
case .undecodedByteSequence(let bytes):
|
|
return "byte sequence \(bytes)"
|
|
case .decimal(let decimal):
|
|
let d = Decimal(sign: decimal.mantissa > 0 ? .plus : .minus,
|
|
exponent: Int(decimal.exponent), significand: Decimal(decimal.mantissa))
|
|
return "decimal \(d)"
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
do {
|
|
let flags = Flags()
|
|
var data = FileHandle.standardInput.readDataToEndOfFile()
|
|
|
|
// We need to strip trailing newlines.
|
|
var index = data.endIndex
|
|
while index > data.startIndex {
|
|
data.formIndex(before: &index)
|
|
if data[index] != UInt8(ascii: "\n") {
|
|
break
|
|
}
|
|
}
|
|
data = data[...index]
|
|
var parser = StructuredFieldParser(data)
|
|
|
|
let result: Header
|
|
switch flags.headerType {
|
|
case .dictionary:
|
|
result = .dictionary(try parser.parseDictionaryField())
|
|
case .list:
|
|
result = .list(try parser.parseListField())
|
|
case .item:
|
|
result = .item(try parser.parseItemField())
|
|
}
|
|
|
|
result.prettyPrint()
|
|
} catch {
|
|
print("error: \(error)")
|
|
exit(1)
|
|
}
|
|
}
|
|
|
|
main()
|