Apply formatting

This commit is contained in:
Cory Benfield committed 2020-07-17 10:06:44 +01:00
1 parent 89ef2cf73d
commit 3f73125a0d
28 files changed
+198 -184

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# file options
--swiftversion 5.2
--exclude .build
# format options
--self insert
--patternlet inline
--stripunusedargs unnamed-only
--ifdef no-indent
# rules
+12 -6
View File
@@ -19,23 +19,29 @@ let package = Package(
products: [
.library(
name: "StructuredHeaders",
targets: ["StructuredHeaders"]),
targets: ["StructuredHeaders"]
),
.library(
name: "CodableStructuredHeaders",
targets: ["CodableStructuredHeaders"]),
targets: ["CodableStructuredHeaders"]
),
],
targets: [
.target(
name: "StructuredHeaders",
dependencies: []),
dependencies: []
),
.target(
name: "CodableStructuredHeaders",
dependencies: ["StructuredHeaders"]),
dependencies: ["StructuredHeaders"]
),
.target(
name: "sh-parser",
dependencies: ["StructuredHeaders"]),
dependencies: ["StructuredHeaders"]
),
.testTarget(
name: "StructuredHeadersTests",
dependencies: ["StructuredHeaders", "CodableStructuredHeaders"]),
dependencies: ["StructuredHeaders", "CodableStructuredHeaders"]
),
]
)
@@ -30,27 +30,27 @@ struct BareInnerListDecoder<BaseData: RandomAccessCollection> where BaseData.Ele
extension BareInnerListDecoder: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
return self.decoder.codingPath
self.decoder.codingPath
}
var count: Int? {
return self.list.count
self.list.count
}
var isAtEnd: Bool {
return self.currentOffset == self.list.count
self.currentOffset == self.list.count
}
var currentIndex: Int {
return self.currentOffset
self.currentOffset
}
mutating func decodeNil() throws -> Bool {
// We never decode nil.
return false
false
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
// This is a request to decode a scalar. We decode the next entry and increment the index.
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
@@ -77,7 +77,7 @@ extension BareInnerListDecoder: UnkeyedDecodingContainer {
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
// This is a request to decode a full item. We decode the next entry and increment the index.
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
@@ -116,5 +116,4 @@ extension BareInnerListDecoder: UnkeyedDecodingContainer {
// No inheritance here folks
throw StructuredHeaderError.invalidTypeForItem
}
}
@@ -27,59 +27,59 @@ struct BareItemDecoder<BaseData: RandomAccessCollection> where BaseData.Element
extension BareItemDecoder: SingleValueDecodingContainer {
var codingPath: [CodingKey] {
return self._codingPath as [CodingKey]
self._codingPath as [CodingKey]
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int8.Type) throws -> Int8 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int16.Type) throws -> Int16 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int32.Type) throws -> Int32 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int64.Type) throws -> Int64 {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: UInt.Type) throws -> UInt {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Int.Type) throws -> Int {
return try self._decodeFixedWidthInteger(type)
try self._decodeFixedWidthInteger(type)
}
func decode(_ type: Float.Type) throws -> Float {
return try self._decodeBinaryFloatingPoint(type)
try self._decodeBinaryFloatingPoint(type)
}
func decode(_ type: Double.Type) throws -> Double {
return try self._decodeBinaryFloatingPoint(type)
try self._decodeBinaryFloatingPoint(type)
}
func decode(_ type: String.Type) throws -> String {
switch item {
func decode(_: String.Type) throws -> String {
switch self.item {
case .string(let string):
return string
case .token(let token):
@@ -89,7 +89,7 @@ extension BareItemDecoder: SingleValueDecodingContainer {
}
}
func decode(_ type: Bool.Type) throws -> Bool {
func decode(_: Bool.Type) throws -> Bool {
guard case .bool(let bool) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
@@ -97,7 +97,7 @@ extension BareItemDecoder: SingleValueDecodingContainer {
return bool
}
func decode(_ type: Data.Type) throws -> Data {
func decode(_: Data.Type) throws -> Data {
guard case .undecodedByteSequence(let data) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
@@ -109,7 +109,7 @@ extension BareItemDecoder: SingleValueDecodingContainer {
return decoded
}
func decode(_ type: Decimal.Type) throws -> Decimal {
func decode(_: Decimal.Type) throws -> Decimal {
guard case .decimal(let pseudoDecimal) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
@@ -121,7 +121,7 @@ extension BareItemDecoder: SingleValueDecodingContainer {
func decodeNil() -> Bool {
// Items are never nil.
return false
false
}
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
@@ -163,7 +163,7 @@ extension BareItemDecoder: SingleValueDecodingContainer {
}
}
private func _decodeBinaryFloatingPoint<T: BinaryFloatingPoint>(_ type: T.Type) throws -> T {
private func _decodeBinaryFloatingPoint<T: BinaryFloatingPoint>(_: T.Type) throws -> T {
guard case .decimal(let decimal) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
@@ -172,7 +172,7 @@ extension BareItemDecoder: SingleValueDecodingContainer {
return T(Double(decimal))
}
private func _decodeFixedWidthInteger<T: FixedWidthInteger>(_ type: T.Type) throws -> T {
private func _decodeFixedWidthInteger<T: FixedWidthInteger>(_: T.Type) throws -> T {
guard case .integer(let int) = self.item else {
throw StructuredHeaderError.invalidTypeForItem
}
@@ -27,23 +27,23 @@ struct DictionaryKeyedContainer<Key: CodingKey, BaseData: RandomAccessCollection
extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
return self.decoder.codingPath
self.decoder.codingPath
}
var allKeys: [Key] {
return self.dictionary.compactMap { Key(stringValue: $0.0) }
self.dictionary.compactMap { Key(stringValue: $0.0) }
}
func contains(_ key: Key) -> Bool {
return self.dictionary.contains(where: { $0.0 == key.stringValue })
self.dictionary.contains(where: { $0.0 == key.stringValue })
}
func decodeNil(forKey key: Key) throws -> Bool {
// We will decode nil if the key is not present.
return !self.contains(key)
!self.contains(key)
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
@@ -32,20 +32,20 @@ struct KeyedInnerListDecoder<Key: CodingKey, BaseData: RandomAccessCollection> w
extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
return self.decoder.codingPath
self.decoder.codingPath
}
var allKeys: [Key] {
return keyedInnerListDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
keyedInnerListDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
return keyedInnerListDecoderSupportedKeys.contains(key.stringValue)
keyedInnerListDecoderSupportedKeys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
// Keys are never nil for this type.
return false
false
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
@@ -32,20 +32,20 @@ struct KeyedItemDecoder<Key: CodingKey, BaseData: RandomAccessCollection> where
extension KeyedItemDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
return self.decoder.codingPath
self.decoder.codingPath
}
var allKeys: [Key] {
return keyedItemDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
keyedItemDecoderSupportedKeys.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
return keyedItemDecoderSupportedKeys.contains(key.stringValue)
keyedItemDecoderSupportedKeys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
// Keys are never nil for this type.
return false
false
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
@@ -27,23 +27,23 @@ struct ParametersDecoder<Key: CodingKey, BaseData: RandomAccessCollection> where
extension ParametersDecoder: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
return self.decoder.codingPath
self.decoder.codingPath
}
var allKeys: [Key] {
return self.parameters.compactMap { Key(stringValue: $0.0) }
self.parameters.compactMap { Key(stringValue: $0.0) }
}
func contains(_ key: Key) -> Bool {
return self.parameters.contains(where: { $0.0 == key.stringValue })
self.parameters.contains(where: { $0.0 == key.stringValue })
}
func decodeNil(forKey key: Key) throws -> Bool {
// We will decode nil if the key is not present.
return !self.contains(key)
!self.contains(key)
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
@@ -20,7 +20,7 @@ public struct StructuredFieldDecoder {
/// A strategy that should be used to map coding keys to wire format keys.
public var keyDecodingStrategy: KeyDecodingStrategy?
public init() { }
public init() {}
}
extension StructuredFieldDecoder {
@@ -129,10 +129,10 @@ class _StructuredFieldDecoder<BaseData: RandomAccessCollection> where BaseData.E
extension _StructuredFieldDecoder: Decoder {
var codingPath: [CodingKey] {
return self._codingStack.map { $0.key as CodingKey }
self._codingStack.map { $0.key as CodingKey }
}
var userInfo: [CodingUserInfoKey : Any] {
var userInfo: [CodingUserInfoKey: Any] {
[:]
}
@@ -147,7 +147,7 @@ extension _StructuredFieldDecoder: Decoder {
self._codingStack.removeLast()
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
if self.currentElement == nil {
// First parse. This may be a dictionary, but depending on the keys this may also be list or item.
// We can't really detect this (Key isn't caseiterable) so we just kinda have to hope. Users can tell
@@ -321,6 +321,6 @@ extension _StructuredFieldDecoder {
/// The element at the current head of the coding stack.
private var currentElement: Element? {
return self._codingStack.last.map { $0.element }
self._codingStack.last.map { $0.element }
}
}
@@ -13,7 +13,7 @@
//===----------------------------------------------------------------------===//
import StructuredHeaders
struct _StructuredHeaderCodingKey : CodingKey {
struct _StructuredHeaderCodingKey: CodingKey {
var stringValue: String
var intValue: Int?
@@ -30,27 +30,27 @@ struct TopLevelListDecoder<BaseData: RandomAccessCollection> where BaseData.Elem
extension TopLevelListDecoder: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
return self.decoder.codingPath
self.decoder.codingPath
}
var count: Int? {
return self.list.count
self.list.count
}
var isAtEnd: Bool {
return self.currentOffset == self.list.count
self.currentOffset == self.list.count
}
var currentIndex: Int {
return self.currentOffset
self.currentOffset
}
mutating func decodeNil() throws -> Bool {
// We never decode nil.
return false
false
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
// This is a request to decode a scalar. We decode the next entry and increment the index.
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
@@ -77,7 +77,7 @@ extension TopLevelListDecoder: UnkeyedDecodingContainer {
}
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
// This is a request to decode a full item. We decode the next entry and increment the index.
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
@@ -116,5 +116,4 @@ extension TopLevelListDecoder: UnkeyedDecodingContainer {
// No inheritance here folks
throw StructuredHeaderError.invalidTypeForItem
}
}
@@ -19,7 +19,7 @@ import StructuredHeaders
public struct StructuredFieldEncoder {
public var keyEncodingStrategy: KeyEncodingStrategy?
public init() { }
public init() {}
}
extension StructuredFieldEncoder {
@@ -90,7 +90,7 @@ class _StructuredFieldEncoder {
self.serializer = serializer
self._codingPath = []
self.keyEncodingStrategy = keyEncodingStrategy
self.currentStackEntry = CodingStackEntry(key: .init(stringValue: ""), storage: .itemHeader) // This default doesn't matter right now.
self.currentStackEntry = CodingStackEntry(key: .init(stringValue: ""), storage: .itemHeader) // This default doesn't matter right now.
}
fileprivate func encodeDictionaryField<StructuredField: Encodable>(_ data: StructuredField) throws -> [UInt8] {
@@ -157,10 +157,10 @@ class _StructuredFieldEncoder {
extension _StructuredFieldEncoder: Encoder {
var codingPath: [CodingKey] {
return self._codingPath.map { $0.key as CodingKey }
self._codingPath.map { $0.key as CodingKey }
}
var userInfo: [CodingUserInfoKey : Any] {
var userInfo: [CodingUserInfoKey: Any] {
[:]
}
@@ -184,11 +184,11 @@ extension _StructuredFieldEncoder: Encoder {
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
return StructuredFieldUnkeyedEncodingContainer(encoder: self)
StructuredFieldUnkeyedEncodingContainer(encoder: self)
}
func singleValueContainer() -> SingleValueEncodingContainer {
return self
self
}
}
@@ -264,7 +264,7 @@ extension _StructuredFieldEncoder: SingleValueEncodingContainer {
}
func encode(_ data: Decimal) throws {
let significand = (data.significand as NSNumber).intValue // Yes, really.
let significand = (data.significand as NSNumber).intValue // Yes, really.
guard let exponent = Int8(exactly: data.exponent) else {
throw StructuredHeaderError.invalidIntegerOrDecimal
}
@@ -273,7 +273,7 @@ extension _StructuredFieldEncoder: SingleValueEncodingContainer {
try self.currentStackEntry.storage.insertBareItem(.decimal(pd))
}
func encode<T>(_ value: T) throws where T : Encodable {
func encode<T>(_ value: T) throws where T: Encodable {
switch value {
case let value as UInt8:
try self.encode(value)
@@ -421,7 +421,7 @@ extension _StructuredFieldEncoder {
}
func append(_ value: Decimal) throws {
let significand = (value.significand as NSNumber).intValue // Yes, really.
let significand = (value.significand as NSNumber).intValue // Yes, really.
guard let exponent = Int8(exactly: value.exponent) else {
throw StructuredHeaderError.invalidIntegerOrDecimal
}
@@ -430,7 +430,7 @@ extension _StructuredFieldEncoder {
try self.currentStackEntry.storage.appendBareItem(.decimal(pd))
}
func append<T>(_ value: T) throws where T : Encodable {
func append<T>(_ value: T) throws where T: Encodable {
switch value {
case let value as UInt8:
try self.append(value)
@@ -588,7 +588,7 @@ extension _StructuredFieldEncoder {
}
func encode(_ value: Decimal, forKey key: String) throws {
let significand = (value.significand as NSNumber).intValue // Yes, really.
let significand = (value.significand as NSNumber).intValue // Yes, really.
guard let exponent = Int8(exactly: value.exponent) else {
throw StructuredHeaderError.invalidIntegerOrDecimal
}
@@ -686,7 +686,6 @@ extension _StructuredFieldEncoder {
throw StructuredHeaderError.invalidTypeForItem
}
case .listHeader, .list, .itemHeader, .bareInnerList,
.parameters:
throw StructuredHeaderError.invalidTypeForItem
@@ -896,7 +895,6 @@ extension _StructuredFieldEncoder {
}
}
extension Item where BaseData == _StructuredFieldEncoder.NodeType.DataType {
fileprivate init(_ partialItem: _StructuredFieldEncoder.NodeType.PartialItem) {
self.init(bareItem: partialItem.bareItem!, parameters: partialItem.parameters)
@@ -26,12 +26,11 @@ struct StructuredFieldKeyedEncodingContainer<Key: CodingKey> {
extension StructuredFieldKeyedEncodingContainer: KeyedEncodingContainerProtocol {
var codingPath: [CodingKey] {
return self.encoder.codingPath
self.encoder.codingPath
}
mutating func encodeNil(forKey key: Key) throws {
// Nil has no representation in structured headers
return
}
mutating func encode(_ value: Bool, forKey key: Key) throws {
@@ -90,25 +89,23 @@ extension StructuredFieldKeyedEncodingContainer: KeyedEncodingContainerProtocol
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
mutating func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
try self.encoder.encode(value, forKey: key.stringValue)
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
return self.encoder.container(keyedBy: keyType)
}
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
return self.encoder.unkeyedContainer()
self.encoder.unkeyedContainer()
}
mutating func superEncoder() -> Encoder {
return self.encoder
self.encoder
}
mutating func superEncoder(forKey key: Key) -> Encoder {
return self.encoder
self.encoder
}
}
@@ -26,11 +26,11 @@ struct StructuredFieldUnkeyedEncodingContainer {
extension StructuredFieldUnkeyedEncodingContainer: UnkeyedEncodingContainer {
var codingPath: [CodingKey] {
return self.encoder.codingPath
self.encoder.codingPath
}
var count: Int {
return self.encoder.count
self.encoder.count
}
func encodeNil() throws {
@@ -93,21 +93,19 @@ extension StructuredFieldUnkeyedEncodingContainer: UnkeyedEncodingContainer {
try self.encoder.append(value)
}
func encode<T>(_ value: T) throws where T : Encodable {
func encode<T>(_ value: T) throws where T: Encodable {
try self.encoder.append(value)
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
return self.encoder.container(keyedBy: keyType)
}
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
return self.encoder.unkeyedContainer()
self.encoder.unkeyedContainer()
}
mutating func superEncoder() -> Encoder {
return self.encoder
self.encoder
}
}
+3 -3
View File
@@ -21,7 +21,7 @@ let asciiUnderscore = UInt8(ascii: "_")
let asciiZero = UInt8(ascii: "0")
let asciiOne = UInt8(ascii: "1")
let asciiNine = UInt8(ascii: "9")
let asciiDigits = asciiZero...asciiNine
let asciiDigits = asciiZero ... asciiNine
let asciiDquote = UInt8(ascii: "\"")
let asciiColon = UInt8(ascii: ":")
let asciiSemicolon = UInt8(ascii: ";")
@@ -47,5 +47,5 @@ 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
let asciiCapitals = asciiCapitalA ... asciiCapitalZ
let asciiLowercases = asciiLowerA ... asciiLowerZ
+23 -18
View File
@@ -17,7 +17,8 @@
// These types are used by the parser, the serializer, and by users of the direct encoding/decoding APIs.
// They are not used by those using the Codable interface.
// MARK:- ItemOrInnerList
// MARK: - ItemOrInnerList
/// `ItemOrInnerList` represents the values in a structured header dictionary, or the
/// entries in a structured header list.
public enum ItemOrInnerList<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
@@ -25,9 +26,10 @@ public enum ItemOrInnerList<BaseData: RandomAccessCollection> where BaseData.Ele
case innerList(InnerList<BaseData>)
}
extension ItemOrInnerList: Hashable { }
extension ItemOrInnerList: Hashable {}
// MARK: - BareItem
// MARK:- BareItem
/// `BareItem` is a representation of the base data types at the bottom of a structured
/// header field. These types are not parameterised: they are raw data.
public enum BareItem<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
@@ -79,9 +81,10 @@ extension BareItem: ExpressibleByStringLiteral {
}
}
extension BareItem: Hashable { }
extension BareItem: Hashable {}
// MARK: - Item
// MARK:- Item
/// `Item` represents a structured header field item: a combination of a `bareItem`
/// and some parameters.
public struct Item<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
@@ -97,9 +100,10 @@ public struct Item<BaseData: RandomAccessCollection> where BaseData.Element == U
}
}
extension Item: Hashable { }
extension Item: Hashable {}
// MARK: - BareInnerList
// MARK:- BareInnerList
/// A `BareInnerList` represents the items contained within an `InnerList`, without
/// the associated parameters.
public struct BareInnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
@@ -131,32 +135,32 @@ extension BareInnerList: RandomAccessCollection, MutableCollection {
}
public var count: Int {
return self.items.count
self.items.count
}
public var startIndex: Index {
return Index(self.items.startIndex)
Index(self.items.startIndex)
}
public var endIndex: Index {
return Index(self.items.endIndex)
Index(self.items.endIndex)
}
public func index(after i: Index) -> Index {
return Index(self.items.index(after: i.baseIndex))
Index(self.items.index(after: i.baseIndex))
}
public func index(before i: Index) -> Index {
return Index(self.items.index(before: i.baseIndex))
Index(self.items.index(before: i.baseIndex))
}
public func index(_ i: Index, offsetBy offset: Int) -> Index {
return Index(self.items.index(i.baseIndex, offsetBy: offset))
Index(self.items.index(i.baseIndex, offsetBy: offset))
}
public subscript(index: Index) -> Item<BaseData> {
get {
return self.items[index.baseIndex]
self.items[index.baseIndex]
}
set {
self.items[index.baseIndex] = newValue
@@ -164,15 +168,16 @@ extension BareInnerList: RandomAccessCollection, MutableCollection {
}
}
extension BareInnerList.Index: Hashable { }
extension BareInnerList.Index: Hashable {}
extension BareInnerList.Index: Comparable {
public static func <(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex < rhs.baseIndex
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.baseIndex < rhs.baseIndex
}
}
// MARK:- InnerList
// MARK: - InnerList
/// An `InnerList` is a list of items, with some associated parameters.
public struct InnerList<BaseData: RandomAccessCollection>: Hashable where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
/// The items contained within this inner list.
+4 -3
View File
@@ -12,7 +12,8 @@
//
//===----------------------------------------------------------------------===//
// MARK:- StructuredHeaderError
// MARK: - StructuredHeaderError
/// Errors that may be encountered when working with structured headers.
public struct StructuredHeaderError: Error {
private enum _BaseError: Hashable {
@@ -58,10 +59,10 @@ extension StructuredHeaderError {
public static let indexOutOfRange = StructuredHeaderError(.indexOutOfRange)
}
extension StructuredHeaderError: Hashable { }
extension StructuredHeaderError: Hashable {}
extension StructuredHeaderError: CustomStringConvertible {
public var description: String {
return String(describing: self.base)
String(describing: self.base)
}
}
+11 -12
View File
@@ -346,7 +346,7 @@ extension StructuredFieldParser {
// Unquoted dquote, this is the end of the string.
endIndex = index
break loop
case 0x00...0x1f, 0x7f...:
case 0x00 ... 0x1F, 0x7F...:
// Forbidden bytes in string: string must be VCHAR and SP.
throw StructuredHeaderError.invalidString
default:
@@ -361,7 +361,7 @@ extension StructuredFieldParser {
if endIndex == self.underlyingData.endIndex {
throw StructuredHeaderError.invalidString
}
let stringSlice = self.underlyingData[self.underlyingData.startIndex..<index]
let stringSlice = self.underlyingData[self.underlyingData.startIndex ..< index]
self.underlyingData.formIndex(after: &index)
self.underlyingData = self.underlyingData[index...]
@@ -496,7 +496,7 @@ extension StructuredFieldParser {
}
}
fileprivate enum IntegerOrDecimal {
private enum IntegerOrDecimal {
case integer
case decimal
}
@@ -541,7 +541,7 @@ extension String {
/// 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 struct StrippingStringEscapesCollection<BaseCollection: RandomAccessCollection> where BaseCollection.Element == UInt8 {
private var base: BaseCollection
private var escapes: UInt
@@ -564,16 +564,16 @@ extension StrippingStringEscapesCollection: Collection {
// 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)
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))
Index(baseIndex: self.unescapedIndex(self.base.startIndex))
}
fileprivate var endIndex: Index {
return Index(baseIndex: self.base.endIndex)
Index(baseIndex: self.base.endIndex)
}
fileprivate func index(after i: Index) -> Index {
@@ -582,7 +582,7 @@ extension StrippingStringEscapesCollection: Collection {
}
fileprivate subscript(index: Index) -> UInt8 {
return self.base[index._baseIndex]
self.base[index._baseIndex]
}
private func unescapedIndex(_ baseIndex: BaseCollection.Index) -> BaseCollection.Index {
@@ -598,11 +598,10 @@ extension StrippingStringEscapesCollection: Collection {
}
}
extension StrippingStringEscapesCollection.Index: Equatable { }
extension StrippingStringEscapesCollection.Index: Equatable {}
extension StrippingStringEscapesCollection.Index: Comparable {
fileprivate static func <(lhs: Self, rhs: Self) -> Bool {
return lhs._baseIndex < rhs._baseIndex
fileprivate static func < (lhs: Self, rhs: Self) -> Bool {
lhs._baseIndex < rhs._baseIndex
}
}
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
fileprivate let validIntegerRange = Int64(-999999999999999)...Int64(999999999999999)
private let validIntegerRange = Int64(-999_999_999_999_999) ... Int64(999_999_999_999_999)
/// A `StructuredFieldSerializer` is the basic parsing object for structured header fields.
public struct StructuredFieldSerializer {
@@ -179,7 +179,7 @@ extension StructuredFieldSerializer {
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 {
guard bytes.allSatisfy({ !(0x00 ... 0x1F).contains($0) && $0 != 0x7F && $0 < 0x80 }) else {
throw StructuredHeaderError.invalidString
}
self.data.append(asciiDquote)
@@ -236,4 +236,3 @@ extension String {
}
}
}
+23 -19
View File
@@ -35,7 +35,7 @@ public struct OrderedMap<Key, Value> where Key: Hashable {
/// Warning! Unlike a regular dictionary, we do not promise this will be O(1)!
public subscript(key: Key) -> Value? {
get {
return self.backing.first(where: { $0.key == key }).map { $0.value }
self.backing.first(where: { $0.key == key }).map { $0.value }
}
set {
if let existing = self.backing.firstIndex(where: { $0.key == key }) {
@@ -51,7 +51,8 @@ public struct OrderedMap<Key, Value> where Key: Hashable {
}
}
// MARK:- Helper struct for storing elements
// MARK: - Helper struct for storing elements
extension OrderedMap {
// This struct takes some explaining.
//
@@ -66,7 +67,8 @@ extension OrderedMap {
}
}
// MARK:- Collection conformances
// MARK: - Collection conformances
extension OrderedMap: RandomAccessCollection, MutableCollection {
public struct Index {
fileprivate var baseIndex: Array<(Key, Value)>.Index
@@ -77,15 +79,15 @@ extension OrderedMap: RandomAccessCollection, MutableCollection {
}
public var startIndex: Index {
return Index(self.backing.startIndex)
Index(self.backing.startIndex)
}
public var endIndex: Index {
return Index(self.backing.endIndex)
Index(self.backing.endIndex)
}
public var count: Int {
return self.backing.count
self.backing.count
}
public subscript(position: Index) -> (Key, Value) {
@@ -99,37 +101,38 @@ extension OrderedMap: RandomAccessCollection, MutableCollection {
}
public func index(_ i: Index, offsetBy distance: Int) -> Index {
return Index(self.backing.index(i.baseIndex, offsetBy: distance))
Index(self.backing.index(i.baseIndex, offsetBy: distance))
}
public func index(after i: Index) -> Index {
return self.index(i, offsetBy: 1)
self.index(i, offsetBy: 1)
}
public func index(before i: Index) -> Index {
return self.index(i, offsetBy: -1)
self.index(i, offsetBy: -1)
}
}
extension OrderedMap.Index: Hashable { }
extension OrderedMap.Index: Hashable {}
extension OrderedMap.Index: Comparable {
public static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex < rhs.baseIndex
lhs.baseIndex < rhs.baseIndex
}
}
extension OrderedMap.Index: Strideable {
public func advanced(by n: Int) -> Self {
return Self(self.baseIndex.advanced(by: n))
Self(self.baseIndex.advanced(by: n))
}
public func distance(to other: Self) -> Int {
return self.baseIndex.distance(to: other.baseIndex)
self.baseIndex.distance(to: other.baseIndex)
}
}
// MARK:- Helper conformances
// MARK: - Helper conformances
extension OrderedMap: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (Key, Value)...) {
self.backing = elements.map { Entry(key: $0.0, value: $0.1) }
@@ -143,8 +146,9 @@ extension OrderedMap: CustomDebugStringConvertible {
}
}
// 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 { }
// 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 {}
@@ -41,7 +41,7 @@ public struct PseudoDecimal: Hashable {
public var mantissa: Int64 {
get {
return self._mantissa
self._mantissa
}
set {
Self.fatalValidate(mantissa: newValue, exponent: self._exponent)
@@ -51,7 +51,7 @@ public struct PseudoDecimal: Hashable {
public var exponent: Int8 {
get {
return self._exponent
self._exponent
}
set {
Self.fatalValidate(mantissa: self._mantissa, exponent: newValue)
@@ -182,7 +182,6 @@ extension PseudoDecimal: ExpressibleByFloatLiteral {
}
}
extension String {
public init(_ decimal: PseudoDecimal) {
var local = decimal
-1
View File
@@ -204,4 +204,3 @@ func main() {
}
main()
+3 -3
View File
@@ -13,7 +13,7 @@
//===----------------------------------------------------------------------===//
import Foundation
fileprivate let base32DecoderAlphabet: [UnicodeScalar: UInt64] = [
private 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,
@@ -25,7 +25,7 @@ extension Data {
self = Data()
for start in stride(from: data.startIndex, to: data.endIndex, by: 8) {
let bytes = data[start..<(start + 8)]
let bytes = data[start ..< (start + 8)]
precondition(bytes.count == 8)
var seenEquals = 0
@@ -60,7 +60,7 @@ extension Data {
fatalError("Impossible equals count: \(seenEquals)")
}
for byteNumber in (ignoredBytes..<5).reversed() {
for byteNumber in (ignoredBytes ..< 5).reversed() {
let byte = UInt8(truncatingIfNeeded: rawValue >> (byteNumber * 8))
self.append(byte)
}
+5 -5
View File
@@ -20,13 +20,13 @@ enum FixturesLoader {
}
private static var serializationFixturesDirectory: URL {
return fixturesDirectory.appendingPathComponent("serialisation-tests").absoluteURL
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 {
var files: [URL]?
for _ in 0 ..< 1000 {
do {
files = try FileManager.default.contentsOfDirectory(at: fixturesDirectory, includingPropertiesForKeys: nil, options: [])
break
@@ -51,8 +51,8 @@ enum FixturesLoader {
static var serializingFixtures: [StructuredHeaderTestFixture] {
// ContentsOfDirectory can throw if it hits EINTR, just spin
var files: [URL]? = nil
for _ in 0..<1000 {
var files: [URL]?
for _ in 0 ..< 1000 {
do {
files = try FileManager.default.contentsOfDirectory(at: serializationFixturesDirectory, includingPropertiesForKeys: nil, options: [])
break
@@ -1,3 +1,4 @@
import CodableStructuredHeaders
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
@@ -12,9 +13,8 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
import StructuredHeaders
import CodableStructuredHeaders
import XCTest
struct ListyDictionaryFieldParameters: Codable, Equatable {
var q: Double?
@@ -31,7 +31,6 @@ struct ListyDictionaryParameterisedList: Codable, Equatable {
var parameters: ListyDictionaryFieldParameters
}
/// An example ListyDictionary structured header field.
///
/// An example of this field is: 'primary=bar;q=1.0, secondary=baz;q=0.5;fallback=last, acceptablejurisdictions=(AU;q=1.0 GB;q=0.9 FR);fallback=primary'
@@ -86,7 +85,7 @@ final class StructuredFieldDecoderTests: XCTestCase {
// rather than crashing for all non-Int64 types. (Ignoring Int/UInt due to their platform
// dependence)
let headerField = "-999999999999999;bar=baz"
let expected = Int64(-999999999999999)
let expected = Int64(-999_999_999_999_999)
XCTAssertThrowsError(try StructuredFieldDecoder().decode(Int8.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(UInt8.self, from: Array(headerField.utf8)))
@@ -1,3 +1,4 @@
import CodableStructuredHeaders
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
@@ -12,9 +13,8 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
import StructuredHeaders
import CodableStructuredHeaders
import XCTest
final class StructuredFieldEncoderTests: XCTestCase {
func testSimpleItemHeaderEncodeBareItem() throws {
@@ -144,7 +144,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
let encoder = StructuredFieldEncoder()
let header = [Item(parameters: ["q": 0.8], item: "gzip"),
Item(parameters: ["q": 0.6], item: "deflate"),]
Item(parameters: ["q": 0.6], item: "deflate")]
XCTAssertEqual(Array("gzip;q=0.8, deflate;q=0.6".utf8),
try encoder.encodeListField(header))
@@ -200,7 +200,7 @@ final class StructuredFieldEncoderTests: XCTestCase {
],
[
Item(item: 3, parameters: ["odd": true]),
Item(item: 4, parameters: ["odd": false])
Item(item: 4, parameters: ["odd": false]),
],
]
XCTAssertEqual(Array("(1;odd 2;odd=?0), (3;odd 4;odd=?0)".utf8),
@@ -12,8 +12,8 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
import StructuredHeaders
import XCTest
enum FixtureTestError: Error {
case base64DecodingFailed
@@ -96,9 +96,9 @@ final class StructuredFieldParserTests: XCTestCase {
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 {
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
}
@@ -12,8 +12,8 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
import StructuredHeaders
import XCTest
final class StructuredFieldSerializerTests: XCTestCase {
enum TestResult<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence == BaseData, BaseData: Hashable {
@@ -65,7 +65,7 @@ final class StructuredFieldSerializerTests: XCTestCase {
guard let raw = fixture.raw else {
fatalError("Cannot run round-trip test without raw header.")
}
let joinedHeaders = Array(raw.joined(separator: ", ").utf8)
do {
@@ -84,7 +84,6 @@ final class StructuredFieldSerializerTests: XCTestCase {
return
}
var serializer = StructuredFieldSerializer()
let serialized: [UInt8]
@@ -113,7 +112,7 @@ final class StructuredFieldSerializerTests: XCTestCase {
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 {
if fixture.mustFail != true, fixture.canFail != true {
self._runRoundTripTest(fixture)
}
}
@@ -143,7 +142,7 @@ extension StructuredFieldSerializerTests.TestResult where BaseData == ArraySlice
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 {
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 {