Skip to content
Navigation Menu
{{ message }}
forked from norio-nomura/ObjectEncoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecoder.swift
More file actions
466 lines (387 loc) · 17.9 KB
/
Copy pathDecoder.swift
File metadata and controls
466 lines (387 loc) · 17.9 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//
// Decoder.swift
// ObjectEncoder
//
// Created by Norio Nomura on 10/21/17.
// Copyright (c) 2017 ObjectEncoder. All rights reserved.
//
#if !_runtime(_ObjC)
import CoreFoundation
#endif
import Foundation
public struct ObjectDecoder {
public init() {}
public func decode<T>(_ type: T.Type = T.self,
from object: Any,
userInfo: [CodingUserInfoKey: Any] = [:]) throws -> T where T: Decodable {
do {
return try ObjectDecoder.Decoder(object, options, userInfo).singleValueContainer().decode(type)
} catch let error as DecodingError {
throw error
} catch {
throw _dataCorrupted(at: [], "The given data was not valid Object.", error)
}
}
public struct DecodingStrategy<T: Decodable> {
public typealias Closure = (Decoder) throws -> T
public init(closure: @escaping Closure) { self.closure = closure }
fileprivate let closure: Closure
}
public struct DecodingStrategies {
var strategies = [ObjectIdentifier: Any]()
public subscript<T>(type: T.Type) -> DecodingStrategy<T>? {
get { return strategies[ObjectIdentifier(type)] as? DecodingStrategy<T> }
set { strategies[ObjectIdentifier(type)] = newValue }
}
}
/// The strategis to use for decoding values.
public var decodingStrategies: DecodingStrategies {
get { return options.decodingStrategies }
set { options.decodingStrategies = newValue }
}
// MARK: -
fileprivate struct Options {
fileprivate var decodingStrategies = DecodingStrategies()
}
fileprivate var options = Options()
}
extension ObjectDecoder {
public struct Decoder: Swift.Decoder {
public let object: Any
fileprivate typealias Options = ObjectDecoder.Options
private let options: Options
fileprivate init(_ object: Any,
_ options: Options,
_ userInfo: [CodingUserInfoKey: Any],
_ codingPath: [CodingKey] = []) {
self.object = object
self.options = options
self.userInfo = userInfo
self.codingPath = codingPath
}
// MARK: - Swift.Decoder properties
public let codingPath: [CodingKey]
public let userInfo: [CodingUserInfoKey: Any]
}
}
extension ObjectDecoder.Decoder {
// MARK: - Swift.Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
return .init(_KeyedDecodingContainer<Key>(decoder: self, wrapping: try cast()))
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
return _UnkeyedDecodingContainer(decoder: self, wrapping: try cast())
}
public func singleValueContainer() throws -> SingleValueDecodingContainer { return self }
// MARK: -
private func applyStrategy<T: Decodable>(_ type: T.Type) throws -> T? {
if let strategy = options.decodingStrategies[type] ?? options.decodingStrategies[T.self] {
return try strategy.closure(self)
}
return nil
}
private func cast<T>() throws -> T {
guard let value = object as? T else {
throw _typeMismatch(at: codingPath, expectation: T.self, reality: object)
}
return value
}
// - SeeAlso: https://github.com/apple/swift/pull/11885
private func cast<T: ShouldNotBeDecodedFromBool>() throws -> T {
if let number = object as? NSNumber {
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw _typeMismatch(at: codingPath, expectation: NSNumber.self, reality: object)
}
guard let value = T.init(exactly: number) else {
throw _dataCorrupted(at: codingPath, "Parsed number <\(number)> does not fit in \(T.self).")
}
return value
} else if let value = object as? T {
return value
}
throw _typeMismatch(at: codingPath, expectation: T.self, reality: object)
}
private func cast() throws -> Bool {
if let number = object as? NSNumber {
if number === kCFBooleanTrue {
return true
} else if number === kCFBooleanFalse {
return false
}
throw _typeMismatch(at: codingPath, expectation: type(of: kCFBooleanTrue.self), reality: object)
} else if let bool = object as? Bool {
return bool
}
throw _typeMismatch(at: codingPath, expectation: Bool.self, reality: object)
}
/// create a new `_Decoder` instance referencing `object` as `key` inheriting `userInfo`
fileprivate func decoder(referencing object: Any, `as` key: CodingKey) -> ObjectDecoder.Decoder {
return .init(object, options, userInfo, codingPath + [key])
}
}
private struct _KeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
private let decoder: ObjectDecoder.Decoder
private let dictionary: [String: Any]
init(decoder: ObjectDecoder.Decoder, wrapping dictionary: [String: Any]) {
self.decoder = decoder
self.dictionary = dictionary
}
// MARK: - Swift.KeyedDecodingContainerProtocol Methods
var codingPath: [CodingKey] { return decoder.codingPath }
var allKeys: [Key] {
#if swift(>=4.1)
return dictionary.keys.compactMap(Key.init)
#else
return dictionary.keys.flatMap(Key.init)
#endif
}
func contains(_ key: Key) -> Bool { return dictionary[key.stringValue] != nil }
func decodeNil(forKey key: Key) throws -> Bool {
return try object(for: key) is NSNull
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try decoder(for: key).decode(type) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return try decoder(for: key).decode(type) }
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: ShouldNotBeDecodedFromBool {
return try decoder(for: key).decode(type)
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
return try decoder(for: key).decode(type)
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type,
forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
return try decoder(for: key).container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
return try decoder(for: key).unkeyedContainer()
}
func superDecoder() throws -> Decoder { return try decoder(for: _ObjectCodingKey.super) }
func superDecoder(forKey key: Key) throws -> Decoder { return try decoder(for: key) }
// MARK: -
private func object(for key: CodingKey) throws -> Any {
guard let object = dictionary[key.stringValue] else {
throw _keyNotFound(at: codingPath, key, "No value associated with key \(key) (\"\(key.stringValue)\").")
}
return object
}
private func decoder(for key: CodingKey) throws -> ObjectDecoder.Decoder {
return decoder.decoder(referencing: try object(for: key), as: key)
}
}
private struct _UnkeyedDecodingContainer: UnkeyedDecodingContainer {
private let decoder: ObjectDecoder.Decoder
private let array: [Any]
init(decoder: ObjectDecoder.Decoder, wrapping array: [Any]) {
self.decoder = decoder
self.array = array
self.currentIndex = 0
}
// MARK: - Swift.UnkeyedDecodingContainer Methods
var codingPath: [CodingKey] { return decoder.codingPath }
var count: Int? { return array.count }
var isAtEnd: Bool { return currentIndex >= array.count }
var currentIndex: Int
mutating func decodeNil() throws -> Bool {
try throwErrorIfAtEnd(Any?.self)
if currentObject is NSNull {
currentIndex += 1
return true
} else {
return false
}
}
mutating func decode(_ type: Bool.Type) throws -> Bool { return try currentDecoder { try $0.decode(type) } }
mutating func decode(_ type: String.Type) throws -> String { return try currentDecoder { try $0.decode(type) } }
mutating func decode<T>(_ type: T.Type) throws -> T where T: ShouldNotBeDecodedFromBool {
return try currentDecoder { try $0.decode(type) }
}
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
return try currentDecoder { try $0.decode(type) }
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
return try currentDecoder { try $0.container(keyedBy: type) }
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return try currentDecoder { try $0.unkeyedContainer() }
}
mutating func superDecoder() throws -> Decoder {
return try currentDecoder { $0 }
}
// MARK: -
private var currentKey: CodingKey { return _ObjectCodingKey(index: currentIndex) }
private var currentObject: Any { return array[currentIndex] }
private func throwErrorIfAtEnd<T>(_ type: T.Type) throws {
if isAtEnd { throw _valueNotFound(at: codingPath + [currentKey], type, "Unkeyed container is at end.") }
}
private mutating func currentDecoder<T>(closure: (ObjectDecoder.Decoder) throws -> T) throws -> T {
try throwErrorIfAtEnd(T.self)
let decoded: T = try closure(decoder.decoder(referencing: currentObject, as: currentKey))
currentIndex += 1
return decoded
}
}
extension ObjectDecoder.Decoder: SingleValueDecodingContainer {
// MARK: - Swift.SingleValueDecodingContainer Methods
public func decodeNil() -> Bool { return object is NSNull }
public func decode(_ type: Bool.Type) throws -> Bool { return try applyStrategy(type) ?? cast() }
public func decode(_ type: String.Type) throws -> String { return try applyStrategy(type) ?? cast() }
public func decode<T>(_ type: T.Type) throws -> T where T: ShouldNotBeDecodedFromBool {
return try applyStrategy(type) ?? cast()
}
public func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
return try applyStrategy(type) ?? type.init(from: self)
}
}
// MARK: - ShouldNotBeDecodedFromBool
// https://github.com/apple/swift/pull/11885
public protocol ShouldNotBeDecodedFromBool: Decodable {
// Swift 4.0 on darwin, Swift 4.0.2 on swift-corelibs-foundation
init?(exactly number: NSNumber)
}
extension Int: ShouldNotBeDecodedFromBool {}
extension Int8: ShouldNotBeDecodedFromBool {}
extension Int16: ShouldNotBeDecodedFromBool {}
extension Int32: ShouldNotBeDecodedFromBool {}
extension Int64: ShouldNotBeDecodedFromBool {}
extension UInt: ShouldNotBeDecodedFromBool {}
extension UInt8: ShouldNotBeDecodedFromBool {}
extension UInt16: ShouldNotBeDecodedFromBool {}
extension UInt32: ShouldNotBeDecodedFromBool {}
extension UInt64: ShouldNotBeDecodedFromBool {}
extension Float: ShouldNotBeDecodedFromBool {}
extension Double: ShouldNotBeDecodedFromBool {}
// MARK: - DecodingError helpers
// swiftlint:disable:next identifier_name
func _dataCorrupted(at codingPath: [CodingKey], _ description: String, _ error: Error? = nil) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description, underlyingError: error)
return .dataCorrupted(context)
}
private func _keyNotFound(at codingPath: [CodingKey], _ key: CodingKey, _ description: String) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
return.keyNotFound(key, context)
}
private func _valueNotFound(at codingPath: [CodingKey], _ type: Any.Type, _ description: String) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
return .valueNotFound(type, context)
}
private func _typeMismatch(at codingPath: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
let description = "Expected to decode \(expectation) but found \(type(of: reality)) instead."
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
return .typeMismatch(expectation, context)
}
// MARK: - ObjectDecoder.DecodingStrategy
extension ObjectDecoder {
/// The strategy to use for decoding `Data` values.
public typealias DataDecodingStrategy = DecodingStrategy<Data>
/// The strategy to use for decoding `Date` values.
public typealias DateDecodingStrategy = DecodingStrategy<Date>
/// The strategy to use for decoding `Double` values.
public typealias DoubleDecodingStrategy = DecodingStrategy<Double>
/// The strategy to use for decoding `Float` values.
public typealias FloatDecodingStrategy = DecodingStrategy<Float>
}
extension ObjectDecoder.DecodingStrategy {
/// Decode the `T` as a custom value decoded by the given closure.
public static func custom(_ closure: @escaping Closure) -> ObjectDecoder.DecodingStrategy<T> {
return .init(closure: closure)
}
}
extension ObjectDecoder.DecodingStrategy where T == Data {
/// Defer to `Data` for decoding.
public static let deferredToData: ObjectDecoder.DataDecodingStrategy? = nil
/// Decode the `Data` from a Base64-encoded string. This is the default strategy.
public static let base64 = ObjectDecoder.DataDecodingStrategy.custom { decoder in
guard let data = Data(base64Encoded: try String(from: decoder)) else {
throw _dataCorrupted(at: decoder.codingPath, "Encountered Data is not valid Base64.")
}
return data
}
}
extension ObjectDecoder.DecodingStrategy where T == Date {
/// Defer to `Date` for decoding.
public static let deferredToDate: ObjectDecoder.DateDecodingStrategy? = nil
/// Decode the `Date` as a UNIX timestamp from a `Double`.
public static let secondsSince1970 = ObjectDecoder.DateDecodingStrategy.custom { decoder in
Date(timeIntervalSince1970: try Double(from: decoder))
}
/// Decode the `Date` as UNIX millisecond timestamp from a `Double`.
public static let millisecondsSince1970 = ObjectDecoder.DateDecodingStrategy.custom { decoder in
Date(timeIntervalSince1970: try Double(from: decoder) / 1000.0)
}
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static let iso8601 = ObjectDecoder.DateDecodingStrategy.custom { decoder in
guard let date = iso8601Formatter.date(from: try String(from: decoder)) else {
throw _dataCorrupted(at: decoder.codingPath, "Expected date string to be ISO8601-formatted.")
}
return date
}
/// Decode the `Date` as a string parsed by the given formatter.
public static func formatted(_ formatter: DateFormatter) -> ObjectDecoder.DateDecodingStrategy {
return .custom { decoder in
guard let date = formatter.date(from: try String(from: decoder)) else {
throw _dataCorrupted(at: decoder.codingPath, "Date string does not match format expected by formatter.")
}
return date
}
}
}
extension ObjectDecoder.DecodingStrategy where T == Decimal {
public static let compatibleWithJSONDecoder = ObjectDecoder.DecodingStrategy<Decimal>.custom { decoder in
if let decimal = decoder.object as? Decimal {
return decimal
} else {
return Decimal(try Double(from: decoder))
}
}
}
extension ObjectDecoder.DecodingStrategy where T == Double {
public static let deferredToDouble: ObjectDecoder.DoubleDecodingStrategy? = nil
public static func convertNonConformingFloatFromString(_ positiveInfinity: String,
_ negativeInfinity: String,
_ nan: String) -> ObjectDecoder.DoubleDecodingStrategy {
return .custom { decoder in
if let double = decoder.object as? Double {
return double
} else if let string = decoder.object as? String {
if string == positiveInfinity {
return .infinity
} else if string == negativeInfinity {
return -.infinity
} else if string == nan {
return .nan
}
}
throw _typeMismatch(at: decoder.codingPath, expectation: Double.self, reality: decoder.object)
}
}
}
extension ObjectDecoder.DecodingStrategy where T == Float {
public static let deferredToFloat: ObjectDecoder.FloatDecodingStrategy? = nil
public static func convertNonConformingFloatFromString(_ positiveInfinity: String,
_ negativeInfinity: String,
_ nan: String) -> ObjectDecoder.FloatDecodingStrategy {
return .custom { decoder in
if let float = decoder.object as? Float {
return float
} else if let string = decoder.object as? String {
if string == positiveInfinity {
return .infinity
} else if string == negativeInfinity {
return -.infinity
} else if string == nan {
return .nan
}
}
throw _typeMismatch(at: decoder.codingPath, expectation: Float.self, reality: decoder.object)
}
}
}
extension ObjectDecoder.DecodingStrategy where T == URL {
public static let compatibleWithJSONDecoder = ObjectDecoder.DecodingStrategy<URL>.custom { decoder in
guard let url = URL(string: try String(from: decoder)) else {
throw _dataCorrupted(at: decoder.codingPath, "Invalid URL string.")
}
return url
}
}
// swiftlint:disable:this file_length
You can’t perform that action at this time.
