mirror of
https://github.com/apple/swift-http-structured-headers
synced 2026-11-24 04:37:50 +00:00
Implement the Serializer.
This commit is contained in:
1 parent
e6e0c68caf
commit
cf08d29cb0
15 files changed
+7806
-56
No files matched your search
@@ -0,0 +1,51 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
let asciiSpace = UInt8(ascii: " ")
|
||||
let asciiTab = UInt8(ascii: "\t")
|
||||
let asciiOpenParenthesis = UInt8(ascii: "(")
|
||||
let asciiCloseParenthesis = UInt8(ascii: ")")
|
||||
let asciiDash = UInt8(ascii: "-")
|
||||
let asciiUnderscore = UInt8(ascii: "_")
|
||||
let asciiZero = UInt8(ascii: "0")
|
||||
let asciiOne = UInt8(ascii: "1")
|
||||
let asciiNine = UInt8(ascii: "9")
|
||||
let asciiDigits = asciiZero...asciiNine
|
||||
let asciiDquote = UInt8(ascii: "\"")
|
||||
let asciiColon = UInt8(ascii: ":")
|
||||
let asciiSemicolon = UInt8(ascii: ";")
|
||||
let asciiBackslash = UInt8(ascii: "\\")
|
||||
let asciiQuestionMark = UInt8(ascii: "?")
|
||||
let asciiExclamationMark = UInt8(ascii: "!")
|
||||
let asciiOctothorpe = UInt8(ascii: "#")
|
||||
let asciiDollar = UInt8(ascii: "$")
|
||||
let asciiPercent = UInt8(ascii: "%")
|
||||
let asciiAmpersand = UInt8(ascii: "&")
|
||||
let asciiSquote = UInt8(ascii: "'")
|
||||
let asciiCaret = UInt8(ascii: "^")
|
||||
let asciiBacktick = UInt8(ascii: "`")
|
||||
let asciiPipe = UInt8(ascii: "|")
|
||||
let asciiTilde = UInt8(ascii: "~")
|
||||
let asciiAsterisk = UInt8(ascii: "*")
|
||||
let asciiEqual = UInt8(ascii: "=")
|
||||
let asciiPlus = UInt8(ascii: "+")
|
||||
let asciiSlash = UInt8(ascii: "/")
|
||||
let asciiPeriod = UInt8(ascii: ".")
|
||||
let asciiComma = UInt8(ascii: ",")
|
||||
let asciiCapitalA = UInt8(ascii: "A")
|
||||
let asciiCapitalZ = UInt8(ascii: "Z")
|
||||
let asciiLowerA = UInt8(ascii: "a")
|
||||
let asciiLowerZ = UInt8(ascii: "z")
|
||||
let asciiCapitals = asciiCapitalA...asciiCapitalZ
|
||||
let asciiLowercases = asciiLowerA...asciiLowerZ
|
||||
@@ -29,7 +29,7 @@ extension ItemOrInnerList: Hashable { }
|
||||
public 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 decimal(PseudoDecimal)
|
||||
case string(String)
|
||||
case undecodedByteSequence(BaseData)
|
||||
case token(BaseData)
|
||||
@@ -49,7 +49,7 @@ extension BareItem: ExpressibleByIntegerLiteral {
|
||||
|
||||
extension BareItem: ExpressibleByFloatLiteral {
|
||||
public init(floatLiteral value: Float64) {
|
||||
self = .decimal(value)
|
||||
self = .decimal(.init(floatLiteral: value))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,11 @@ extension BareItem: Hashable { }
|
||||
public struct Item<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
public var bareItem: BareItem<BaseData>
|
||||
public var parameters: OrderedMap<BaseData, BareItem<BaseData>>
|
||||
|
||||
public init(bareItem: BareItem<BaseData>, parameters: OrderedMap<BaseData, BareItem<BaseData>>) {
|
||||
self.bareItem = bareItem
|
||||
self.parameters = parameters
|
||||
}
|
||||
}
|
||||
|
||||
extension Item: Hashable { }
|
||||
@@ -144,4 +149,9 @@ extension BareInnerList.Index: Comparable {
|
||||
public struct InnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
public var bareInnerList: BareInnerList<BaseData>
|
||||
public var parameters: OrderedMap<BaseData, BareItem<BaseData>>
|
||||
|
||||
public init(bareInnerList: BareInnerList<BaseData>, parameters: OrderedMap<BaseData, BareItem<BaseData>>) {
|
||||
self.bareInnerList = bareInnerList
|
||||
self.parameters = parameters
|
||||
}
|
||||
}
|
||||
@@ -142,7 +142,8 @@ extension BareItemDecoder: SingleValueDecodingContainer {
|
||||
throw StructuredHeaderError.invalidTypeForItem
|
||||
}
|
||||
|
||||
return T(decimal)
|
||||
// Going via Double is a bit sad. Swift Numerics would help here.
|
||||
return T(Double(decimal))
|
||||
}
|
||||
|
||||
private func _decodeFixedWidthInteger<T: FixedWidthInteger>(_ type: T.Type) throws -> T {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK:- StructuredHeaderError
|
||||
public struct StructuredHeaderError: Error {
|
||||
private enum _BaseError: Hashable {
|
||||
case invalidTrailingBytes
|
||||
|
||||
@@ -12,44 +12,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
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.
|
||||
public struct StructuredFieldParser<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
|
||||
// Right now I'm on the fence about whether this should be generic. It's convenient,
|
||||
@@ -322,8 +284,9 @@ extension StructuredFieldParser {
|
||||
}
|
||||
|
||||
// Same notes here as above
|
||||
let baseFloat = Float64(String(decoding: integerBytes, as: UTF8.self))!
|
||||
return .decimal(baseFloat * Float64(sign))
|
||||
var decimal = PseudoDecimal(bytes: integerBytes)
|
||||
decimal.mantissa *= Int64(sign)
|
||||
return .decimal(decimal)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
// We need this for string formatting of floats. Remove if we don't need that anymore.
|
||||
import Foundation
|
||||
|
||||
fileprivate let validIntegerRange = Int64(-999999999999999)...Int64(999999999999999)
|
||||
|
||||
public struct StructuredFieldSerializer {
|
||||
// TODO: Allow users to choose this.
|
||||
private var data: [UInt8]
|
||||
|
||||
public init() {
|
||||
self.data = []
|
||||
}
|
||||
}
|
||||
|
||||
extension StructuredFieldSerializer {
|
||||
// TODO: decide if this is the best API, it forces allocations.
|
||||
public mutating func writeDictionaryHeader<BaseData: RandomAccessCollection>(_ root: OrderedMap<BaseData, ItemOrInnerList<BaseData>>) throws -> [UInt8] where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
guard root.count > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
defer {
|
||||
self.data.removeAll(keepingCapacity: true)
|
||||
}
|
||||
try self.serializeADictionary(root)
|
||||
return self.data
|
||||
}
|
||||
|
||||
public mutating func writeListHeader<BaseData: RandomAccessCollection>(_ list: [ItemOrInnerList<BaseData>]) throws -> [UInt8] where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
guard list.count > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
defer {
|
||||
self.data.removeAll(keepingCapacity: true)
|
||||
}
|
||||
try self.serializeAList(list)
|
||||
return self.data
|
||||
}
|
||||
|
||||
public mutating func writeItemHeader<BaseData: RandomAccessCollection>(_ item: Item<BaseData>) throws -> [UInt8] where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
defer {
|
||||
self.data.removeAll(keepingCapacity: true)
|
||||
}
|
||||
try self.serializeAnItem(item)
|
||||
return self.data
|
||||
}
|
||||
}
|
||||
|
||||
extension StructuredFieldSerializer {
|
||||
private mutating func serializeADictionary<BaseData: RandomAccessCollection>(_ dictionary: OrderedMap<BaseData, ItemOrInnerList<BaseData>>) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
for (name, value) in dictionary {
|
||||
try self.serializeAKey(name)
|
||||
|
||||
if case .item(let item) = value, case .bool(true) = item.bareItem {
|
||||
try self.serializeParameters(item.parameters)
|
||||
} else {
|
||||
self.data.append(asciiEqual)
|
||||
|
||||
switch value {
|
||||
case .innerList(let inner):
|
||||
try self.serializeAnInnerList(inner)
|
||||
case .item(let item):
|
||||
try self.serializeAnItem(item)
|
||||
}
|
||||
}
|
||||
|
||||
self.data.append(asciiComma)
|
||||
self.data.append(asciiSpace)
|
||||
}
|
||||
|
||||
self.data.removeLast(2)
|
||||
}
|
||||
|
||||
private mutating func serializeAList<BaseData: RandomAccessCollection>(_ list: [ItemOrInnerList<BaseData>]) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
for element in list.dropLast() {
|
||||
switch element {
|
||||
case .innerList(let innerList):
|
||||
try self.serializeAnInnerList(innerList)
|
||||
case .item(let item):
|
||||
try self.serializeAnItem(item)
|
||||
}
|
||||
|
||||
self.data.append(asciiComma)
|
||||
self.data.append(asciiSpace)
|
||||
}
|
||||
|
||||
if let last = list.last {
|
||||
switch last {
|
||||
case .innerList(let innerList):
|
||||
try self.serializeAnInnerList(innerList)
|
||||
case .item(let item):
|
||||
try self.serializeAnItem(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func serializeAnInnerList<BaseData: RandomAccessCollection>(_ innerList: InnerList<BaseData>) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
self.data.append(asciiOpenParenthesis)
|
||||
|
||||
for item in innerList.bareInnerList.dropLast() {
|
||||
try self.serializeAnItem(item)
|
||||
self.data.append(asciiSpace)
|
||||
}
|
||||
|
||||
if let last = innerList.bareInnerList.last {
|
||||
try self.serializeAnItem(last)
|
||||
}
|
||||
|
||||
self.data.append(asciiCloseParenthesis)
|
||||
|
||||
try self.serializeParameters(innerList.parameters)
|
||||
}
|
||||
|
||||
private mutating func serializeAnItem<BaseData: RandomAccessCollection>(_ item: Item<BaseData>) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
try self.serializeABareItem(item.bareItem)
|
||||
try self.serializeParameters(item.parameters)
|
||||
}
|
||||
|
||||
private mutating func serializeParameters<BaseData: RandomAccessCollection>(_ parameters: OrderedMap<BaseData, BareItem<BaseData>>) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
for (key, value) in parameters {
|
||||
self.data.append(asciiSemicolon)
|
||||
try self.serializeAKey(key)
|
||||
|
||||
if case .bool(true) = value {
|
||||
// Don't serialize boolean true
|
||||
continue
|
||||
}
|
||||
|
||||
self.data.append(asciiEqual)
|
||||
try self.serializeABareItem(value)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func serializeAKey<BaseData: RandomAccessCollection>(_ key: BaseData) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
// We touch each byte twice here, but that's ok: this is cache friendly and less branchy (the copy gets to be memcpy in some cases!)
|
||||
try key.validateStructuredHeaderKey()
|
||||
self.data.append(contentsOf: key)
|
||||
}
|
||||
|
||||
private mutating func serializeABareItem<BaseData: RandomAccessCollection>(_ item: BareItem<BaseData>) throws where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
switch item {
|
||||
case .integer(let int):
|
||||
guard let wideInt = Int64(exactly: int), validIntegerRange.contains(wideInt) else {
|
||||
throw StructuredHeaderError.invalidIntegerOrDecimal
|
||||
}
|
||||
|
||||
self.data.append(contentsOf: String(int, radix: 10).utf8)
|
||||
|
||||
case .decimal(let decimal):
|
||||
self.data.append(contentsOf: String(decimal).utf8)
|
||||
case .string(let string):
|
||||
let bytes = string.utf8
|
||||
guard bytes.allSatisfy({ !(0x00...0x1f).contains($0) && $0 != 0x7f && $0 < 0x80 }) else {
|
||||
throw StructuredHeaderError.invalidString
|
||||
}
|
||||
self.data.append(asciiDquote)
|
||||
for byte in bytes {
|
||||
if byte == asciiBackslash || byte == asciiDquote {
|
||||
self.data.append(asciiBackslash)
|
||||
}
|
||||
self.data.append(byte)
|
||||
}
|
||||
self.data.append(asciiDquote)
|
||||
case .token(let token):
|
||||
switch token.first {
|
||||
case .some(asciiCapitals), .some(asciiLowercases), .some(asciiAsterisk):
|
||||
// Good
|
||||
()
|
||||
default:
|
||||
throw StructuredHeaderError.invalidToken
|
||||
}
|
||||
|
||||
for byte in token {
|
||||
switch byte {
|
||||
// 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
|
||||
()
|
||||
default:
|
||||
// Bad token
|
||||
throw StructuredHeaderError.invalidToken
|
||||
}
|
||||
}
|
||||
|
||||
self.data.append(contentsOf: token)
|
||||
case .undecodedByteSequence(let bytes):
|
||||
// We require the user to have gotten this right.
|
||||
self.data.append(asciiColon)
|
||||
self.data.append(contentsOf: bytes)
|
||||
self.data.append(asciiColon)
|
||||
case .bool(let bool):
|
||||
self.data.append(asciiQuestionMark)
|
||||
let character = bool ? asciiOne : asciiZero
|
||||
self.data.append(character)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RandomAccessCollection where Element == UInt8 {
|
||||
func validateStructuredHeaderKey() throws {
|
||||
if let firstByte = self.first {
|
||||
switch firstByte {
|
||||
case asciiLowercases, asciiAsterisk:
|
||||
// Good
|
||||
()
|
||||
default:
|
||||
throw StructuredHeaderError.invalidKey
|
||||
}
|
||||
}
|
||||
|
||||
let validKey = self.dropFirst().allSatisfy {
|
||||
switch $0 {
|
||||
case asciiLowercases, asciiDigits, asciiUnderscore,
|
||||
asciiDash, asciiPeriod, asciiAsterisk:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
guard validKey else {
|
||||
throw StructuredHeaderError.invalidKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
/// 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.
|
||||
///
|
||||
/// Note that this preserves _original_ insertion order: if you overwrite a key's value, the
|
||||
/// key does not move to "last". This is a specific requirement for Structured Headers and may
|
||||
/// harm the generality of this implementation.
|
||||
public struct OrderedMap<Key, Value> where Key: Hashable {
|
||||
private var backing: [Entry]
|
||||
|
||||
@@ -35,9 +39,12 @@ public struct OrderedMap<Key, Value> where Key: Hashable {
|
||||
}
|
||||
set {
|
||||
if let existing = self.backing.firstIndex(where: { $0.key == key }) {
|
||||
self.backing.remove(at: existing)
|
||||
}
|
||||
if let newValue = newValue {
|
||||
if let newValue = newValue {
|
||||
self.backing[existing] = Entry(key: key, value: newValue)
|
||||
} else {
|
||||
self.backing.remove(at: existing)
|
||||
}
|
||||
} else if let newValue = newValue {
|
||||
self.backing.append(Entry(key: key, value: newValue))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(GLibc)
|
||||
import GLibc
|
||||
#else
|
||||
#error("Unsupported OS")
|
||||
#endif
|
||||
|
||||
/// A pseudo-representation of a decimal number.
|
||||
///
|
||||
/// The goal of this type is to remove a dependency on Foundation. As Structured Headers require only a very simple
|
||||
/// conception of a decimal, there is no need to bring in the entire Foundation dependency: it's sufficient to define
|
||||
/// a trivial type to represent the _idea_ of a decimal number. We don't have any requirement to do math on this type:
|
||||
/// we just need to be able to use the type to store the fixed point representation of the value.
|
||||
///
|
||||
/// For ease of conversion to _actual_ decimal types, we use a mantissa/exponent/sign representation much like other
|
||||
/// types would. Note that this is a base 10 exponent, not a base 2 exponent: the exponent multiplies by 10, not 2. We also
|
||||
/// encode the sign bit implicitly in the sign bit of the mantissa.
|
||||
///
|
||||
/// The range of this type is from -999,999,999,999.999 to 999,999,999,999.999. This means the maximum value of the significand
|
||||
/// is 999,999,999,999,999. The exponent ranges from -3 to 0. Additionally, there may be no more than 12 decimal digits before
|
||||
/// the decimal place, so while the maximum value of the significand is 999,999,999,999,999, that is only acceptable if the
|
||||
/// exponent is -3.
|
||||
public struct PseudoDecimal: Hashable {
|
||||
private var _mantissa: Int64
|
||||
|
||||
private var _exponent: Int8
|
||||
|
||||
public var mantissa: Int64 {
|
||||
get {
|
||||
return self._mantissa
|
||||
}
|
||||
set {
|
||||
Self.fatalValidate(mantissa: newValue, exponent: self._exponent)
|
||||
self._mantissa = newValue
|
||||
}
|
||||
}
|
||||
|
||||
public var exponent: Int8 {
|
||||
get {
|
||||
return self._exponent
|
||||
}
|
||||
set {
|
||||
Self.fatalValidate(mantissa: self._mantissa, exponent: newValue)
|
||||
self._exponent = newValue
|
||||
}
|
||||
}
|
||||
|
||||
public init(mantissa: Int, exponent: Int) {
|
||||
self._mantissa = Int64(mantissa)
|
||||
self._exponent = Int8(exponent)
|
||||
Self.fatalValidate(mantissa: self._mantissa, exponent: self._exponent)
|
||||
}
|
||||
|
||||
internal init<Bytes: RandomAccessCollection>(bytes: Bytes) where Bytes.Element == UInt8 {
|
||||
let elements = bytes.split(separator: asciiPeriod, maxSplits: 1)
|
||||
// Precondition is safe, this can only be called from the parser which has already validated the formatting.
|
||||
precondition(elements.count == 2)
|
||||
|
||||
var nonSignBytes = bytes.count
|
||||
var sign = Int64(1)
|
||||
if bytes.first == asciiDash {
|
||||
sign = -1
|
||||
nonSignBytes &-= 1
|
||||
}
|
||||
|
||||
var mantissa = Int64(0)
|
||||
var periodOffset = 0
|
||||
for (offset, element) in bytes.enumerated() {
|
||||
if element == asciiPeriod {
|
||||
periodOffset = offset
|
||||
continue
|
||||
}
|
||||
|
||||
let integerValue = element - asciiZero
|
||||
assert(integerValue < 10 && integerValue >= 0)
|
||||
|
||||
mantissa *= 10
|
||||
mantissa += Int64(integerValue)
|
||||
}
|
||||
|
||||
self._mantissa = mantissa * sign
|
||||
|
||||
// Check where the period was in relation to the rest of the string. We can have anywhere between
|
||||
// 1 and 3 digits after the period. Note that if the period was last, offset == nonSignBytes - 1, so
|
||||
// the actual values here are 2 to 4.
|
||||
switch nonSignBytes - periodOffset {
|
||||
case 2:
|
||||
self._exponent = -1
|
||||
case 3:
|
||||
self._exponent = -2
|
||||
case 4:
|
||||
self._exponent = -3
|
||||
default:
|
||||
preconditionFailure("Unexpected value of offset: have \(nonSignBytes) bytes and offset \(periodOffset)")
|
||||
}
|
||||
}
|
||||
|
||||
private static func validate(mantissa: Int64, exponent: Int8) throws {
|
||||
// We compare against our upper and lower bounds. The maximum allowable magnitude of the mantissa is contingent
|
||||
// on the exponent.
|
||||
switch exponent {
|
||||
case 0 where mantissa.magnitude <= 999_999_999_999,
|
||||
-1 where mantissa.magnitude <= 9_999_999_999_999,
|
||||
-2 where mantissa.magnitude <= 99_999_999_999_999,
|
||||
-3 where mantissa.magnitude <= 999_999_999_999_999:
|
||||
// All acceptable
|
||||
()
|
||||
default:
|
||||
throw StructuredHeaderError.invalidIntegerOrDecimal
|
||||
}
|
||||
}
|
||||
|
||||
private static func fatalValidate(mantissa: Int64, exponent: Int8) {
|
||||
do {
|
||||
try Self.validate(mantissa: mantissa, exponent: exponent)
|
||||
} catch {
|
||||
preconditionFailure("Invalid value for structured header decimal: mantissa \(mantissa) exponent \(exponent)")
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate mutating func canonicalise() {
|
||||
// This cannonicalises the decimal into a standard format suitable for direct serialisation.
|
||||
//
|
||||
// Structured headers prefers decimals to be serialized with no leading or trailing zeros. Leading zeros
|
||||
// are easily avoided, but trailing zeros are a function of the exponent. As we must have at least one
|
||||
// digit after the decimal place, exponent zero is not suitable, so if that's our current exponent we
|
||||
// will arrange to have exponent -1. If the exponent is -1, we'll leave it alone. For -3 and -2 exponents
|
||||
// we'll try to cascade them down toward exponent -1 if we can divide the mantissa by 10 evenly, as that will
|
||||
// eliminate trailing zeros after the decimal place.
|
||||
switch self._exponent {
|
||||
case 0:
|
||||
self._mantissa *= 10
|
||||
self._exponent = -1
|
||||
case -3 where self._mantissa % 10 == 0:
|
||||
self._mantissa /= 10
|
||||
self._exponent &+= 1
|
||||
fallthrough
|
||||
case -2:
|
||||
if self._mantissa % 10 == 0 {
|
||||
self._mantissa /= 10
|
||||
self._exponent &+= 1
|
||||
}
|
||||
default:
|
||||
// These other cases don't require any work.
|
||||
()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension PseudoDecimal: ExpressibleByFloatLiteral {
|
||||
public init(_ value: Double) throws {
|
||||
// This is kinda dumb, but it's basically good enough: we multiply by 1000 and then round that type
|
||||
// to an integer.
|
||||
var multiplied = value * 1000
|
||||
multiplied.round(.toNearestOrEven)
|
||||
let mantissa = Int64(exactly: multiplied)!
|
||||
self._mantissa = mantissa
|
||||
self._exponent = -3
|
||||
try Self.validate(mantissa: self._mantissa, exponent: self._exponent)
|
||||
}
|
||||
|
||||
public init(floatLiteral value: Double) {
|
||||
do {
|
||||
try self.init(value)
|
||||
} catch {
|
||||
preconditionFailure("Invalid value for structured header decimal: \(value)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension String {
|
||||
public init(_ decimal: PseudoDecimal) {
|
||||
var local = decimal
|
||||
local.canonicalise()
|
||||
|
||||
// First, serialize the mantissa. We do this with a magnitude because we add a sign later.
|
||||
var string = String(local.mantissa.magnitude, radix: 10)
|
||||
|
||||
// Then, based on the exponent, we insert a period. Turns out the offset for
|
||||
// where we want to insert this character is exactly the exponent.
|
||||
// Before we do this, quick check: we may not even have that many digits! If we don't,
|
||||
// we need to pad with leading zeros until we do.
|
||||
let neededPadding = Int(local.exponent.magnitude) - string.count
|
||||
if neededPadding > 0 {
|
||||
string = String(repeating: "0", count: neededPadding) + string
|
||||
}
|
||||
|
||||
let periodIndex = string.index(string.endIndex, offsetBy: Int(local.exponent))
|
||||
let needLeadingZero = periodIndex == string.startIndex
|
||||
string.insert(".", at: periodIndex)
|
||||
|
||||
// One check: did we insert the period at the front? If we did, add a leading zero. Note
|
||||
// that the above insert invalidated the indices so we must ask for the new start index.
|
||||
if needLeadingZero {
|
||||
string.insert("0", at: string.startIndex)
|
||||
}
|
||||
if local.mantissa < 0 {
|
||||
string.insert("-", at: string.startIndex)
|
||||
}
|
||||
self = string
|
||||
}
|
||||
}
|
||||
|
||||
// Swift Numerics would let us do this for all the floating point types.
|
||||
extension Double {
|
||||
public init(_ pseudoDecimal: PseudoDecimal) {
|
||||
self = Double(pseudoDecimal.mantissa) * pow(10, Double(pseudoDecimal.exponent))
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,11 @@ enum FixturesLoader {
|
||||
return URL(string: "../TestFixtures/", relativeTo: myURL)!.absoluteURL
|
||||
}
|
||||
|
||||
static var fixtures: [StructuredHeaderTestFixture] {
|
||||
private static var serializationFixturesDirectory: URL {
|
||||
return fixturesDirectory.appendingPathComponent("serialisation-tests").absoluteURL
|
||||
}
|
||||
|
||||
static var parsingFixtures: [StructuredHeaderTestFixture] {
|
||||
// ContentsOfDirectory can throw if it hits EINTR, just spin
|
||||
var files: [URL]? = nil
|
||||
for _ in 0..<1000 {
|
||||
@@ -44,14 +48,40 @@ enum FixturesLoader {
|
||||
return try! decoder.decode([StructuredHeaderTestFixture].self, from: content)
|
||||
}
|
||||
}
|
||||
|
||||
static var serializingFixtures: [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: serializationFixturesDirectory, 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 list of header fields that should be parsed. Not present if this is a serialization test.
|
||||
var raw: [String]?
|
||||
|
||||
/// The type to use to parse the fields
|
||||
var headerType: String
|
||||
@@ -100,4 +130,13 @@ enum JSONSchema: Decodable {
|
||||
preconditionFailure("Failed to decode at \(container.codingPath)")
|
||||
}
|
||||
}
|
||||
|
||||
var isArray: Bool {
|
||||
switch self {
|
||||
case .array:
|
||||
return true
|
||||
case .dictionary, .integer, .double, .string, .bool:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-7
@@ -19,7 +19,7 @@ enum FixtureTestError: Error {
|
||||
case base64DecodingFailed
|
||||
}
|
||||
|
||||
final class StructuredHeadersTests: XCTestCase {
|
||||
final class StructuredFieldParserTests: XCTestCase {
|
||||
enum TestResult<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
|
||||
case dictionary(OrderedMap<BaseData, ItemOrInnerList<BaseData>>)
|
||||
case list([ItemOrInnerList<BaseData>])
|
||||
@@ -31,12 +31,11 @@ final class StructuredHeadersTests: XCTestCase {
|
||||
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)")
|
||||
XCTAssertEqual(String(baseDecimal), String(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)")
|
||||
// We just cannot tell the difference here, so we tolerate this flexibility.
|
||||
XCTAssertEqual(Double(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)):
|
||||
@@ -165,7 +164,11 @@ final class StructuredHeadersTests: XCTestCase {
|
||||
|
||||
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)
|
||||
guard let raw = fixture.raw else {
|
||||
// Serialization only test, skip.
|
||||
return
|
||||
}
|
||||
let joinedHeaders = Array(raw.joined(separator: ", ").utf8)
|
||||
|
||||
do {
|
||||
var parser = StructuredFieldParser(joinedHeaders)
|
||||
@@ -211,7 +214,7 @@ final class StructuredHeadersTests: XCTestCase {
|
||||
|
||||
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 {
|
||||
for fixture in FixturesLoader.parsingFixtures {
|
||||
self._runTestOnFixture(fixture)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
import StructuredHeaders
|
||||
|
||||
final class StructuredFieldSerializerTests: 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 _runSerializationTest(_ fixture: StructuredHeaderTestFixture) {
|
||||
guard let expected = fixture.expected else {
|
||||
fatalError("No structure to serialize")
|
||||
}
|
||||
|
||||
do {
|
||||
let toSerialize: TestResult<ArraySlice<UInt8>>
|
||||
do {
|
||||
toSerialize = try TestResult<ArraySlice<UInt8>>(expected)
|
||||
} catch let error as StructuredHeaderError where error == .invalidIntegerOrDecimal {
|
||||
// We expect this error, it's fine
|
||||
return
|
||||
}
|
||||
|
||||
var serializer = StructuredFieldSerializer()
|
||||
|
||||
let result: [UInt8]
|
||||
switch toSerialize {
|
||||
case .dictionary(let dictionary):
|
||||
result = try serializer.writeDictionaryHeader(dictionary)
|
||||
case .list(let list):
|
||||
result = try serializer.writeListHeader(list)
|
||||
case .item(let item):
|
||||
result = try serializer.writeItemHeader(item)
|
||||
}
|
||||
|
||||
if fixture.mustFail == true || fixture.canFail == true {
|
||||
XCTFail("\(fixture.name): Fixture did not throw when serializing.")
|
||||
} else if let canonical = fixture.canonical {
|
||||
let expectedCanonicalForm = canonical.joined(separator: ", ")
|
||||
XCTAssertEqual(Array(expectedCanonicalForm.utf8), result,
|
||||
"\(fixture.name): Bad serialization, expected \(expectedCanonicalForm), got \(String(decoding: result, as: UTF8.self))")
|
||||
}
|
||||
} catch {
|
||||
XCTAssert(fixture.mustFail == true || fixture.canFail == true,
|
||||
"\(fixture.name): Unexpected failure, threw error \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func _runRoundTripTest(_ fixture: StructuredHeaderTestFixture) {
|
||||
guard let raw = fixture.raw else {
|
||||
fatalError("Cannot run round-trip test without raw header.")
|
||||
}
|
||||
|
||||
let joinedHeaders = Array(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
|
||||
}
|
||||
|
||||
|
||||
var serializer = StructuredFieldSerializer()
|
||||
let serialized: [UInt8]
|
||||
|
||||
let canonicalJoinedHeaders: [UInt8]
|
||||
if let canonical = fixture.canonical {
|
||||
canonicalJoinedHeaders = Array(canonical.joined(separator: ", ").utf8)
|
||||
} else {
|
||||
canonicalJoinedHeaders = joinedHeaders
|
||||
}
|
||||
|
||||
switch testResult {
|
||||
case .dictionary(let result):
|
||||
serialized = try serializer.writeDictionaryHeader(result)
|
||||
case .list(let list):
|
||||
serialized = try serializer.writeListHeader(list)
|
||||
case .item(let item):
|
||||
serialized = try serializer.writeItemHeader(item)
|
||||
}
|
||||
|
||||
XCTAssertEqual(canonicalJoinedHeaders, serialized, "\(fixture.name): Header serialization mismatch: expected \(String(decoding: canonicalJoinedHeaders, as: UTF8.self)), got \(String(decoding: serialized, as: UTF8.self))")
|
||||
} catch {
|
||||
XCTFail("\(fixture.name): Fixture threw unexpected error \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func testCanPassAllParsingFixtures() 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.parsingFixtures {
|
||||
if fixture.mustFail != true && fixture.canFail != true {
|
||||
self._runRoundTripTest(fixture)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCanPassAllSerializationFixtures() 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.serializingFixtures {
|
||||
self._runSerializationTest(fixture)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StructuredFieldSerializerTests.TestResult where BaseData == ArraySlice<UInt8> {
|
||||
init(_ schema: JSONSchema) throws {
|
||||
switch schema {
|
||||
case .dictionary(let dictionary):
|
||||
// Top level JSON objects are encoding dictionaries.
|
||||
var dict = OrderedMap<BaseData, ItemOrInnerList<BaseData>>()
|
||||
|
||||
for (name, value) in dictionary {
|
||||
dict[ArraySlice(name.utf8)] = try ItemOrInnerList(value)
|
||||
}
|
||||
|
||||
self = .dictionary(dict)
|
||||
|
||||
case .array(let jsonArray):
|
||||
// Top level JSON arrays may be either list headers or item headers. To know, we have
|
||||
// to investigate a bit. An item will have only two entries, and neither will be an array.
|
||||
if jsonArray.count == 2, let first = jsonArray.first, let last = jsonArray.last, !first.isArray && !last.isArray {
|
||||
// This is an item!
|
||||
self = .item(try Item(schema))
|
||||
} else {
|
||||
self = .list(try jsonArray.map { try ItemOrInnerList($0) })
|
||||
}
|
||||
case .bool, .double, .integer, .string:
|
||||
fatalError("Invalid top-level JSON object \(schema)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ItemOrInnerList where BaseData == ArraySlice<UInt8> {
|
||||
init(_ schema: JSONSchema) throws {
|
||||
// We need to detect the difference between an item or inner list. Both will be JSON arrays, but
|
||||
// in the case of inner list the first element will be an array, while for an item it will not.
|
||||
guard case .array(let arrayElements) = schema, arrayElements.count == 2, let first = arrayElements.first else {
|
||||
fatalError("Invalid item or inner list: \(schema)")
|
||||
}
|
||||
|
||||
if case .array = first {
|
||||
self = .innerList(try InnerList(schema))
|
||||
} else {
|
||||
self = .item(try Item(schema))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Item where BaseData == ArraySlice<UInt8> {
|
||||
init(_ schema: JSONSchema) throws {
|
||||
guard case .array(let arrayElements) = schema, arrayElements.count == 2, let first = arrayElements.first, let last = arrayElements.last else {
|
||||
fatalError("Invalid item: \(schema)")
|
||||
}
|
||||
|
||||
self.init(bareItem: try BareItem(first), parameters: try OrderedMap(parameters: last))
|
||||
}
|
||||
}
|
||||
|
||||
extension BareItem where BaseData == ArraySlice<UInt8> {
|
||||
init(_ schema: JSONSchema) throws {
|
||||
switch schema {
|
||||
case .integer(let int):
|
||||
self = .integer(int)
|
||||
case .double(let double):
|
||||
self = try .decimal(.init(double))
|
||||
case .string(let string):
|
||||
self = .string(string)
|
||||
case .dictionary(let typeObject):
|
||||
switch (typeObject["__type"], typeObject["value"]) {
|
||||
case (.some(.string("token")), .some(.string(let value))):
|
||||
self = .token(ArraySlice(value.utf8))
|
||||
|
||||
case (.some(.string("binary")), .some(.string(let value))):
|
||||
let expectedBase64Bytes = Data(base32Encoded: Data(value.utf8)).base64EncodedData()
|
||||
self = .undecodedByteSequence(ArraySlice(expectedBase64Bytes))
|
||||
|
||||
default:
|
||||
preconditionFailure("Unexpected type object \(typeObject)")
|
||||
}
|
||||
case .bool(let bool):
|
||||
self = .bool(bool)
|
||||
case .array:
|
||||
preconditionFailure("Base item cannot be JSON array")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension InnerList where BaseData == ArraySlice<UInt8> {
|
||||
init(_ schema: JSONSchema) throws {
|
||||
guard case .array(let arrayElements) = schema, arrayElements.count == 2, let first = arrayElements.first, let last = arrayElements.last else {
|
||||
fatalError("Invalid item: \(schema)")
|
||||
}
|
||||
|
||||
self.init(bareInnerList: try BareInnerList(first), parameters: try OrderedMap(parameters: last))
|
||||
}
|
||||
}
|
||||
|
||||
extension BareInnerList where BaseData == ArraySlice<UInt8> {
|
||||
init(_ schema: JSONSchema) throws {
|
||||
guard case .array(let items) = schema else {
|
||||
fatalError("Unexpected bare inner list object \(schema)")
|
||||
}
|
||||
|
||||
self.init()
|
||||
|
||||
for element in items {
|
||||
self.append(try Item(element))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension OrderedMap where Key == ArraySlice<UInt8>, Value == BareItem<ArraySlice<UInt8>> {
|
||||
init(parameters: JSONSchema) throws {
|
||||
guard case .dictionary(let jsonDict) = parameters else {
|
||||
fatalError("Invalid format for parameters: \(parameters)")
|
||||
}
|
||||
|
||||
self.init()
|
||||
|
||||
for (name, value) in jsonDict {
|
||||
self[ArraySlice(name.utf8)] = try BareItem(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
[
|
||||
{
|
||||
"name": "too big postive integer - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [1000000000000000, {}],
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "too big negative integer - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [-1000000000000000, {}],
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "too big postive decimal - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [1000000000000.1, {}],
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "too big negative decimal - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [-1000000000000.1, {}],
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "round positive odd decimal - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [0.0015, {}],
|
||||
"canonical": ["0.002"]
|
||||
},
|
||||
{
|
||||
"name": "round positive even decimal - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [0.0025, {}],
|
||||
"canonical": ["0.002"]
|
||||
},
|
||||
{
|
||||
"name": "round negative odd decimal - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [-0.0015, {}],
|
||||
"canonical": ["-0.002"]
|
||||
},
|
||||
{
|
||||
"name": "round negative even decimal - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [-0.0025, {}],
|
||||
"canonical": ["-0.002"]
|
||||
},
|
||||
{
|
||||
"name": "decimal round up to integer part - serialize",
|
||||
"header_type": "item",
|
||||
"expected": [9.9995, {}],
|
||||
"canonical": ["10.0"]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
[
|
||||
{
|
||||
"name": "0x00 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0000",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x01 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0001",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x02 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0002",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x03 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0003",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x04 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0004",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x05 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0005",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x06 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0006",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x07 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0007",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x08 in string - serialise only",
|
||||
"expected": [
|
||||
"\b",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x09 in string - serialise only",
|
||||
"expected": [
|
||||
"\t",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x0a in string - serialise only",
|
||||
"expected": [
|
||||
"\n",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x0b in string - serialise only",
|
||||
"expected": [
|
||||
"\u000b",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x0c in string - serialise only",
|
||||
"expected": [
|
||||
"\f",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x0d in string - serialise only",
|
||||
"expected": [
|
||||
"\r",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x0e in string - serialise only",
|
||||
"expected": [
|
||||
"\u000e",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x0f in string - serialise only",
|
||||
"expected": [
|
||||
"\u000f",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x10 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0010",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x11 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0011",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x12 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0012",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x13 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0013",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x14 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0014",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x15 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0015",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x16 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0016",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x17 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0017",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x18 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0018",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x19 in string - serialise only",
|
||||
"expected": [
|
||||
"\u0019",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x1a in string - serialise only",
|
||||
"expected": [
|
||||
"\u001a",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x1b in string - serialise only",
|
||||
"expected": [
|
||||
"\u001b",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x1c in string - serialise only",
|
||||
"expected": [
|
||||
"\u001c",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x1d in string - serialise only",
|
||||
"expected": [
|
||||
"\u001d",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x1e in string - serialise only",
|
||||
"expected": [
|
||||
"\u001e",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x1f in string - serialise only",
|
||||
"expected": [
|
||||
"\u001f",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
},
|
||||
{
|
||||
"name": "0x7f in string - serialise only",
|
||||
"expected": [
|
||||
"\u007f",
|
||||
{}
|
||||
],
|
||||
"header_type": "item",
|
||||
"must_fail": true
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user