generated from dankinsoid/iOSLibraryTemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
TypeRevisionDecoder.swift
632 lines (534 loc) · 18.1 KB
/
TypeRevisionDecoder.swift
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import Foundation
final class TypeRevisionDecoder: Decoder {
typealias Cache = [ObjectIdentifier: (TypeInfo, Decodable)]
var path: [TypePath]
var codingPath: [CodingKey] { path.map(\.key) }
var userInfo: [CodingUserInfoKey: Any]
var result: TypeInfo
var context: TypeRevision
init(
path: [TypePath] = [],
context: TypeRevision
) {
self.path = path
userInfo = [:]
result = .any
self.context = context
}
func container<Key>(keyedBy _: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
result.container.keyed = KeyedInfo()
let container = TypeRevisionKeyedDecodingContainer<Key>(
path: path,
decoder: self,
result: Ref(self, \.result.container.keyed)
)
return KeyedDecodingContainer(container)
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
result.container.unkeyed = nil
return TypeRevisionSingleValueDecodingContainer(
isSingle: false,
path: path,
decoder: self,
result: Ref { [self] in
result.container.unkeyed
} set: { [self] newValue in
result.container.unkeyed = newValue
}
)
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
var wasSetted = false
return TypeRevisionSingleValueDecodingContainer(
isSingle: true,
path: path,
decoder: self,
result: Ref { [self] in
wasSetted ? result : nil
} set: { [self] newValue in
if let newValue {
wasSetted = true
result = newValue
}
}
)
}
@discardableResult
func decode(_ type: Decodable.Type) throws -> Decodable {
guard path.isEmpty || !path.dropLast().contains(where: { path in path.type == type }) else {
result.container = .recursive
result.type = type
if let decodable = collection(for: type) {
return decodable
}
if path.isEmpty {
throw AnyError("Cannot resolve recursive type \(type)")
} else {
throw AnyError("Cannot resolve recursive type \(type) at .\(path.map(\.key.stringValue).joined(separator: "."))")
}
}
let decodingError: Error
let decodable: Decodable?
do {
decodable = try type.init(from: self)
decodingError = AnyError("Unknown error")
} catch {
decodable = nil
decodingError = error
}
if let custom = context.customDescription(type, decodable) {
result.container = custom
} else {
switch type {
case is Date.Type:
let date = Date()
result.type = type
result.container = .single(.double(nil))
return date
case is URL.Type:
let url = URL(string: "https://github.com/dankinsoid/SwiftOpenAPI")!
result.container = .single(.string(nil))
result.type = type
return url
case is UUID.Type:
let uuid = UUID()
result.container = .single(.string(nil))
result.type = type
return uuid
case is Data.Type:
result.container = .single(.string(nil))
result.type = type
return Data()
case let iterable as any CaseIterable.Type:
result.type = type
let allCases = iterable.allCases as any Collection
if let result = (allCases.first as? Decodable) ?? decodable {
return result
}
throw AnyError("Cannot decode CaseIterable \(type) type with an empty allCases")
default:
if case .keyed = result.container {
let decoder = CheckAllKeysDecoder()
_ = try? type.init(from: decoder)
result.container.keyed.isFixed = !decoder.isAdditional
}
}
}
guard let value = decodable ?? collection(for: type) else {
throw decodingError
}
result.type = type
return value
}
private func collection(for type: Decodable.Type) -> Decodable? {
if let collectionType = type as? any RangeReplaceableCollection.Type {
return collectionType.init() as? Decodable
}
return nil
}
}
private struct TypeRevisionSingleValueDecodingContainer: SingleValueDecodingContainer, UnkeyedDecodingContainer {
var count: Int? { 1 }
var isAtEnd: Bool { currentIndex == 1 }
var currentIndex: Int {
result == nil ? 0 : 1
}
let isSingle: Bool
var path: [TypePath]
var codingPath: [CodingKey] { path.map(\.key) }
var decoder: TypeRevisionDecoder
@Ref var result: TypeInfo?
func decodeNil() -> Bool {
result[or: .any].isOptional = true
return false
}
func decode(_ type: Bool.Type) throws -> Bool {
result = TypeInfo(type: type, container: .single(.bool(nil)))
return true
}
func decodeIfPresent(_ type: Bool.Type) throws -> Bool? {
result = TypeInfo(type: type, isOptional: true, container: .single(.bool(nil)))
return nil
}
func decode(_ type: String.Type) throws -> String {
result = TypeInfo(type: type, container: .single(.string(nil)))
return ""
}
func decodeIfPresent(_ type: String.Type) throws -> String? {
result = TypeInfo(type: type, isOptional: true, container: .single(.string(nil)))
return nil
}
func decode(_ type: Double.Type) throws -> Double {
result = TypeInfo(type: type, container: .single(.double(nil)))
return 0
}
func decodeIfPresent(_ type: Double.Type) throws -> Double? {
result = TypeInfo(type: type, isOptional: true, container: .single(.double(nil)))
return nil
}
func decode(_ type: Float.Type) throws -> Float {
result = TypeInfo(type: type, container: .single(.float(nil)))
return 0
}
func decodeIfPresent(_ type: Float.Type) throws -> Float? {
result = TypeInfo(type: type, isOptional: true, container: .single(.float(nil)))
return nil
}
func decode(_ type: Int.Type) throws -> Int {
result = TypeInfo(type: type, container: .single(.int(nil)))
return 0
}
func decodeIfPresent(_ type: Int.Type) throws -> Int? {
result = TypeInfo(type: type, isOptional: true, container: .single(.int(nil)))
return nil
}
func decode(_ type: Int8.Type) throws -> Int8 {
result = TypeInfo(type: type, container: .single(.int8(nil)))
return 0
}
func decodeIfPresent(_ type: Int8.Type) throws -> Int8? {
result = TypeInfo(type: type, isOptional: true, container: .single(.int8(nil)))
return nil
}
func decode(_ type: Int16.Type) throws -> Int16 {
result = TypeInfo(type: type, container: .single(.int16(nil)))
return 0
}
func decodeIfPresent(_ type: Int16.Type) throws -> Int16? {
result = TypeInfo(type: type, isOptional: true, container: .single(.int16(nil)))
return nil
}
func decode(_ type: Int32.Type) throws -> Int32 {
result = TypeInfo(type: type, container: .single(.int32(nil)))
return 0
}
func decodeIfPresent(_ type: Int32.Type) throws -> Int32? {
result = TypeInfo(type: type, isOptional: true, container: .single(.int32(nil)))
return nil
}
func decode(_ type: Int64.Type) throws -> Int64 {
result = TypeInfo(type: type, container: .single(.int64(nil)))
return 0
}
func decodeIfPresent(_ type: Int64.Type) throws -> Int64? {
result = TypeInfo(type: type, isOptional: true, container: .single(.int64(nil)))
return nil
}
func decode(_ type: UInt.Type) throws -> UInt {
result = TypeInfo(type: type, container: .single(.uint(nil)))
return 0
}
func decodeIfPresent(_ type: UInt.Type) throws -> UInt? {
result = TypeInfo(type: type, isOptional: true, container: .single(.uint(nil)))
return nil
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
result = TypeInfo(type: type, container: .single(.uint8(nil)))
return 0
}
func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? {
result = TypeInfo(type: type, isOptional: true, container: .single(.uint8(nil)))
return nil
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
result = TypeInfo(type: type, container: .single(.uint16(nil)))
return 0
}
func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? {
result = TypeInfo(type: type, isOptional: true, container: .single(.uint16(nil)))
return nil
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
result = TypeInfo(type: type, container: .single(.uint32(nil)))
return 0
}
func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? {
result = TypeInfo(type: type, isOptional: true, container: .single(.uint32(nil)))
return nil
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
result = TypeInfo(type: type, container: .single(.uint64(nil)))
return 0
}
func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? {
result = TypeInfo(type: type, isOptional: true, container: .single(.uint64(nil)))
return nil
}
func decodeIfPresent<T>(_ type: T.Type) throws -> T? where T : Decodable {
_decodeIfPresent(type, optional: true)
}
func decode<T: Decodable>(_ type: T.Type) throws -> T {
guard let t = _decodeIfPresent(type, optional: false) else {
throw AnyError("Cannot create a mock instance of \(type)")
}
return t
}
private func _decodeIfPresent<T>(_ type: T.Type, optional: Bool) -> T? where T : Decodable {
let decoder = TypeRevisionDecoder(
path: nestedPath(for: optional ? Optional<T>.self : type),
context: decoder.context
)
let decodable = try? decoder.decode(type)
var value = decoder.result
if optional {
value.isOptional = true
}
value.type = type
result = value
return decodable as? T
}
func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type) -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
result[or: .any].container.keyed = KeyedInfo()
let container = TypeRevisionKeyedDecodingContainer<NestedKey>(
path: nestedPath(for: [String: Any].self),
decoder: decoder,
result: Ref { [$result] in
$result.wrappedValue[or: .any].container.keyed
} set: { [$result] newValue in
$result.wrappedValue[or: .any].container.keyed = newValue
}
)
return KeyedDecodingContainer(container)
}
func nestedUnkeyedContainer() -> UnkeyedDecodingContainer {
result[or: .any].container.unkeyed = .any
return TypeRevisionSingleValueDecodingContainer(
isSingle: false,
path: nestedPath(for: [Any].self),
decoder: decoder,
result: Ref { [$result] in
$result.wrappedValue[or: .any].container.unkeyed ?? .any
} set: { [$result] newValue in
$result.wrappedValue[or: .any].container.unkeyed = newValue
}
)
}
func superDecoder() -> Decoder {
TypeRevisionDecoder(path: path, context: decoder.context)
}
private func nestedPath(for type: Any.Type) -> [TypePath] {
isSingle ? path : path + [TypePath(type: type, key: IntKey(intValue: 0))]
}
}
private struct TypeRevisionKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
var allKeys: [Key] {
if let iterable = Key.self as? any CaseIterable.Type {
let array = iterable.allCases as any Collection
return Array(array.compactMap { $0 as? Key }.prefix(1))
}
return Key(stringValue: "").map { [$0] } ?? []
}
var path: [TypePath]
var codingPath: [CodingKey] { path.map(\.key) }
var decoder: TypeRevisionDecoder
@Ref var result: KeyedInfo
@inline(__always)
private func str(_ key: Key) -> String {
key.stringValue
}
func contains(_: Key) -> Bool { true }
func decodeNil(forKey key: Key) throws -> Bool {
result[str(key)].isOptional = true
return false
}
func decode(_: Bool.Type, forKey key: Key) throws -> Bool {
decode(.bool(nil), forKey: key, optional: false)
return true
}
func decodeIfPresent(_: Bool.Type, forKey key: Key) throws -> Bool? {
decode(.bool(nil), forKey: key, optional: true)
return nil
}
func decode(_: String.Type, forKey key: Key) throws -> String {
decode(.string(nil), forKey: key, optional: false)
return ""
}
func decodeIfPresent(_: String.Type, forKey key: Key) throws -> String? {
decode(.string(nil), forKey: key, optional: true)
return nil
}
func decode(_: Double.Type, forKey key: Key) throws -> Double {
decode(.double(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Double.Type, forKey key: Key) throws -> Double? {
decode(.double(nil), forKey: key, optional: true)
return nil
}
func decode(_: Float.Type, forKey key: Key) throws -> Float {
decode(.float(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Float.Type, forKey key: Key) throws -> Float? {
decode(.float(nil), forKey: key, optional: true)
return nil
}
func decode(_: Int.Type, forKey key: Key) throws -> Int {
decode(.int(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Int.Type, forKey key: Key) throws -> Int? {
decode(.int(nil), forKey: key, optional: true)
return nil
}
func decode(_: Int8.Type, forKey key: Key) throws -> Int8 {
decode(.int8(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Int8.Type, forKey key: Key) throws -> Int8? {
decode(.int8(nil), forKey: key, optional: true)
return nil
}
func decode(_: Int16.Type, forKey key: Key) throws -> Int16 {
decode(.int16(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Int16.Type, forKey key: Key) throws -> Int16? {
decode(.int16(nil), forKey: key, optional: true)
return nil
}
func decode(_: Int32.Type, forKey key: Key) throws -> Int32 {
decode(.int32(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Int32.Type, forKey key: Key) throws -> Int32? {
decode(.int32(nil), forKey: key, optional: true)
return nil
}
func decode(_: Int64.Type, forKey key: Key) throws -> Int64 {
decode(.int64(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: Int64.Type, forKey key: Key) throws -> Int64? {
decode(.int64(nil), forKey: key, optional: true)
return nil
}
func decode(_: UInt.Type, forKey key: Key) throws -> UInt {
decode(.uint(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: UInt.Type, forKey key: Key) throws -> UInt? {
decode(.uint(nil), forKey: key, optional: true)
return nil
}
func decode(_: UInt8.Type, forKey key: Key) throws -> UInt8 {
decode(.uint8(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: UInt8.Type, forKey key: Key) throws -> UInt8? {
decode(.uint8(nil), forKey: key, optional: true)
return nil
}
func decode(_: UInt16.Type, forKey key: Key) throws -> UInt16 {
decode(.uint16(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: UInt16.Type, forKey key: Key) throws -> UInt16? {
decode(.uint16(nil), forKey: key, optional: true)
return nil
}
func decode(_: UInt32.Type, forKey key: Key) throws -> UInt32 {
decode(.uint32(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: UInt32.Type, forKey key: Key) throws -> UInt32? {
decode(.uint32(nil), forKey: key, optional: true)
return nil
}
func decode(_: UInt64.Type, forKey key: Key) throws -> UInt64 {
decode(.uint64(nil), forKey: key, optional: false)
return 0
}
func decodeIfPresent(_: UInt64.Type, forKey key: Key) throws -> UInt64? {
decode(.uint64(nil), forKey: key, optional: true)
return nil
}
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
try decode(type, forKey: key, optional: false)
}
func decodeIfPresent<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T? {
try? decode(type, forKey: key, optional: true)
}
private func decode<T: Decodable>(_ type: T.Type, forKey key: Key, optional: Bool) throws -> T {
let decoder = TypeRevisionDecoder(
path: nestedPath(for: key, optional ? Optional<T>.self : type),
context: decoder.context
)
let decodeResult = Result {
try decoder.decode(type)
}
var value = decoder.result
value.type = type
value.isOptional = optional
result[str(key)] = value
switch decodeResult {
case .success(let decodable):
guard let t = decodable as? T else {
throw DecodingError.typeMismatch(
T.self,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "Expected to decode \(T.self) but found \(Swift.type(of: decodable)) instead."
)
)
}
return t
case .failure(let failure):
throw failure
}
}
func nestedContainer<NestedKey: CodingKey>(keyedBy _: NestedKey.Type, forKey key: Key) -> KeyedDecodingContainer<NestedKey> {
let strKey = str(key)
let container = TypeRevisionKeyedDecodingContainer<NestedKey>(
path: nestedPath(for: key, [String: Any].self),
decoder: decoder,
result: Ref(self, \.result[strKey].container.keyed)
)
result[strKey].container.keyed = KeyedInfo()
return KeyedDecodingContainer(container)
}
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedDecodingContainer {
let strKey = str(key)
let container = TypeRevisionSingleValueDecodingContainer(
isSingle: false,
path: nestedPath(for: key, [Any].self),
decoder: decoder,
result: Ref { [$result] in
$result.wrappedValue[strKey].container.unkeyed ?? .any
} set: { [$result] newValue in
$result.wrappedValue[strKey].container.unkeyed = newValue
}
)
result[strKey].container.unkeyed = .any
return container
}
func superDecoder() -> Decoder {
TypeRevisionDecoder(path: path, context: decoder.context)
}
func superDecoder(forKey key: Key) -> Decoder {
TypeRevisionDecoder(path: nestedPath(for: key, Any.self), context: decoder.context)
}
private func nestedPath(for key: Key, _ type: Any.Type) -> [TypePath] {
path + [TypePath(type: type, key: key)]
}
@inline(__always)
private func decode(_ value: CodableValues, forKey key: Key, optional: Bool) {
result[str(key)] = TypeInfo(type: value.type, isOptional: optional, container: .single(value))
}
}
private struct AnyError: LocalizedError {
var errorDescription: String?
init(_ errorDescription: String? = nil) {
self.errorDescription = errorDescription
}
}
private extension Optional {
subscript(or value: Wrapped) -> Wrapped {
get { self ?? value }
set { self = value }
}
}
struct TypePath {
var type: Any.Type
var key: CodingKey
}