-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathCodableCBORDecoder.swift
More file actions
239 lines (201 loc) · 8.43 KB
/
Copy pathCodableCBORDecoder.swift
File metadata and controls
239 lines (201 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import Foundation
final public class CodableCBORDecoder {
public var useStringKeys: Bool = false
public var dateStrategy: DateStrategy = .taggedAsEpochTimestamp
public var maximumDepth: Int = .max
struct _Options {
let useStringKeys: Bool
let dateStrategy: DateStrategy
let maximumDepth: Int
init(
useStringKeys: Bool = false,
dateStrategy: DateStrategy = .taggedAsEpochTimestamp,
maximumDepth: Int = .max
) {
self.useStringKeys = useStringKeys
self.dateStrategy = dateStrategy
self.maximumDepth = maximumDepth
}
func toCBOROptions() -> CBOROptions {
return CBOROptions(
useStringKeys: self.useStringKeys,
dateStrategy: self.dateStrategy,
maximumDepth: self.maximumDepth
)
}
}
var options: _Options {
return _Options(useStringKeys: self.useStringKeys, dateStrategy: self.dateStrategy, maximumDepth: self.maximumDepth)
}
public init() {}
public var userInfo: [CodingUserInfoKey : Any] = [:]
public func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
return try decode(type, from: ArraySlice([UInt8](data)))
}
public func decode<T: Decodable>(_ type: T.Type, from data: ArraySlice<UInt8>) throws -> T {
let decoder = _CBORDecoder(data: data, options: self.options)
decoder.userInfo = self.userInfo
if type == Date.self {
guard let cbor = try? CBORDecoder(input: [UInt8](data), options: self.options.toCBOROptions()).decodeItem(),
case .date(let date) = cbor
else {
let context = DecodingError.Context(codingPath: [], debugDescription: "Unable to decode data for Date")
throw DecodingError.dataCorrupted(context)
}
return date as! T
} else if type == Data.self {
guard let cbor = try? CBORDecoder(input: [UInt8](data), options: self.options.toCBOROptions()).decodeItem(),
case .byteString(let data) = cbor
else {
let context = DecodingError.Context(codingPath: [], debugDescription: "Unable to decode data for Data")
throw DecodingError.dataCorrupted(context)
}
return Data(data) as! T
}
return try T(from: decoder)
}
func setOptions(_ newOptions: _Options) {
self.useStringKeys = newOptions.useStringKeys
self.dateStrategy = newOptions.dateStrategy
self.maximumDepth = newOptions.maximumDepth
}
}
final class _CBORDecoder {
var codingPath: [CodingKey] = []
var userInfo: [CodingUserInfoKey : Any] = [:]
var container: CBORDecodingContainer?
fileprivate var data: ArraySlice<UInt8>
let options: CodableCBORDecoder._Options
var currentDepth: Int
init(data: ArraySlice<UInt8>, options: CodableCBORDecoder._Options, currentDepth: Int = 0) {
self.data = data
self.options = options
self.currentDepth = currentDepth
}
}
extension _CBORDecoder: Decoder {
func container<Key: CodingKey>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard self.currentDepth < self.options.maximumDepth else {
let context = DecodingError.Context(
codingPath: self.codingPath,
debugDescription: "Maximum decoding depth of \(self.options.maximumDepth) exceeded"
)
throw DecodingError.dataCorrupted(context)
}
try ensureMap(self.data.first, keyType: Key.self)
let container = KeyedContainer<Key>(data: self.data, codingPath: self.codingPath, userInfo: self.userInfo, options: self.options, currentDepth: self.currentDepth)
self.container = container
return KeyedDecodingContainer(container)
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard self.currentDepth < self.options.maximumDepth else {
let context = DecodingError.Context(
codingPath: self.codingPath,
debugDescription: "Maximum decoding depth of \(self.options.maximumDepth) exceeded"
)
throw DecodingError.dataCorrupted(context)
}
try ensureArray(self.data.first)
let container = UnkeyedContainer(data: self.data, codingPath: self.codingPath, userInfo: self.userInfo, options: self.options, currentDepth: self.currentDepth)
self.container = container
return container
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
let container = SingleValueContainer(data: self.data, codingPath: self.codingPath, userInfo: self.userInfo, options: self.options, currentDepth: self.currentDepth)
self.container = container
return container
}
func ensureMap<Key: CodingKey>(_ initialByte: UInt8?, keyType: Key.Type) throws {
switch initialByte {
case .some(0xa0...0xbf):
// all good, continue
return
case nil:
let context = DecodingError.Context(
codingPath: self.codingPath,
debugDescription: "Unexpected end of data"
)
throw DecodingError.dataCorrupted(context)
default:
let typeDescriptionOfByte = typeDescriptionFromByte(initialByte!) ?? "unknown"
let context = DecodingError.Context(
codingPath: self.codingPath,
debugDescription: "Expected map but found \(typeDescriptionOfByte)"
)
throw DecodingError.typeMismatch(keyType, context)
}
}
func ensureArray(_ initialByte: UInt8?) throws {
switch initialByte {
case .some(0x80...0x9f):
// all good, continue
return
case nil:
let context = DecodingError.Context(
codingPath: self.codingPath,
debugDescription: "Unexpected end of data"
)
throw DecodingError.dataCorrupted(context)
default:
let typeDescriptionOfByte = typeDescriptionFromByte(initialByte!) ?? "unknown"
let context = DecodingError.Context(
codingPath: self.codingPath,
debugDescription: "Expected array but found \(typeDescriptionOfByte)"
)
throw DecodingError.typeMismatch(Array<Any?>.self, context)
}
}
}
protocol CBORDecodingContainer: AnyObject {
var codingPath: [CodingKey] { get set }
var userInfo: [CodingUserInfoKey : Any] { get }
var data: ArraySlice<UInt8> { get set }
var index: Data.Index { get set }
}
extension CBORDecodingContainer {
func readByte() throws -> UInt8 {
return try read(1).first!
}
func read(_ length: Int) throws -> Data {
let nextIndex = self.index.advanced(by: length)
guard nextIndex <= self.data.endIndex else {
let context = DecodingError.Context(codingPath: self.codingPath, debugDescription: "Unexpected end of data")
throw DecodingError.dataCorrupted(context)
}
defer { self.index = nextIndex }
return Data(Array(self.data[self.index..<(nextIndex)]))
}
func peekByte() throws -> UInt8 {
return try peek(1).first!
}
func peek(_ length: Int) throws -> ArraySlice<UInt8> {
let nextIndex = self.index.advanced(by: length)
guard nextIndex <= self.data.endIndex else {
let context = DecodingError.Context(codingPath: self.codingPath, debugDescription: "Unexpected end of data")
throw DecodingError.dataCorrupted(context)
}
return self.data[self.index..<(nextIndex)]
}
func read<T: FixedWidthInteger>(_ type: T.Type) throws -> T {
let stride = MemoryLayout<T>.stride
let bytes = [UInt8](try read(stride))
return T(bytes: bytes)
}
}
func typeDescriptionFromByte(_ byte: UInt8) -> String? {
switch byte {
case 0x00...0x1b, 0x20...0x3b: return "integer"
case 0x40...0x5b, 0x5f: return "byte string"
case 0x60...0x7b, 0x7f: return "string"
case 0x80...0x9f: return "array"
case 0xa0...0xbf: return "map"
case 0xc0: return "text-based date/time"
case 0xc1: return "epoch-based date/time"
case 0xc2...0xdb: return "unspecified tagged value"
case 0xf4, 0xf5: return "boolean"
case 0xf6: return "null"
case 0xf8...0xfb: return "float"
default:
return nil
}
}