mirror of
https://github.com/apple/swift-http-structured-headers
synced 2026-11-26 04:57:47 +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))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user