Initial Structured Headers decoder.

This commit is contained in:
Cory Benfield committed 2020-07-01 16:41:52 +01:00
1 parent fa8c1e771c
commit 03fa905bed
28 files changed
+36361 -19

No files matched your search

+1
View File
@@ -3,3 +3,4 @@
/Packages
/*.xcodeproj
xcuserdata/
.swiftpm/
+13 -1
View File
@@ -1,5 +1,17 @@
// swift-tools-version:5.2
//===----------------------------------------------------------------------===//
//
// 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 PackageDescription
let package = Package(
+57
View File
@@ -0,0 +1,57 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
public struct StructuredHeaderParsingError: Error {
private enum _BaseError: Hashable {
case invalidTrailingBytes
case invalidInnerList
case invalidItem
case invalidKey
case invalidIntegerOrDecimal
case invalidString
case invalidByteSequence
case invalidBoolean
case invalidToken
case invalidList
case invalidDictionary
}
private var base: _BaseError
private init(_ base: _BaseError) {
self.base = base
}
}
extension StructuredHeaderParsingError {
public static let invalidTrailingBytes = StructuredHeaderParsingError(.invalidTrailingBytes)
public static let invalidInnerList = StructuredHeaderParsingError(.invalidInnerList)
public static let invalidItem = StructuredHeaderParsingError(.invalidItem)
public static let invalidKey = StructuredHeaderParsingError(.invalidKey)
public static let invalidIntegerOrDecimal = StructuredHeaderParsingError(.invalidIntegerOrDecimal)
public static let invalidString = StructuredHeaderParsingError(.invalidString)
public static let invalidByteSequence = StructuredHeaderParsingError(.invalidByteSequence)
public static let invalidBoolean = StructuredHeaderParsingError(.invalidBoolean)
public static let invalidToken = StructuredHeaderParsingError(.invalidToken)
public static let invalidList = StructuredHeaderParsingError(.invalidList)
public static let invalidDictionary = StructuredHeaderParsingError(.invalidDictionary)
}
extension StructuredHeaderParsingError: Hashable { }
extension StructuredHeaderParsingError: CustomStringConvertible {
public var description: String {
return String(describing: self.base)
}
}
+745
View File
@@ -0,0 +1,745 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
fileprivate let asciiSpace = UInt8(ascii: " ")
fileprivate let asciiTab = UInt8(ascii: "\t")
fileprivate let asciiOpenParenthesis = UInt8(ascii: "(")
fileprivate let asciiCloseParenthesis = UInt8(ascii: ")")
fileprivate let asciiDash = UInt8(ascii: "-")
fileprivate let asciiUnderscore = UInt8(ascii: "_")
fileprivate let asciiZero = UInt8(ascii: "0")
fileprivate let asciiOne = UInt8(ascii: "1")
fileprivate let asciiNine = UInt8(ascii: "9")
fileprivate let asciiDigits = asciiZero...asciiNine
fileprivate let asciiDquote = UInt8(ascii: "\"")
fileprivate let asciiColon = UInt8(ascii: ":")
fileprivate let asciiSemicolon = UInt8(ascii: ";")
fileprivate let asciiBackslash = UInt8(ascii: "\\")
fileprivate let asciiQuestionMark = UInt8(ascii: "?")
fileprivate let asciiExclamationMark = UInt8(ascii: "!")
fileprivate let asciiOctothorpe = UInt8(ascii: "#")
fileprivate let asciiDollar = UInt8(ascii: "$")
fileprivate let asciiPercent = UInt8(ascii: "%")
fileprivate let asciiAmpersand = UInt8(ascii: "&")
fileprivate let asciiSquote = UInt8(ascii: "'")
fileprivate let asciiCaret = UInt8(ascii: "^")
fileprivate let asciiBacktick = UInt8(ascii: "`")
fileprivate let asciiPipe = UInt8(ascii: "|")
fileprivate let asciiTilde = UInt8(ascii: "~")
fileprivate let asciiAsterisk = UInt8(ascii: "*")
fileprivate let asciiEqual = UInt8(ascii: "=")
fileprivate let asciiPlus = UInt8(ascii: "+")
fileprivate let asciiSlash = UInt8(ascii: "/")
fileprivate let asciiPeriod = UInt8(ascii: ".")
fileprivate let asciiComma = UInt8(ascii: ",")
fileprivate let asciiCapitalA = UInt8(ascii: "A")
fileprivate let asciiCapitalZ = UInt8(ascii: "Z")
fileprivate let asciiLowerA = UInt8(ascii: "a")
fileprivate let asciiLowerZ = UInt8(ascii: "z")
fileprivate let asciiCapitals = asciiCapitalA...asciiCapitalZ
fileprivate let asciiLowercases = asciiLowerA...asciiLowerZ
/// A FieldParser is the basic parsing object for structured header fields represented as lists.
struct StructuredFieldParser<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
// Right now I'm on the fence about whether this should be generic. It's convenient,
// and makes it really easy for us to express the parsing over a wide range of data types.
// But it risks code size in a really nasty way! We should validate that we don't pay too
// much for this flexibility.
private var underlyingData: BaseData.SubSequence
init(_ data: BaseData) {
self.underlyingData = data[...]
}
}
extension StructuredFieldParser {
// Helper typealiases to avoid the explosion of generic parameters
typealias BareItem = StructuredHeaders.BareItem<BaseData.SubSequence>
typealias Item = StructuredHeaders.Item<BaseData.SubSequence>
typealias BareInnerList = StructuredHeaders.BareInnerList<BaseData.SubSequence>
typealias InnerList = StructuredHeaders.InnerList<BaseData.SubSequence>
typealias ItemOrInnerList = StructuredHeaders.ItemOrInnerList<BaseData.SubSequence>
typealias Key = BaseData.SubSequence
/// Parse the HTTP structured field as a list.
///
/// This is a straightforward implementation of the parser in the draft spec.
mutating func parseListField() throws -> [ItemOrInnerList] {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
// Step 2, enter the core list parsing loop.
let members = try self._parseAList()
// Final step, strip trailing spaces (which are now leading spaces, natch).
self.underlyingData.stripLeadingSpaces()
// The data is _required_ to be empty now, if it isn't we fail.
guard self.underlyingData.count == 0 else {
throw StructuredHeaderParsingError.invalidTrailingBytes
}
return members
}
/// Parse the HTTP structured header field as a dictionary.
mutating func parseDictionaryField() throws -> OrderedMap<Key, ItemOrInnerList> {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
// Step 2, enter the core dictionary parsing loop.
let map = try self._parseADictionary()
// Final step, strip trailing spaces (which are now leading spaces, natch).
self.underlyingData.stripLeadingSpaces()
// The data is _required_ to be empty now, if it isn't we fail.
guard self.underlyingData.count == 0 else {
throw StructuredHeaderParsingError.invalidTrailingBytes
}
return map
}
/// Parse the HTTP structured header field as an item.
mutating func parseItemField() throws -> Item {
// Step one, strip leading spaces.
self.underlyingData.stripLeadingSpaces()
// Step 2, do the core parse.
let item = try self._parseAnItem()
// Final step, strip trailing spaces (which are now leading spaces, natch).
self.underlyingData.stripLeadingSpaces()
// The data is _required_ to be empty now, if it isn't we fail.
guard self.underlyingData.count == 0 else {
throw StructuredHeaderParsingError.invalidTrailingBytes
}
return item
}
private mutating func _parseAList() throws -> [ItemOrInnerList] {
var results: [ItemOrInnerList] = []
loop: while self.underlyingData.count > 0 {
results.append(try self._parseAnItemOrInnerList())
self.underlyingData.stripLeadingOWS()
// If we've consumed all the data, the parse is finished.
guard let next = self.underlyingData.popFirst() else {
break loop
}
// Otherwise, the next character needs to be a comma.
guard next == asciiComma else {
throw StructuredHeaderParsingError.invalidList
}
self.underlyingData.stripLeadingOWS()
guard self.underlyingData.count > 0 else {
// Trailing comma!
throw StructuredHeaderParsingError.invalidList
}
}
return results
}
private mutating func _parseADictionary() throws -> OrderedMap<Key, ItemOrInnerList> {
var results = OrderedMap<Key, ItemOrInnerList>()
loop: while self.underlyingData.count > 0 {
let key = try self._parseAKey()
if self.underlyingData.first == asciiEqual {
self.underlyingData.consumeFirst()
results[key] = try self._parseAnItemOrInnerList()
} else {
results[key] = .item(Item(bareItem: true, parameters: try self._parseParameters()))
}
self.underlyingData.stripLeadingOWS()
/// If we've consumed all the data, the parse is finished.
guard let next = self.underlyingData.popFirst() else {
break loop
}
guard next == asciiComma else {
throw StructuredHeaderParsingError.invalidDictionary
}
self.underlyingData.stripLeadingOWS()
guard self.underlyingData.count > 0 else {
// Trailing comma!
throw StructuredHeaderParsingError.invalidList
}
}
return results
}
private mutating func _parseAnItemOrInnerList() throws -> ItemOrInnerList {
if self.underlyingData.first == asciiOpenParenthesis {
return .innerList(try self._parseAnInnerList())
} else {
return .item(try self._parseAnItem())
}
}
private mutating func _parseAnInnerList() throws -> InnerList {
precondition(self.underlyingData.popFirst() == asciiOpenParenthesis)
var innerList = BareInnerList()
while self.underlyingData.count > 0 {
self.underlyingData.stripLeadingSpaces()
if self.underlyingData.first == asciiCloseParenthesis {
// Consume, parse parameters, and complete.
self.underlyingData.consumeFirst()
let parameters = try self._parseParameters()
return InnerList(bareInnerList: innerList, parameters: parameters)
}
innerList.append(try self._parseAnItem())
let nextChar = self.underlyingData.first
guard nextChar == asciiSpace || nextChar == asciiCloseParenthesis else {
throw StructuredHeaderParsingError.invalidInnerList
}
}
// If we got here, we never got the close character for the list. Not good! This is an error.
throw StructuredHeaderParsingError.invalidInnerList
}
private mutating func _parseAnItem() throws -> Item {
let bareItem = try _parseABareItem()
let parameters = try self._parseParameters()
return Item(bareItem: bareItem, parameters: parameters)
}
private mutating func _parseABareItem() throws -> BareItem {
guard let first = self.underlyingData.first else {
throw StructuredHeaderParsingError.invalidItem
}
switch first {
case asciiDash, asciiDigits:
return try self._parseAnIntegerOrDecimal()
case asciiDquote:
return try self._parseAString()
case asciiColon:
return try self._parseAByteSequence()
case asciiQuestionMark:
return try self._parseABoolean()
case asciiCapitals, asciiLowercases, asciiAsterisk:
return try self._parseAToken()
default:
throw StructuredHeaderParsingError.invalidItem
}
}
private mutating func _parseAnIntegerOrDecimal() throws -> BareItem {
var sign = 1
var type = IntegerOrDecimal.integer
if let first = self.underlyingData.first, first == asciiDash {
sign = -1
self.underlyingData.consumeFirst()
}
guard let first = self.underlyingData.first, asciiDigits.contains(first) else {
throw StructuredHeaderParsingError.invalidIntegerOrDecimal
}
var index = self.underlyingData.startIndex
let endIndex = self.underlyingData.endIndex
loop: while index < endIndex {
switch self.underlyingData[index] {
case asciiDigits:
// Do nothing
()
case asciiPeriod where type == .integer:
// If input_number contains more than 12 characters, fail parsing. Otherwise,
// set type to decimal and consume.
if self.underlyingData.distance(from: self.underlyingData.startIndex, to: index) > 12 {
throw StructuredHeaderParsingError.invalidIntegerOrDecimal
}
type = .decimal
default:
// Non period or number, we're done parsing.
break loop
}
// "Consume" the character by advancing.
self.underlyingData.formIndex(after: &index)
// If type is integer and the input contains more than 15 characters, or type is decimal and more than 16,
// fail parsing.
let count = self.underlyingData.distance(from: self.underlyingData.startIndex, to: index)
switch type {
case .integer:
if count > 15 {
throw StructuredHeaderParsingError.invalidIntegerOrDecimal
}
case .decimal:
if count > 16 {
throw StructuredHeaderParsingError.invalidIntegerOrDecimal
}
}
}
// Consume the string.
let integerBytes = self.underlyingData[..<index]
self.underlyingData = self.underlyingData[index...]
switch type {
case .integer:
// This intermediate string is sad, we should rewrite this manually to avoid it.
// This force-unwrap is safe, as we have validated that all characters are ascii digits.
let baseInt = Int(String(decoding: integerBytes, as: UTF8.self), radix: 10)!
return .integer(baseInt * sign)
case .decimal:
// This must be non-nil, otherwise we couldn't have flipped to the decimal type.
let periodIndex = integerBytes.firstIndex(of: asciiPeriod)!
let periodIndexDistance = integerBytes.distance(from: periodIndex, to: integerBytes.endIndex)
if periodIndexDistance == 1 || periodIndexDistance > 4 {
// Period may not be last, or have more than three characters after it.
throw StructuredHeaderParsingError.invalidIntegerOrDecimal
}
// Same notes here as above
let baseFloat = Float64(String(decoding: integerBytes, as: UTF8.self))!
return .decimal(baseFloat * Float64(sign))
}
}
private mutating func _parseAString() throws -> BareItem {
guard self.underlyingData.first == asciiDquote else {
throw StructuredHeaderParsingError.invalidString
}
self.underlyingData.consumeFirst()
// Ok, let's pause. Here we need to parse out a String and turn it into...well, into something.
// It doesn't have to be a String now, but at some stage a user is going to want it to be a String,
// so we need to include the idea that we'll have to manifest a String at some point.
//
// The wrinkle here is we have to deal with escapes. Two characters may appear escaped in strings:
// dquote and backslash. Worse, _only_ those two may appear escaped: any other escape sequence is invalid.
// This means the most naive algorithm, which also happens to be best for the cache and branch predictor
// (just treat a string as a byte slice, walk forward until we find dquote, and slice it out) doesn't work.
//
// We can choose to do this _anyway_, by searching for the first unescaped dquote. But we have to remember
// to handle the escaping at some point, and we also have to police character validity. Doing this later risks
// that we'll have evicted these bytes from cache, forcing a cache miss to get them back. Not ideal.
//
// So we do a different thing. We walk the string twice: first to validate and find its length, and then the
// second time to actually create the String. We can't do this in one step without risking gravely over-allocating
// for the String, which would be sad, so we tolerate doing it twice. While we do it, we record whether the string
// contains escapes. If it doesn't, we know that we can fall back to the optimised String construction with no branches,
// making this fairly quick. If it does, well, we have branchy awkward code, but at least we have confidence that our
// data is in cache.
// First, walk 1: find the length, validate as we go, check for escapes.
var escapes = 0
var index = self.underlyingData.startIndex
var endIndex = self.underlyingData.endIndex
loop: while index < endIndex {
let char = self.underlyingData[index]
switch char {
case asciiBackslash:
self.underlyingData.formIndex(after: &index)
if index == endIndex {
throw StructuredHeaderParsingError.invalidString
}
let next = self.underlyingData[index]
guard next == asciiDquote || next == asciiBackslash else {
throw StructuredHeaderParsingError.invalidString
}
escapes += 1
case asciiDquote:
// Unquoted dquote, this is the end of the string.
endIndex = index
break loop
case 0x00...0x1f, 0x7f...:
// Forbidden bytes in string: string must be VCHAR and SP.
throw StructuredHeaderParsingError.invalidString
default:
// Allowed, unescape, uncontrol byte.
()
}
self.underlyingData.formIndex(after: &index)
}
// Oops, fell off the back of the string.
if endIndex == self.underlyingData.endIndex {
throw StructuredHeaderParsingError.invalidString
}
let stringSlice = self.underlyingData[self.underlyingData.startIndex..<index]
self.underlyingData.formIndex(after: &index)
self.underlyingData = self.underlyingData[index...]
// Ok, now we check: if we have encountered an escape, we have to fall back to the slow mode. If not,
// we can initialize the string directly.
if escapes == 0 {
return .string(String(decoding: stringSlice, as: UTF8.self))
} else {
return .string(String.decodingEscapes(stringSlice, escapes: escapes))
}
}
private mutating func _parseAByteSequence() throws -> BareItem {
guard self.underlyingData.first == asciiColon else {
throw StructuredHeaderParsingError.invalidByteSequence
}
self.underlyingData.consumeFirst()
var index = self.underlyingData.startIndex
while index < self.underlyingData.endIndex {
switch self.underlyingData[index] {
case asciiColon:
// Hey, this is the end! The base64 data is the data prior to here.
let consumedSlice = self.underlyingData[..<index]
// Skip the colon and consume it.
self.underlyingData.formIndex(after: &index)
self.underlyingData = self.underlyingData[index...]
return .undecodedByteSequence(consumedSlice)
case asciiCapitals, asciiLowercases, asciiDigits, asciiPlus, asciiSlash, asciiEqual:
// All valid characters for Base64 here.
self.underlyingData.formIndex(after: &index)
default:
// Invalid character
throw StructuredHeaderParsingError.invalidByteSequence
}
}
// Whoops, got to the end, invalid byte sequence.
throw StructuredHeaderParsingError.invalidByteSequence
}
private mutating func _parseABoolean() throws -> BareItem {
guard self.underlyingData.first == asciiQuestionMark else {
throw StructuredHeaderParsingError.invalidBoolean
}
self.underlyingData.consumeFirst()
switch self.underlyingData.first {
case asciiOne:
self.underlyingData.consumeFirst()
return true
case asciiZero:
self.underlyingData.consumeFirst()
return false
default:
// Whoops!
throw StructuredHeaderParsingError.invalidBoolean
}
}
private mutating func _parseAToken() throws -> BareItem {
switch self.underlyingData.first {
case .some(asciiCapitals), .some(asciiLowercases), .some(asciiAsterisk):
// Good
()
default:
throw StructuredHeaderParsingError.invalidToken
}
var index = self.underlyingData.startIndex
loop: while index < self.underlyingData.endIndex {
switch self.underlyingData[index] {
// Valid token characters are RFC 7230 tchar, colon, and slash.
// tchar is:
//
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
// / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
// / DIGIT / ALPHA
//
// The following insane case statement covers this. Tokens suck.
case asciiExclamationMark, asciiOctothorpe, asciiDollar, asciiPercent,
asciiAmpersand, asciiSquote, asciiAsterisk, asciiPlus, asciiDash,
asciiPeriod, asciiCaret, asciiUnderscore, asciiBacktick, asciiPipe,
asciiTilde, asciiDigits, asciiCapitals, asciiLowercases,
asciiColon, asciiSlash:
// Good, consume
self.underlyingData.formIndex(after: &index)
default:
// Token complete
break loop
}
}
// Token is complete either when we stop getting valid token characters or when
// we get to the end of the string.
let tokenSlice = self.underlyingData[..<index]
self.underlyingData = self.underlyingData[index...]
return .token(tokenSlice)
}
private mutating func _parseParameters() throws -> OrderedMap<BaseData.SubSequence, BareItem> {
var parameters = OrderedMap<BaseData.SubSequence, BareItem>()
// We want to loop while we still have bytes _and_ while the first character is asciiSemicolon.
// This covers both.
while self.underlyingData.first == asciiSemicolon {
// Consume the colon
self.underlyingData.consumeFirst()
self.underlyingData.stripLeadingSpaces()
let paramName = try self._parseAKey()
var paramValue: BareItem = true
if self.underlyingData.first == asciiEqual {
self.underlyingData.consumeFirst()
paramValue = try self._parseABareItem()
}
parameters[paramName] = paramValue
}
return parameters
}
private mutating func _parseAKey() throws -> BaseData.SubSequence {
guard let first = self.underlyingData.first, asciiLowercases.contains(first) || first == asciiAsterisk else {
throw StructuredHeaderParsingError.invalidKey
}
let key = self.underlyingData.prefix(while: {
switch $0 {
case asciiLowercases, asciiDigits, asciiUnderscore, asciiDash, asciiPeriod, asciiAsterisk:
return true
default:
return false
}
})
self.underlyingData = self.underlyingData.dropFirst(key.count)
return key
}
}
enum ItemOrInnerList<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
case item(Item<BaseData>)
case innerList(InnerList<BaseData>)
}
enum BareItem<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
case bool(Bool)
case integer(Int)
case decimal(Float64) // Not great, can we do better?
case string(String)
case undecodedByteSequence(BaseData)
case token(BaseData)
}
extension BareItem: ExpressibleByBooleanLiteral {
init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
extension BareItem: Hashable { }
struct Item<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
var bareItem: BareItem<BaseData>
var parameters: OrderedMap<BaseData, BareItem<BaseData>>
}
extension Item: Hashable { }
struct BareInnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
private var items: [Item<BaseData>]
init() {
self.items = []
}
fileprivate mutating func append(_ item: Item<BaseData>) {
self.items.append(item)
}
}
extension BareInnerList: RandomAccessCollection, MutableCollection {
struct Index {
fileprivate var baseIndex: Array<Item<BaseData>>.Index
init(_ baseIndex: Array<Item<BaseData>>.Index) {
self.baseIndex = baseIndex
}
}
var count: Int {
return self.items.count
}
var startIndex: Index {
return Index(self.items.startIndex)
}
var endIndex: Index {
return Index(self.items.endIndex)
}
func index(after i: Index) -> Index {
return Index(self.items.index(after: i.baseIndex))
}
func index(before i: Index) -> Index {
return Index(self.items.index(before: i.baseIndex))
}
func index(_ i: Index, offsetBy offset: Int) -> Index {
return Index(self.items.index(i.baseIndex, offsetBy: offset))
}
subscript(index: Index) -> Item<BaseData> {
get {
return self.items[index.baseIndex]
}
set {
self.items[index.baseIndex] = newValue
}
}
}
extension BareInnerList.Index: Hashable { }
extension BareInnerList.Index: Comparable {
static func <(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex < rhs.baseIndex
}
}
struct InnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
var bareInnerList: BareInnerList<BaseData>
var parameters: OrderedMap<BaseData, BareItem<BaseData>>
}
fileprivate enum IntegerOrDecimal {
case integer
case decimal
}
extension RandomAccessCollection where Element == UInt8, SubSequence == Self {
mutating func stripLeadingSpaces() {
self = self.drop(while: { $0 == asciiSpace })
}
mutating func stripLeadingOWS() {
self = self.drop(while: { $0 == asciiSpace || $0 == asciiTab })
}
mutating func consumeFirst() {
self = self.dropFirst()
}
}
extension String {
// This is the slow path, so we never inline this.
@inline(never)
fileprivate static func decodingEscapes<Bytes: RandomAccessCollection>(_ bytes: Bytes, escapes: Int) -> String where Bytes.Element == UInt8 {
// We assume the string is previously validated, so the escapes are easily removed. See the doc comment for
// `StrippingStringEscapesCollection` for more details on what we're doing here.
let unescapedBytes = StrippingStringEscapesCollection(bytes, escapes: escapes)
if #available(macOS 10.16, macCatalyst 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
return String(unsafeUninitializedCapacity: unescapedBytes.count) { innerPtr in
let (_, endIndex) = innerPtr.initialize(from: unescapedBytes)
return endIndex
}
} else {
return String(decoding: unescapedBytes, as: UTF8.self)
}
}
}
/// This helper struct is used to try to minimise the surface area of the unsafe string constructor.
///
/// We have a goal to create the String as cheaply as possible in the presence of escapes. Using the safe constructor will not
/// do that: if a non-contiguous collection is used to create a String directly, an intermediate Array will be used to flatten
/// the collection. As an escaped string is definitionally non-contiguous, we would hit that path, which is very sad.
/// Until this issue is fixed (https://bugs.swift.org/browse/SR-13111) we take a different approach: we use
/// `String.init(unsafeUninitializedCapacity:initializingWith)`. This is an unsafe function, so to reduce the unsafety as much
/// as possible we define this safe wrapping Collection and then use `copyBytes` to implement the initialization.
fileprivate struct StrippingStringEscapesCollection<BaseCollection: RandomAccessCollection> where BaseCollection.Element == UInt8 {
private var base: BaseCollection
private var escapes: UInt
init(_ base: BaseCollection, escapes: Int) {
self.base = base
self.escapes = UInt(escapes)
}
}
extension StrippingStringEscapesCollection: Collection {
fileprivate struct Index {
fileprivate var _baseIndex: BaseCollection.Index
fileprivate init(baseIndex: BaseCollection.Index) {
self._baseIndex = baseIndex
}
}
// This is an extremely important customisation point! Our base collection is random access,
// so we know that on the base this is O(1), but as this collection is _not_ random access here
// it's O(n).
fileprivate var count: Int {
return self.base.count - Int(self.escapes)
}
fileprivate var startIndex: Index {
// Tricky note here, but start index _might_ be an ascii backslash, which we have to skip.
return Index(baseIndex: self.unescapedIndex(self.base.startIndex))
}
fileprivate var endIndex: Index {
return Index(baseIndex: self.base.endIndex)
}
fileprivate func index(after i: Index) -> Index {
let next = self.base.index(after: i._baseIndex)
return Index(baseIndex: self.unescapedIndex(next))
}
fileprivate subscript(index: Index) -> UInt8 {
return self.base[index._baseIndex]
}
private func unescapedIndex(_ baseIndex: BaseCollection.Index) -> BaseCollection.Index {
if baseIndex == self.base.endIndex {
return baseIndex
}
if self.base[baseIndex] == asciiBackslash {
return self.base.index(after: baseIndex)
} else {
return baseIndex
}
}
}
extension StrippingStringEscapesCollection.Index: Equatable { }
extension StrippingStringEscapesCollection.Index: Comparable {
fileprivate static func <(lhs: Self, rhs: Self) -> Bool {
return lhs._baseIndex < rhs._baseIndex
}
}
+143
View File
@@ -0,0 +1,143 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// 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
/// maps in structured headers are small (fewer than 20 elements), and so the
/// distinction between hashing and linear search is not really a concern. However, for
/// future implementation flexibility, we continue to require that keys be hashable.
struct OrderedMap<Key, Value> where Key: Hashable {
private var backing: [Entry]
init() {
self.backing = []
}
/// Look up the value for a given key.
///
/// Warning! Unlike a regular dictionary, we do not promise this will be O(1)!
subscript(key: Key) -> Value? {
get {
return self.backing.first(where: { $0.key == key }).map { $0.value }
}
set {
if let existing = self.backing.firstIndex(where: { $0.key == key }) {
self.backing.remove(at: existing)
}
if let newValue = newValue {
self.backing.append(Entry(key: key, value: newValue))
}
}
}
}
// MARK:- Helper struct for storing elements
extension OrderedMap {
// This struct takes some explaining.
//
// We don't want to maintain too much code here. In particular, we'd like to have straightforward equatable and hashable
// implementations. However, tuples aren't equatable or hashable. So we need to actually store something that is: a nominal
// type. That's this!
//
// This existence of this struct is a pure implementation detail and not exposed to the user of the type.
fileprivate struct Entry {
var key: Key
var value: Value
}
}
// MARK:- Collection conformances
extension OrderedMap: RandomAccessCollection, MutableCollection {
struct Index {
fileprivate var baseIndex: Array<(Key, Value)>.Index
fileprivate init(_ baseIndex: Array<(Key, Value)>.Index) {
self.baseIndex = baseIndex
}
}
var startIndex: Index {
return Index(self.backing.startIndex)
}
var endIndex: Index {
return Index(self.backing.endIndex)
}
var count: Int {
return self.backing.count
}
subscript(position: Index) -> (Key, Value) {
get {
let element = self.backing[position.baseIndex]
return (element.key, element.value)
}
set {
self.backing[position.baseIndex] = Entry(key: newValue.0, value: newValue.1)
}
}
func index(_ i: Index, offsetBy distance: Int) -> Index {
return Index(self.backing.index(i.baseIndex, offsetBy: distance))
}
func index(after i: Index) -> Index {
return self.index(i, offsetBy: 1)
}
func index(before i: Index) -> Index {
return self.index(i, offsetBy: -1)
}
}
extension OrderedMap.Index: Hashable { }
extension OrderedMap.Index: Comparable {
static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex < rhs.baseIndex
}
}
extension OrderedMap.Index: Strideable {
func advanced(by n: Int) -> Self {
return Self(self.baseIndex.advanced(by: n))
}
func distance(to other: Self) -> Int {
return self.baseIndex.distance(to: other.baseIndex)
}
}
// MARK:- Helper conformances
extension OrderedMap: ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Key, Value)...) {
self.backing = elements.map { Entry(key: $0.0, value: $0.1) }
}
}
extension OrderedMap: CustomDebugStringConvertible {
var debugDescription: String {
let backingRepresentation = self.backing.map { "\($0.key): \($0.value)" }.joined(separator: ", ")
return "[\(backingRepresentation)]"
}
}
// MARK:- Conditional conformances
extension OrderedMap.Entry: Equatable where Key: Equatable, Value: Equatable { }
extension OrderedMap: Equatable where Key: Equatable, Value: Equatable { }
extension OrderedMap.Entry: Hashable where Key: Hashable, Value: Hashable { }
extension OrderedMap: Hashable where Key: Hashable, Value: Hashable { }
@@ -1,3 +0,0 @@
struct swift_structured_headers {
var text = "Hello, World!"
}
+69
View File
@@ -0,0 +1,69 @@
//===----------------------------------------------------------------------===//
//
// 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
fileprivate let base32DecoderAlphabet: [UnicodeScalar: UInt64] = [
"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7,
"I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15,
"Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23,
"Y": 24, "Z": 25, "2": 26, "3": 27, "4": 28, "5": 29, "6": 30, "7": 31,
]
extension Data {
init(base32Encoded data: Data) {
self = Data()
for start in stride(from: data.startIndex, to: data.endIndex, by: 8) {
let bytes = data[start..<(start + 8)]
precondition(bytes.count == 8)
var seenEquals = 0
var rawValue = UInt64(0)
for character in bytes {
// Each character encodes 5 bits. The equals pad with zeros _on the right_, so we must shift for every
// character we see.
rawValue <<= 5
if character == UInt8(ascii: "=") {
seenEquals += 1
continue
}
let underlyingValue = base32DecoderAlphabet[UnicodeScalar(character)]!
rawValue |= underlyingValue
}
let ignoredBytes: Int
switch seenEquals {
case 0:
ignoredBytes = 0
case 1:
ignoredBytes = 1
case 3:
ignoredBytes = 2
case 4:
ignoredBytes = 3
case 6:
ignoredBytes = 4
default:
fatalError("Impossible equals count: \(seenEquals)")
}
for byteNumber in (ignoredBytes..<5).reversed() {
let byte = UInt8(truncatingIfNeeded: rawValue >> (byteNumber * 8))
self.append(byte)
}
}
}
}
+103
View File
@@ -0,0 +1,103 @@
//===----------------------------------------------------------------------===//
//
// 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
enum FixturesLoader {
private static var fixturesDirectory: URL {
let myURL = URL(fileURLWithPath: #file, isDirectory: false)
return URL(string: "../TestFixtures/", relativeTo: myURL)!.absoluteURL
}
static var fixtures: [StructuredHeaderTestFixture] {
// ContentsOfDirectory can throw if it hits EINTR, just spin
var files: [URL]? = nil
for _ in 0..<1000 {
do {
files = try FileManager.default.contentsOfDirectory(at: fixturesDirectory, includingPropertiesForKeys: nil, options: [])
break
} catch let error as NSError {
guard let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError, underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == EINTR else {
fatalError("\(error)")
}
// Ok, we'll continue
}
}
guard let realFiles = files else {
fatalError("Hit EINTR 1000 times!")
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return realFiles.filter { $0.pathExtension == "json" }.flatMap { file -> [StructuredHeaderTestFixture] in
let content = try! Data(contentsOf: file, options: [.uncached, .mappedIfSafe])
return try! decoder.decode([StructuredHeaderTestFixture].self, from: content)
}
}
}
struct StructuredHeaderTestFixture: Decodable {
/// The name of this test.
var name: String
/// The list of header fields that should be parsed.
var raw: [String]
/// The type to use to parse the fields
var headerType: String
/// The expected data structure to be produced. Note that this is stored as a serialized JSON object:
/// this is because the shape of this data structure varies from test-case to test-case, so we can't
/// incorporate it into the type system. This type is also preventing us from using Codable here: we just
/// don't know what the heck we're expecting to see.
var expected: JSONSchema?
/// Whether this test is required to fail.
var mustFail: Bool?
/// Whether this test is allowed to fail.
var canFail: Bool?
/// The canonical form if the field value, if different from raw. Not applicable if `mustFail` is `true`.
var canonical: [String]?
}
/// This defines the JSON types that can be used to encode structured headers. It allows us to express the expected outcome of
/// a parse in a type-safe way.
enum JSONSchema: Decodable {
case dictionary([String: JSONSchema])
case array([JSONSchema])
case integer(Int)
case double(Double)
case string(String)
case bool(Bool)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(String.self) {
self = .string(value)
} else if let bool = try? container.decode(Bool.self) {
self = .bool(bool)
} else if let value = try? container.decode(Int.self) {
self = .integer(value)
} else if let value = try? container.decode(Double.self) {
self = .double(value)
} else if let value = try? container.decode([String: JSONSchema].self) {
self = .dictionary(value)
} else if let value = try? container.decode([JSONSchema].self) {
self = .array(value)
} else {
preconditionFailure("Failed to decode at \(container.codingPath)")
}
}
}
@@ -0,0 +1,218 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
@testable import StructuredHeaders
enum FixtureTestError: Error {
case base64DecodingFailed
}
final class StructuredHeadersTests: XCTestCase {
enum TestResult<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
case dictionary(OrderedMap<BaseData, ItemOrInnerList<BaseData>>)
case list([ItemOrInnerList<BaseData>])
case item(Item<BaseData>)
}
private func _validateBareItem<BaseData: RandomAccessCollection>(_ bareItem: BareItem<BaseData>, against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
switch (bareItem, schema) {
case (.integer(let baseInt), .integer(let jsonInt)):
XCTAssertEqual(baseInt, jsonInt, "\(fixtureName): Got \(bareItem), expected \(schema)")
case (.decimal(let baseDecimal), .double(let jsonDouble)):
XCTAssertEqual(baseDecimal, jsonDouble, "\(fixtureName): Got \(bareItem), expected \(schema)")
case (.decimal(let baseDecimal), .integer(let jsonInteger)):
// Due to limits of Foundation's JSONSerialization, we can get types that decode as integers but are actually decimals.
// We just cannot tell the difference here, so we tolerate this flexibility by checking whether the baseDecimal is indeed
// an integer and using that.
XCTAssertEqual(baseDecimal, Double(jsonInteger), "\(fixtureName): Got \(bareItem), expected \(schema)")
case (.string(let baseString), .string(let jsonString)):
XCTAssertEqual(baseString, jsonString, "\(fixtureName): Got \(bareItem), expected \(schema)")
case (.token(let baseToken), .dictionary(let typeDictionary)):
guard typeDictionary.count == 2, case .string(let typeName) = typeDictionary["__type"], case .string(let typeValue) = typeDictionary["value"] else {
XCTFail("\(fixtureName): Unexpected type dict \(typeDictionary)")
return
}
XCTAssertEqual(typeName, "token", "\(fixtureName): Expected type token, got type \(typeName)")
XCTAssertEqual(typeValue, String(decoding: baseToken, as: UTF8.self), "\(fixtureName): Got \(String(decoding: baseToken, as: UTF8.self)), expected \(typeValue)")
case (.undecodedByteSequence(let binary), .dictionary(let typeDictionary)):
guard typeDictionary.count == 2, case .string(let typeName) = typeDictionary["__type"], case .string(let typeValue) = typeDictionary["value"] else {
XCTFail("\(fixtureName): Unexpected type dict \(typeDictionary)")
return
}
XCTAssertEqual(typeName, "binary", "\(fixtureName): Expected type binary, got type \(typeName)")
guard let decodedValue = Data(base64Encoded: Data(binary)) else {
throw FixtureTestError.base64DecodingFailed
}
let decodedExpected = Data(base32Encoded: Data(typeValue.utf8))
XCTAssertEqual(decodedValue, decodedExpected, "\(fixtureName): Got \(Array(decodedValue)), expected \(Array(decodedExpected))")
case (.bool(let baseBool), .bool(let expectedBool)):
XCTAssertEqual(baseBool, expectedBool, "\(fixtureName): Got \(baseBool), expected \(expectedBool)")
default:
XCTFail("\(fixtureName): Got \(bareItem), expected \(schema)")
}
}
private func _validateParameters<BaseData: RandomAccessCollection>(_ parameters: OrderedMap<BaseData, BareItem<BaseData>>, against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
guard case .dictionary(let expectedParameters) = schema else {
XCTFail("\(fixtureName): Expected parameters to be a JSON dictionary, but got \(schema)")
return
}
XCTAssertEqual(expectedParameters.count, parameters.count, "\(fixtureName): Different numbers of parameters: expected \(expectedParameters), got \(parameters)")
for (name, value) in parameters {
guard let expectedValue = expectedParameters[String(decoding: name, as: UTF8.self)] else {
XCTFail("\(fixtureName): Did not contain parameter for \(String(decoding: name, as: UTF8.self))")
return
}
try self._validateBareItem(value, against: expectedValue, fixtureName: fixtureName)
}
}
private func _validateItem<BaseData: RandomAccessCollection>(_ item: Item<BaseData>, against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
// Item: JSON array with two elements, the Bare-Item and Parameters
guard case .array(let arrayElements) = schema, arrayElements.count == 2 else {
XCTFail("\(fixtureName): Unexpected item: got \(item), expected \(schema)")
return
}
// First, match the item.
try self._validateBareItem(item.bareItem, against: arrayElements.first!, fixtureName: fixtureName)
// Now the parameters.
try self._validateParameters(item.parameters, against: arrayElements.last!, fixtureName: fixtureName)
}
private func _validateInnerList<BaseData: RandomAccessCollection>(_ innerList: InnerList<BaseData>, against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
guard case .array(let arrayElements) = schema,
arrayElements.count == 2,
case .some(.array(let expectedItems)) = arrayElements.first,
let expectedParameters = arrayElements.last else {
XCTFail("\(fixtureName): Unexpected inner list: got \(innerList), expected \(schema)")
return
}
XCTAssertEqual(expectedItems.count, innerList.bareInnerList.count, "\(fixtureName): Unexpected inner list items: expected \(expectedItems), got \(innerList.bareInnerList)")
for (actualItem, expectedItem) in zip(innerList.bareInnerList, expectedItems) {
try self._validateItem(actualItem, against: expectedItem, fixtureName: fixtureName)
}
try self._validateParameters(innerList.parameters, against: expectedParameters, fixtureName: fixtureName)
}
private func _validateList<BaseData: RandomAccessCollection>(_ result: [ItemOrInnerList<BaseData>], against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
guard case .array(let arrayElements) = schema else {
XCTFail("\(fixtureName): Unexpected list: got \(result), expected \(schema)")
return
}
XCTAssertEqual(arrayElements.count, result.count, "\(fixtureName): Different counts in list: got \(result), expected \(arrayElements)")
for (innerResult, expectedElement) in zip(result, arrayElements) {
switch innerResult {
case .innerList(let innerList):
try self._validateInnerList(innerList, against: expectedElement, fixtureName: fixtureName)
case .item(let item):
try self._validateItem(item, against: expectedElement, fixtureName: fixtureName)
}
}
}
private func _validateDictionary<BaseData: RandomAccessCollection>(_ result: OrderedMap<BaseData, ItemOrInnerList<BaseData>>, against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
guard case .dictionary(let expectedElements) = schema else {
XCTFail("\(fixtureName): Unexpected dictionary: got \(result), expected \(schema)")
return
}
XCTAssertEqual(expectedElements.count, result.count, "\(fixtureName): Different counts in dictionary: got \(result), expected \(expectedElements)")
for (key, value) in result {
guard let expectedEntry = expectedElements[String(decoding: key, as: UTF8.self)] else {
XCTFail("\(fixtureName): Could not find \(String(decoding: key, as: UTF8.self)) in \(expectedElements)")
return
}
switch value {
case .innerList(let innerList):
try self._validateInnerList(innerList, against: expectedEntry, fixtureName: fixtureName)
case .item(let item):
try self._validateItem(item, against: expectedEntry, fixtureName: fixtureName)
}
}
}
private func _validateFixtureResult<BaseData: RandomAccessCollection>(_ result: TestResult<BaseData>, against schema: JSONSchema, fixtureName: String) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
// We want to recursively validate the result here.
switch result {
case .list(let resultItems):
try self._validateList(resultItems, against: schema, fixtureName: fixtureName)
case .dictionary(let resultDictionary):
try self._validateDictionary(resultDictionary, against: schema, fixtureName: fixtureName)
case .item(let resultItem):
// Items have a specific format, but we have a helper for it.
try self._validateItem(resultItem, against: schema, fixtureName: fixtureName)
}
}
private func _runTestOnFixture(_ fixture: StructuredHeaderTestFixture) {
// Temporary join here for now, we may want to use a fancy collection at some point.
let joinedHeaders = Array(fixture.raw.joined(separator: ", ").utf8)
do {
var parser = StructuredFieldParser(joinedHeaders)
let testResult: TestResult<ArraySlice<UInt8>>
switch fixture.headerType {
case "dictionary":
testResult = try .dictionary(parser.parseDictionaryField())
case "list":
testResult = try .list(parser.parseListField())
case "item":
testResult = try .item(parser.parseItemField())
default:
XCTFail("\(fixture.name): Unexpected header type \(fixture.headerType)")
return
}
// If we got here, but we were supposed to error, we should error.
if fixture.mustFail == true {
XCTFail("\(fixture.name): Fixture must fail, but parse succeeded")
return
}
// We allow this function to throw. It may only throw in cases where the test is allowed to fail,
// so we police it under the same rules. In this case, we do some extra policing to confirm we only
// tolerate the appropriate kinds of errors.
// This force-unwrap is safe, expected can only be nil if mustFail is true.
do {
try self._validateFixtureResult(testResult, against: fixture.expected!, fixtureName: fixture.name)
} catch let error as FixtureTestError {
throw error
} catch {
XCTFail("\(fixture.name): validator threw unexpected error \(error)")
}
} catch {
// Throwing is fine if this test is allowed to or expected to fail. If it isn't, fail the test.
guard fixture.mustFail == true || fixture.canFail == true else {
XCTFail("\(fixture.name): Fixture threw unexpected error \(error)")
return
}
}
}
func testCanPassAllFixtures() throws {
// This is a bulk-test: we run across all the fixtures in the fixtures directory to confirm we can handle all of them.
for fixture in FixturesLoader.fixtures {
self._runTestOnFixture(fixture)
}
}
}
@@ -1,15 +0,0 @@
import XCTest
@testable import swift_structured_headers
final class swift_structured_headersTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(swift_structured_headers().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
+76
View File
@@ -0,0 +1,76 @@
[
{
"name": "basic binary",
"raw": [":aGVsbG8=:"],
"header_type": "item",
"expected": [
{"__type": "binary", "value": "NBSWY3DP"},
{}]
},
{
"name": "empty binary",
"raw": ["::"],
"header_type": "item",
"expected": [
{"__type": "binary", "value": ""},
{}]
},
{
"name": "bad paddding",
"raw": [":aGVsbG8:"],
"header_type": "item",
"expected": [
{"__type": "binary", "value": "NBSWY3DP"},
{}],
"can_fail": true,
"canonical": [":aGVsbG8=:"]
},
{
"name": "bad end delimiter",
"raw": [":aGVsbG8="],
"header_type": "item",
"must_fail": true
},
{
"name": "extra whitespace",
"raw": [":aGVsb G8=:"],
"header_type": "item",
"must_fail": true
},
{
"name": "extra chars",
"raw": [":aGVsbG!8=:"],
"header_type": "item",
"must_fail": true
},
{
"name": "suffix chars",
"raw": [":aGVsbG8=!:"],
"header_type": "item",
"must_fail": true
},
{
"name": "non-zero pad bits",
"raw": [":iZ==:"],
"header_type": "item",
"expected": [
{"__type": "binary", "value": "RE======"},
{}],
"can_fail": true,
"canonical": [":iQ==:"]
},
{
"name": "non-ASCII binary",
"raw": [":/+Ah:"],
"header_type": "item",
"expected": [
{"__type": "binary", "value": "77QCC==="},
{}]
},
{
"name": "base64url binary",
"raw": [":_-Ah:"],
"header_type": "item",
"must_fail": true
}
]
+69
View File
@@ -0,0 +1,69 @@
[
{
"name": "basic true boolean",
"raw": ["?1"],
"header_type": "item",
"expected": [true, {}]
},
{
"name": "basic false boolean",
"raw": ["?0"],
"header_type": "item",
"expected": [false, {}]
},
{
"name": "unknown boolean",
"raw": ["?Q"],
"header_type": "item",
"must_fail": true
},
{
"name": "whitespace boolean",
"raw": ["? 1"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative zero boolean",
"raw": ["?-0"],
"header_type": "item",
"must_fail": true
},
{
"name": "T boolean",
"raw": ["?T"],
"header_type": "item",
"must_fail": true
},
{
"name": "F boolean",
"raw": ["?F"],
"header_type": "item",
"must_fail": true
},
{
"name": "t boolean",
"raw": ["?t"],
"header_type": "item",
"must_fail": true
},
{
"name": "f boolean",
"raw": ["?f"],
"header_type": "item",
"must_fail": true
},
{
"name": "spelled-out True boolean",
"raw": ["?True"],
"header_type": "item",
"must_fail": true
},
{
"name": "spelled-out False boolean",
"raw": ["?False"],
"header_type": "item",
"must_fail": true
}
]
+163
View File
@@ -0,0 +1,163 @@
[
{
"name": "basic dictionary",
"raw": ["en=\"Applepie\", da=:w4ZibGV0w6ZydGUK:"],
"header_type": "dictionary",
"expected": {"en": ["Applepie", {}], "da": [
{"__type": "binary", "value": "YODGE3DFOTB2M4TUMUFA===="},
{}]
}
},
{
"name": "empty dictionary",
"raw": [""],
"header_type": "dictionary",
"expected": {},
"canonical": []
},
{
"name": "single item dictionary",
"raw": ["a=1"],
"header_type": "dictionary",
"expected": {"a": [1, {}]}
},
{
"name": "list item dictionary",
"raw": ["a=(1 2)"],
"header_type": "dictionary",
"expected": {"a": [[[1, {}], [2, {}]], {}]}
},
{
"name": "single list item dictionary",
"raw": ["a=(1)"],
"header_type": "dictionary",
"expected": {"a": [[[1, {}]], {}]}
},
{
"name": "empty list item dictionary",
"raw": ["a=()"],
"header_type": "dictionary",
"expected": {"a": [[], {}]}
},
{
"name": "no whitespace dictionary",
"raw": ["a=1,b=2"],
"header_type": "dictionary",
"expected": {"a": [1, {}], "b": [2, {}]},
"canonical": ["a=1, b=2"]
},
{
"name": "extra whitespace dictionary",
"raw": ["a=1 , b=2"],
"header_type": "dictionary",
"expected": {"a": [1, {}], "b": [2, {}]},
"canonical": ["a=1, b=2"]
},
{
"name": "tab separated dictionary",
"raw": ["a=1\t,\tb=2"],
"header_type": "dictionary",
"expected": {"a": [1, {}], "b": [2, {}]},
"canonical": ["a=1, b=2"]
},
{
"name": "leading whitespace dictionary",
"raw": [" a=1 , b=2"],
"header_type": "dictionary",
"expected": {"a": [1, {}], "b": [2, {}]},
"canonical": ["a=1, b=2"]
},
{
"name": "whitespace before = dictionary",
"raw": ["a =1, b=2"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "whitespace after = dictionary",
"raw": ["a=1, b= 2"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "two lines dictionary",
"raw": ["a=1", "b=2"],
"header_type": "dictionary",
"expected": {"a": [1, {}], "b": [2, {}]},
"canonical": ["a=1, b=2"]
},
{
"name": "missing value dictionary",
"raw": ["a=1, b, c=3"],
"header_type": "dictionary",
"expected": {"a": [1,{}], "b": [true, {}], "c": [3, {}]}
},
{
"name": "all missing value dictionary",
"raw": ["a, b, c"],
"header_type": "dictionary",
"expected": {"a": [true,{}], "b": [true, {}], "c": [true, {}]}
},
{
"name": "start missing value dictionary",
"raw": ["a, b=2"],
"header_type": "dictionary",
"expected": {"a": [true,{}], "b": [2, {}]}
},
{
"name": "end missing value dictionary",
"raw": ["a=1, b"],
"header_type": "dictionary",
"expected": {"a": [1,{}], "b": [true, {}]}
},
{
"name": "missing value with params dictionary",
"raw": ["a=1, b;foo=9, c=3"],
"header_type": "dictionary",
"expected": {"a": [1,{}], "b": [true, {"foo": 9}], "c": [3, {}]}
},
{
"name": "explicit true value with params dictionary",
"raw": ["a=1, b=?1;foo=9, c=3"],
"header_type": "dictionary",
"expected": {"a": [1,{}], "b": [true, {"foo": 9}], "c": [3, {}]},
"canonical": ["a=1, b;foo=9, c=3"]
},
{
"name": "trailing comma dictionary",
"raw": ["a=1, b=2,"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "empty item dictionary",
"raw": ["a=1,,b=2,"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "duplicate key dictionary",
"raw": ["a=1,b=2,a=3"],
"header_type": "dictionary",
"expected": {"a": [3, {}], "b": [2, {}]},
"canonical": ["a=3, b=2"]
},
{
"name": "numeric key dictionary",
"raw": ["a=1,1b=2,a=1"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "uppercase key dictionary",
"raw": ["a=1,B=2,a=1"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "bad key dictionary",
"raw": ["a=1,b!=2,a=1"],
"header_type": "dictionary",
"must_fail": true
}
]
+206
View File
@@ -0,0 +1,206 @@
[
{
"name": "Foo-Example",
"raw": ["2; foourl=\"https://foo.example.com/\""],
"header_type": "item",
"expected": [2, {"foourl": "https://foo.example.com/"}],
"canonical": ["2;foourl=\"https://foo.example.com/\""]
},
{
"name": "Example-StrListHeader",
"raw": ["\"foo\", \"bar\", \"It was the best of times.\""],
"header_type": "list",
"expected": [
["foo", {}],
["bar", {}],
["It was the best of times.", {}]
]
},
{
"name": "Example-Hdr (list on one line)",
"raw": ["foo, bar"],
"header_type": "list",
"expected": [
[{"__type":"token", "value":"foo"}, {}],
[{"__type":"token", "value":"bar"}, {}]
]
},
{
"name": "Example-Hdr (list on two lines)",
"raw": ["foo", "bar"],
"header_type": "list",
"expected": [
[{"__type":"token", "value":"foo"}, {}],
[{"__type":"token", "value":"bar"}, {}]
],
"canonical": ["foo, bar"]
},
{
"name": "Example-StrListListHeader",
"raw": ["(\"foo\" \"bar\"), (\"baz\"), (\"bat\" \"one\"), ()"],
"header_type": "list",
"expected": [
[[
["foo", {}],
["bar", {}]
], {}],
[[
["baz", {}]
], {}],
[[
["bat", {}],
["one", {}]
], {}],
[[], {}]
]
},
{
"name": "Example-ListListParam",
"raw": ["(\"foo\"; a=1;b=2);lvl=5, (\"bar\" \"baz\");lvl=1"],
"header_type": "list",
"expected": [
[[
["foo", {"a": 1, "b": 2}]
], {"lvl": 5}],
[[
["bar", {}], ["baz", {}]
], {"lvl": 1}]
],
"canonical": ["(\"foo\";a=1;b=2);lvl=5, (\"bar\" \"baz\");lvl=1"]
},
{
"name": "Example-ParamListHeader",
"raw": ["abc;a=1;b=2; cde_456, (ghi;jk=4 l);q=\"9\";r=w"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "abc"}, {"a": 1, "b": 2, "cde_456": true}],
[
[
[{"__type": "token", "value": "ghi"}, {"jk": 4}],
[{"__type": "token", "value": "l"}, {}]
],
{"q": "9", "r": {"__type": "token", "value": "w"}}
]
],
"canonical": ["abc;a=1;b=2;cde_456, (ghi;jk=4 l);q=\"9\";r=w"]
},
{
"name": "Example-IntHeader",
"raw": ["1; a; b=?0"],
"header_type": "item",
"expected": [1, {"a": true, "b": false}],
"canonical": ["1;a;b=?0"]
},
{
"name": "Example-DictHeader",
"raw": ["en=\"Applepie\", da=:w4ZibGV0w6ZydGU=:"],
"header_type": "dictionary",
"expected": {
"en": ["Applepie", {}],
"da": [{"__type": "binary", "value": "YODGE3DFOTB2M4TUMU======"}, {}]
}
},
{
"name": "Example-DictHeader",
"raw": ["a=?0, b, c; foo=bar"],
"header_type": "dictionary",
"expected": {"a": [false, {}], "b": [true, {}], "c": [
true, {"foo": {"__type": "token", "value": "bar"}}
]},
"canonical": ["a=?0, b, c;foo=bar"]
},
{
"name": "Example-DictListHeader",
"raw": ["rating=1.5, feelings=(joy sadness)"],
"header_type": "dictionary",
"expected": {
"rating": [1.5, {}],
"feelings": [[
[{"__type": "token", "value": "joy"}, {}],
[{"__type": "token", "value": "sadness"}, {}]
], {}]
}
},
{
"name": "Example-MixDict",
"raw": ["a=(1 2), b=3, c=4;aa=bb, d=(5 6);valid"],
"header_type": "dictionary",
"expected": {
"a": [[
[1, {}],
[2, {}]
], {}],
"b": [3, {}],
"c": [4, {"aa": {"__type": "token", "value": "bb"}}],
"d": [[
[5, {}],
[6, {}]
], {"valid": true}]
},
"canonical": ["a=(1 2), b=3, c=4;aa=bb, d=(5 6);valid"]
},
{
"name": "Example-Hdr (dictionary on one line)",
"raw": ["foo=1, bar=2"],
"header_type": "dictionary",
"expected": {
"foo": [1, {}],
"bar": [2, {}]
}
},
{
"name": "Example-Hdr (dictionary on two lines)",
"raw": ["foo=1", "bar=2"],
"header_type": "dictionary",
"expected": {
"foo": [1, {}],
"bar": [2, {}]
},
"canonical": ["foo=1, bar=2"]
},
{
"name": "Example-IntItemHeader",
"raw": ["5"],
"header_type": "item",
"expected": [5, {}]
},
{
"name": "Example-IntItemHeader (params)",
"raw": ["5; foo=bar"],
"header_type": "item",
"expected": [5, {"foo": {"__type": "token", "value": "bar"}}],
"canonical": ["5;foo=bar"]
},
{
"name": "Example-IntegerHeader",
"raw": ["42"],
"header_type": "item",
"expected": [42, {}]
},
{
"name": "Example-FloatHeader",
"raw": ["4.5"],
"header_type": "item",
"expected": [4.5, {}]
},
{
"name": "Example-StringHeader",
"raw": ["\"hello world\""],
"header_type": "item",
"expected": ["hello world", {}]
},
{
"name": "Example-BinaryHdr",
"raw": [":cHJldGVuZCB0aGlzIGlzIGJpbmFyeSBjb250ZW50Lg==:"],
"header_type": "item",
"expected": [{"__type": "binary", "value": "OBZGK5DFNZSCA5DINFZSA2LTEBRGS3TBOJ4SAY3PNZ2GK3TUFY======"}, {}]
},
{
"name": "Example-BoolHdr",
"raw": ["?1"],
"header_type": "item",
"expected": [true, {}]
}
]
+34
View File
@@ -0,0 +1,34 @@
[
{
"name": "empty item",
"raw": [""],
"header_type": "item",
"must_fail": true
},
{
"name": "leading space",
"raw": [" \t 1"],
"header_type": "item",
"must_fail": true
},
{
"name": "trailing space",
"raw": ["1 \t "],
"header_type": "item",
"must_fail": true
},
{
"name": "leading and trailing space",
"raw": [" 1 "],
"header_type": "item",
"expected": [1, {}],
"canonical": ["1"]
},
{
"name": "leading and trailing whitespace",
"raw": [" 1 "],
"header_type": "item",
"expected": [1, {}],
"canonical": ["1"]
}
]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+68
View File
@@ -0,0 +1,68 @@
[
{
"name": "basic list",
"raw": ["1, 42"],
"header_type": "list",
"expected": [[1, {}], [42, {}]]
},
{
"name": "empty list",
"raw": [""],
"header_type": "list",
"expected": [],
"canonical": []
},
{
"name": "leading SP list",
"raw": [" 42, 43"],
"canonical": ["42, 43"],
"header_type": "list",
"expected": [[42, {}], [43, {}]]
},
{
"name": "single item list",
"raw": ["42"],
"header_type": "list",
"expected": [[42, {}]]
},
{
"name": "no whitespace list",
"raw": ["1,42"],
"header_type": "list",
"expected": [[1, {}], [42, {}]],
"canonical": ["1, 42"]
},
{
"name": "extra whitespace list",
"raw": ["1 , 42"],
"header_type": "list",
"expected": [[1, {}], [42, {}]],
"canonical": ["1, 42"]
},
{
"name": "tab separated list",
"raw": ["1\t,\t42"],
"header_type": "list",
"expected": [[1, {}], [42, {}]],
"canonical": ["1, 42"]
},
{
"name": "two line list",
"raw": ["1", "42"],
"header_type": "list",
"expected": [[1, {}], [42, {}]],
"canonical": ["1, 42"]
},
{
"name": "trailing comma list",
"raw": ["1, 42,"],
"header_type": "list",
"must_fail": true
},
{
"name": "empty item list",
"raw": ["1,,42"],
"header_type": "list",
"must_fail": true
}
]
+58
View File
@@ -0,0 +1,58 @@
[
{
"name": "basic list of lists",
"raw": ["(1 2), (42 43)"],
"header_type": "list",
"expected": [[[[1,{}], [2,{}]], {}], [[[42,{}], [43,{}]], {}]]
},
{
"name": "single item list of lists",
"raw": ["(42)"],
"header_type": "list",
"expected": [[[[42,{}]], {}]]
},
{
"name": "empty item list of lists",
"raw": ["()"],
"header_type": "list",
"expected": [[[], {}]]
},
{
"name": "empty middle item list of lists",
"raw": ["(1),(),(42)"],
"header_type": "list",
"expected": [[[[1,{}]], {}], [[], {}], [[[42,{}]], {}]],
"canonical": ["(1), (), (42)"]
},
{
"name": "extra whitespace list of lists",
"raw": ["( 1 42 )"],
"header_type": "list",
"expected": [[[[1,{}], [42,{}]], {}]],
"canonical": ["(1 42)"]
},
{
"name": "wrong whitespace list of lists",
"raw": ["(1\t 42)"],
"header_type": "list",
"must_fail": true
},
{
"name": "no trailing parenthesis list of lists",
"raw": ["(1 42"],
"header_type": "list",
"must_fail": true
},
{
"name": "no trailing parenthesis middle list of lists",
"raw": ["(1 2, (42 43)"],
"header_type": "list",
"must_fail": true
},
{
"name": "no spaces in inner-list",
"raw": ["(abc\"def\"?0123*dXZ3*xyz)"],
"header_type": "list",
"must_fail": true
}
]
File diff suppressed because it is too large. Load diff
+193
View File
@@ -0,0 +1,193 @@
[
{
"name": "basic integer",
"raw": ["42"],
"header_type": "item",
"expected": [42, {}]
},
{
"name": "zero integer",
"raw": ["0"],
"header_type": "item",
"expected": [0, {}]
},
{
"name": "leading 0 zero",
"raw": ["00"],
"header_type": "item",
"expected": [0, {}],
"canonical": ["0"]
},
{
"name": "negative zero",
"raw": ["-0"],
"header_type": "item",
"expected": [0, {}],
"canonical": ["0"]
},
{
"name": "double negative zero",
"raw": ["--0"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative integer",
"raw": ["-42"],
"header_type": "item",
"expected": [-42, {}]
},
{
"name": "leading 0 integer",
"raw": ["042"],
"header_type": "item",
"expected": [42, {}],
"canonical": ["42"]
},
{
"name": "leading 0 negative integer",
"raw": ["-042"],
"header_type": "item",
"expected": [-42, {}],
"canonical": ["-42"]
},
{
"name": "leading 0 zero",
"raw": ["00"],
"header_type": "item",
"expected": [0, {}],
"canonical": ["0"]
},
{
"name": "comma",
"raw": ["2,3"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative non-DIGIT first character",
"raw": ["-a23"],
"header_type": "item",
"must_fail": true
},
{
"name": "sign out of place",
"raw": ["4-2"],
"header_type": "item",
"must_fail": true
},
{
"name": "whitespace after sign",
"raw": ["- 42"],
"header_type": "item",
"must_fail": true
},
{
"name": "long integer",
"raw": ["123456789012345"],
"header_type": "item",
"expected": [123456789012345, {}]
},
{
"name": "long negative integer",
"raw": ["-123456789012345"],
"header_type": "item",
"expected": [-123456789012345, {}]
},
{
"name": "too long integer",
"raw": ["1234567890123456"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative too long integer",
"raw": ["-1234567890123456"],
"header_type": "item",
"must_fail": true
},
{
"name": "simple decimal",
"raw": ["1.23"],
"header_type": "item",
"expected": [1.23, {}]
},
{
"name": "negative decimal",
"raw": ["-1.23"],
"header_type": "item",
"expected": [-1.23, {}]
},
{
"name": "decimal, whitespace after decimal",
"raw": ["1. 23"],
"header_type": "item",
"must_fail": true
},
{
"name": "decimal, whitespace before decimal",
"raw": ["1 .23"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative decimal, whitespace after sign",
"raw": ["- 1.23"],
"header_type": "item",
"must_fail": true
},
{
"name": "tricky precision decimal",
"raw": ["123456789012.1"],
"header_type": "item",
"expected": [123456789012.1, {}]
},
{
"name": "double decimal decimal",
"raw": ["1.5.4"],
"header_type": "item",
"must_fail": true
},
{
"name": "adjacent double decimal decimal",
"raw": ["1..4"],
"header_type": "item",
"must_fail": true
},
{
"name": "decimal with three fractional digits",
"raw": ["1.123"],
"header_type": "item",
"expected": [1.123, {}]
},
{
"name": "negative decimal with three fractional digits",
"raw": ["-1.123"],
"header_type": "item",
"expected": [-1.123, {}]
},
{
"name": "decimal with four fractional digits",
"raw": ["1.1234"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative decimal with four fractional digits",
"raw": ["-1.1234"],
"header_type": "item",
"must_fail": true
},
{
"name": "decimal with thirteen integer digits",
"raw": ["1234567890123.0"],
"header_type": "item",
"must_fail": true
},
{
"name": "negative decimal with thirteen integer digits",
"raw": ["-1234567890123.0"],
"header_type": "item",
"must_fail": true
}
]
+113
View File
@@ -0,0 +1,113 @@
[
{
"name": "basic parameterised dict",
"raw": ["abc=123;a=1;b=2, def=456, ghi=789;q=9;r=\"+w\""],
"header_type": "dictionary",
"expected": {
"abc": [123, {"a": 1, "b": 2}],
"def": [456, {}],
"ghi": [789, {"q": 9, "r": "+w"}]
}
},
{
"name": "single item parameterised dict",
"raw": ["a=b; q=1.0"],
"header_type": "dictionary",
"expected": {
"a": [{"__type": "token", "value": "b"}, {"q": 1.0}]
},
"canonical": ["a=b;q=1.0"]
},
{
"name": "list item parameterised dictionary",
"raw": ["a=(1 2); q=1.0"],
"header_type": "dictionary",
"expected": {"a": [[[1, {}], [2, {}]], {"q": 1.0}]},
"canonical": ["a=(1 2);q=1.0"]
},
{
"name": "missing parameter value parameterised dict",
"raw": ["a=3;c;d=5"],
"header_type": "dictionary",
"expected": {
"a": [3, {"c": true, "d": 5}]
}
},
{
"name": "terminal missing parameter value parameterised dict",
"raw": ["a=3;c=5;d"],
"header_type": "dictionary",
"expected": {
"a": [3, {"c": 5, "d": true}]
}
},
{
"name": "no whitespace parameterised dict",
"raw": ["a=b;c=1,d=e;f=2"],
"header_type": "dictionary",
"expected": {
"a": [{"__type": "token", "value": "b"}, {"c": 1}],
"d": [{"__type": "token", "value": "e"}, {"f": 2}]
},
"canonical": ["a=b;c=1, d=e;f=2"]
},
{
"name": "whitespace before = parameterised dict",
"raw": ["a=b;q =0.5"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "whitespace after = parameterised dict",
"raw": ["a=b;q= 0.5"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "whitespace before ; parameterised dict",
"raw": ["a=b ;q=0.5"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "whitespace after ; parameterised dict",
"raw": ["a=b; q=0.5"],
"header_type": "dictionary",
"expected": {
"a": [{"__type": "token", "value": "b"}, {"q": 0.5}]
},
"canonical": ["a=b;q=0.5"]
},
{
"name": "extra whitespace parameterised dict",
"raw": ["a=b; c=1 , d=e; f=2; g=3"],
"header_type": "dictionary",
"expected": {
"a": [{"__type": "token", "value": "b"}, {"c": 1}],
"d": [{"__type": "token", "value": "e"}, {"f": 2, "g": 3}]
},
"canonical": ["a=b;c=1, d=e;f=2;g=3"]
},
{
"name": "two lines parameterised list",
"raw": ["a=b;c=1", "d=e;f=2"],
"header_type": "dictionary",
"expected": {
"a": [{"__type": "token", "value": "b"}, {"c": 1}],
"d": [{"__type": "token", "value": "e"}, {"f": 2}]
},
"canonical": ["a=b;c=1, d=e;f=2"]
},
{
"name": "trailing comma parameterised list",
"raw": ["a=b; q=1.0,"],
"header_type": "dictionary",
"must_fail": true
},
{
"name": "empty item parameterised list",
"raw": ["a=b; q=1.0,,c=d"],
"header_type": "dictionary",
"must_fail": true
}
]
+108
View File
@@ -0,0 +1,108 @@
[
{
"name": "basic parameterised list",
"raw": ["abc_123;a=1;b=2; cdef_456, ghi;q=9;r=\"+w\""],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "abc_123"}, {"a": 1, "b": 2, "cdef_456": true}],
[{"__type": "token", "value": "ghi"}, {"q": 9, "r": "+w"}]
],
"canonical": ["abc_123;a=1;b=2;cdef_456, ghi;q=9;r=\"+w\""]
},
{
"name": "single item parameterised list",
"raw": ["text/html;q=1.0"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {"q": 1.0}]
]
},
{
"name": "missing parameter value parameterised list",
"raw": ["text/html;a;q=1.0"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {"a": true, "q": 1.0}]
]
},
{
"name": "missing terminal parameter value parameterised list",
"raw": ["text/html;q=1.0;a"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {"q": 1.0, "a": true}]
]
},
{
"name": "no whitespace parameterised list",
"raw": ["text/html,text/plain;q=0.5"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {}],
[{"__type": "token", "value": "text/plain"}, {"q": 0.5}]
],
"canonical": ["text/html, text/plain;q=0.5"]
},
{
"name": "whitespace before = parameterised list",
"raw": ["text/html, text/plain;q =0.5"],
"header_type": "list",
"must_fail": true
},
{
"name": "whitespace after = parameterised list",
"raw": ["text/html, text/plain;q= 0.5"],
"header_type": "list",
"must_fail": true
},
{
"name": "whitespace before ; parameterised list",
"raw": ["text/html, text/plain ;q=0.5"],
"header_type": "list",
"must_fail": true
},
{
"name": "whitespace after ; parameterised list",
"raw": ["text/html, text/plain; q=0.5"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {}],
[{"__type": "token", "value": "text/plain"}, {"q": 0.5}]
],
"canonical": ["text/html, text/plain;q=0.5"]
},
{
"name": "extra whitespace parameterised list",
"raw": ["text/html , text/plain; q=0.5; charset=utf-8"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {}],
[{"__type": "token", "value": "text/plain"},
{"q": 0.5, "charset": {"__type": "token", "value": "utf-8"}
}]
],
"canonical": ["text/html, text/plain;q=0.5;charset=utf-8"]
},
{
"name": "two lines parameterised list",
"raw": ["text/html", "text/plain;q=0.5"],
"header_type": "list",
"expected": [
[{"__type": "token", "value": "text/html"}, {}],
[{"__type": "token", "value": "text/plain"}, {"q": 0.5}]
],
"canonical": ["text/html, text/plain;q=0.5"]
},
{
"name": "trailing comma parameterised list",
"raw": ["text/html,text/plain;q=0.5,"],
"header_type": "list",
"must_fail": true
},
{
"name": "empty item parameterised list",
"raw": ["text/html,,text/plain;q=0.5,"],
"header_type": "list",
"must_fail": true
}
]
+36
View File
@@ -0,0 +1,36 @@
[
{
"name": "parameterised inner list",
"raw": ["(abc_123);a=1;b=2, cdef_456"],
"header_type": "list",
"expected": [
[
[[{"__type": "token", "value": "abc_123"}, {}]],
{"a": 1, "b": 2}
],
[{"__type": "token", "value": "cdef_456"}, {}]
]
},
{
"name": "parameterised inner list item",
"raw": ["(abc_123;a=1;b=2;cdef_456)"],
"header_type": "list",
"expected": [
[
[[{"__type": "token", "value": "abc_123"}, {"a": 1, "b": 2, "cdef_456": true}]],
{}
]
]
},
{
"name": "parameterised inner list with parameterised item",
"raw": ["(abc_123;a=1;b=2);cdef_456"],
"header_type": "list",
"expected": [
[
[[{"__type": "token", "value": "abc_123"}, {"a": 1, "b": 2}]],
{"cdef_456": true}
]
]
}
]
File diff suppressed because it is too large. Load diff
+80
View File
@@ -0,0 +1,80 @@
[
{
"name": "basic string",
"raw": ["\"foo bar\""],
"header_type": "item",
"expected": ["foo bar", {}]
},
{
"name": "empty string",
"raw": ["\"\""],
"header_type": "item",
"expected": ["", {}]
},
{
"name": "long string",
"raw": ["\"foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \""],
"header_type": "item",
"expected": ["foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo ", {}]
},
{
"name": "whitespace string",
"raw": ["\" \""],
"header_type": "item",
"expected": [" ", {}]
},
{
"name": "non-ascii string",
"raw": ["\"füü\""],
"header_type": "item",
"must_fail": true
},
{
"name": "tab in string",
"raw": ["\"\\t\""],
"header_type": "item",
"must_fail": true
},
{
"name": "newline in string",
"raw": ["\" \\n \""],
"header_type": "item",
"must_fail": true
},
{
"name": "single quoted string",
"raw": ["'foo'"],
"header_type": "item",
"must_fail": true
},
{
"name": "unbalanced string",
"raw": ["\"foo"],
"header_type": "item",
"must_fail": true
},
{
"name": "string quoting",
"raw": ["\"foo \\\"bar\\\" \\\\ baz\""],
"header_type": "item",
"expected": ["foo \"bar\" \\ baz", {}]
},
{
"name": "bad string quoting",
"raw": ["\"foo \\,\""],
"header_type": "item",
"must_fail": true
},
{
"name": "ending string quote",
"raw": ["\"foo \\\""],
"header_type": "item",
"must_fail": true
},
{
"name": "abruptly ending string quote",
"raw": ["\"foo \\"],
"header_type": "item",
"must_fail": true
}
]
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
[
{
"name": "basic token - item",
"raw": ["a_b-c.d3:f%00/*"],
"header_type": "item",
"expected": [{"__type": "token", "value": "a_b-c.d3:f%00/*"}, {}]
},
{
"name": "token with capitals - item",
"raw": ["fooBar"],
"header_type": "item",
"expected": [{"__type": "token", "value": "fooBar"}, {}]
},
{
"name": "token starting with capitals - item",
"raw": ["FooBar"],
"header_type": "item",
"expected": [{"__type": "token", "value": "FooBar"}, {}]
},
{
"name": "basic token - list",
"raw": ["a_b-c3/*"],
"header_type": "list",
"expected": [[{"__type": "token", "value": "a_b-c3/*"}, {}]]
},
{
"name": "token with capitals - list",
"raw": ["fooBar"],
"header_type": "list",
"expected": [[{"__type": "token", "value": "fooBar"}, {}]]
},
{
"name": "token starting with capitals - list",
"raw": ["FooBar"],
"header_type": "list",
"expected": [[{"__type": "token", "value": "FooBar"}, {}]]
}
]