-
Notifications
You must be signed in to change notification settings - Fork 104
/
XMLDecoder.swift
831 lines (638 loc) · 33.3 KB
/
XMLDecoder.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//
// XMLDecoder.swift
// XMLCoder
//
// Created by Shawn Moore on 11/20/17.
// Copyright © 2017 Shawn Moore. All rights reserved.
//
import Foundation
//===----------------------------------------------------------------------===//
// XML Decoder
//===----------------------------------------------------------------------===//
/// `XMLDecoder` facilitates the decoding of XML into semantic `Decodable` types.
open class XMLDecoder {
// MARK: Options
/// The strategy to use for decoding `Date` values.
public enum DateDecodingStrategy {
/// Defer to `Date` for decoding. This is the default strategy.
case deferredToDate
/// Decode the `Date` as a UNIX timestamp from a XML number. This is the default strategy.
case secondsSince1970
/// Decode the `Date` as UNIX millisecond timestamp from a XML number.
case millisecondsSince1970
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decode the `Date` as a string parsed by the given formatter.
case formatted(DateFormatter)
/// Decode the `Date` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Date)
/// Decode the `Date` as a string parsed by the given formatter for the give key.
static func keyFormatted(_ formatterForKey: @escaping (CodingKey) throws -> DateFormatter?) -> XMLDecoder.DateDecodingStrategy {
return .custom({ (decoder) -> Date in
guard let codingKey = decoder.codingPath.last else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "No Coding Path Found"))
}
guard let container = try? decoder.singleValueContainer(),
let text = try? container.decode(String.self) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date text"))
}
guard let dateFormatter = try formatterForKey(codingKey) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "No date formatter for date text")
}
if let date = dateFormatter.date(from: text) {
return date
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(text)")
}
})
}
}
/// The strategy to use for decoding `Data` values.
public enum DataDecodingStrategy {
/// Defer to `Data` for decoding.
case deferredToData
/// Decode the `Data` from a Base64-encoded string. This is the default strategy.
case base64
/// Decode the `Data` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Data)
/// Decode the `Data` as a custom value by the given closure for the give key.
static func keyFormatted(_ formatterForKey: @escaping (CodingKey) throws -> Data?) -> XMLDecoder.DataDecodingStrategy {
return .custom({ (decoder) -> Data in
guard let codingKey = decoder.codingPath.last else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "No Coding Path Found"))
}
guard let container = try? decoder.singleValueContainer(),
let text = try? container.decode(String.self) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date text"))
}
guard let data = try formatterForKey(codingKey) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode data string \(text)")
}
return data
})
}
}
/// The strategy to use for non-XML-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatDecodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Decode the values from the given representation strings.
case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use for automatically changing the value of keys before decoding.
public enum KeyDecodingStrategy {
/// Use the keys specified by each type. This is the default strategy.
case useDefaultKeys
/// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type.
///
/// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
///
/// Converting from snake case to camel case:
/// 1. Capitalizes the word starting after each `_`
/// 2. Removes all `_`
/// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata).
/// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`.
///
/// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character.
case convertFromSnakeCase
/// Convert from "CodingKey" to "codingKey"
case convertFromCapitalized
/// Provide a custom conversion from the key in the encoded XML to the keys specified by the decoded types.
/// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding.
/// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from.
case custom((_ codingPath: [CodingKey]) -> CodingKey)
static func _convertFromCapitalized(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
var result = stringKey
let range = result.startIndex...result.index(after: result.startIndex)
result.replaceSubrange(range, with: result[range].lowercased())
return result
}
static func _convertFromSnakeCase(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
// Find the first non-underscore character
guard let firstNonUnderscore = stringKey.index(where: { $0 != "_" }) else {
// Reached the end without finding an _
return stringKey
}
// Find the last non-underscore character
var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
stringKey.formIndex(before: &lastNonUnderscore)
}
let keyRange = firstNonUnderscore...lastNonUnderscore
let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex
var components = stringKey[keyRange].split(separator: "_")
let joinedString: String
if components.count == 1 {
// No underscores in key, leave the word as is - maybe already camel cased
joinedString = String(stringKey[keyRange])
} else {
joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
}
// Do a cheap isEmpty check before creating and appending potentially empty strings
let result: String
if leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty {
result = joinedString
} else if !leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty {
// Both leading and trailing underscores
result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange])
} else if !leadingUnderscoreRange.isEmpty {
// Just leading
result = String(stringKey[leadingUnderscoreRange]) + joinedString
} else {
// Just trailing
result = joinedString + String(stringKey[trailingUnderscoreRange])
}
return result
}
}
/// The strategy to use in decoding dates. Defaults to `.secondsSince1970`.
open var dateDecodingStrategy: DateDecodingStrategy = .secondsSince1970
/// The strategy to use in decoding binary data. Defaults to `.base64`.
open var dataDecodingStrategy: DataDecodingStrategy = .base64
/// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
/// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`.
open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey: Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
internal struct _Options {
let dateDecodingStrategy: DateDecodingStrategy
let dataDecodingStrategy: DataDecodingStrategy
let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
let keyDecodingStrategy: KeyDecodingStrategy
let userInfo: [CodingUserInfoKey: Any]
}
/// The options set on the top-level decoder.
internal var options: _Options {
return _Options(dateDecodingStrategy: dateDecodingStrategy,
dataDecodingStrategy: dataDecodingStrategy,
nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy,
keyDecodingStrategy: keyDecodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a XML Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given XML representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid XML.
/// - throws: An error if any value throws an error during decoding.
open func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
let topLevel: [String: Any]
do {
topLevel = try _XMLStackParser.parse(with: data)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid XML.", underlyingError: error))
}
let decoder = _XMLDecoder(referencing: topLevel, options: options)
guard let value = try decoder.unbox(topLevel, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
}
// MARK: - _XMLDecoder
internal class _XMLDecoder: Decoder {
// MARK: Properties
/// The decoder's storage.
internal var storage: _XMLDecodingStorage
/// Options set on the top-level decoder.
internal let options: XMLDecoder._Options
/// The path to the current point in encoding.
public internal(set) var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey: Any] {
return options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
internal init(referencing container: Any, at codingPath: [CodingKey] = [], options: XMLDecoder._Options) {
storage = _XMLDecodingStorage()
storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy _: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let topContainer = storage.topContainer as? [String: Any] else {
throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Any].self, reality: storage.topContainer)
}
let container = _XMLKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
let topContainer: [Any]
if let container = storage.topContainer as? [Any] {
topContainer = container
} else {
topContainer = [storage.topContainer]
}
return _XMLUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
extension _XMLDecoder: SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
return storage.topContainer is NSNull
}
public func decode(_: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try unbox(storage.topContainer, as: Bool.self)!
}
public func decode(_: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try unbox(storage.topContainer, as: Int.self)!
}
public func decode(_: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try unbox(storage.topContainer, as: Int8.self)!
}
public func decode(_: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try unbox(storage.topContainer, as: Int16.self)!
}
public func decode(_: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try unbox(storage.topContainer, as: Int32.self)!
}
public func decode(_: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try unbox(storage.topContainer, as: Int64.self)!
}
public func decode(_: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try unbox(storage.topContainer, as: UInt.self)!
}
public func decode(_: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try unbox(storage.topContainer, as: UInt8.self)!
}
public func decode(_: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try unbox(storage.topContainer, as: UInt16.self)!
}
public func decode(_: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try unbox(storage.topContainer, as: UInt32.self)!
}
public func decode(_: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try unbox(storage.topContainer, as: UInt64.self)!
}
public func decode(_: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try unbox(storage.topContainer, as: Float.self)!
}
public func decode(_: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try unbox(storage.topContainer, as: Double.self)!
}
public func decode(_: String.Type) throws -> String {
try expectNonNull(String.self)
return try unbox(storage.topContainer, as: String.self)!
}
public func decode<T: Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(type)
return try unbox(storage.topContainer, as: type)!
}
}
// MARK: - Concrete Value Representations
extension _XMLDecoder {
/// Returns the given value unboxed from a container.
internal func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
guard !(value is NSNull) else { return nil }
guard let value = value as? String else { return nil }
if value == "true" || value == "1" {
return true
} else if value == "false" || value == "0" {
return false
}
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
internal func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return int
}
internal func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return int8
}
internal func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return int16
}
internal func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return int32
}
internal func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return int64
}
internal func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return uint
}
internal func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return uint8
}
internal func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return uint16
}
internal func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return uint32
}
internal func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
guard let value = Float(string) else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: string)
}
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number <\(number)> does not fit in \(type)."))
}
return uint64
}
internal func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
if let value = Double(string) {
let number = NSNumber(value: value)
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
let double = number.doubleValue
guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Parsed XML number \(number) does not fit in \(type)."))
}
return Float(double)
} else if case let .convertFromString(posInfString, negInfString, nanString) = options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Float.infinity
} else if string == negInfString {
return -Float.infinity
} else if string == nanString {
return Float.nan
}
}
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
internal func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else { return nil }
if let number = Decimal(string: string) as NSDecimalNumber? {
guard number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
return number.doubleValue
} else if case let .convertFromString(posInfString, negInfString, nanString) = options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Double.infinity
} else if string == negInfString {
return -Double.infinity
} else if string == nanString {
return Double.nan
}
}
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
internal func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
return string
}
internal func unbox(_ value: Any, as _: Date.Type) throws -> Date? {
guard !(value is NSNull) else { return nil }
switch options.dateDecodingStrategy {
case .deferredToDate:
storage.push(container: value)
defer { storage.popContainer() }
return try Date(from: self)
case .secondsSince1970:
let double = try unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double)
case .millisecondsSince1970:
let double = try unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double / 1000.0)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let string = try unbox(value, as: String.self)!
guard let date = _iso8601Formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
}
return date
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case let .formatted(formatter):
let string = try unbox(value, as: String.self)!
guard let date = formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Date string does not match format expected by formatter."))
}
return date
case let .custom(closure):
storage.push(container: value)
defer { storage.popContainer() }
return try closure(self)
}
}
internal func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
guard !(value is NSNull) else { return nil }
switch options.dataDecodingStrategy {
case .deferredToData:
storage.push(container: value)
defer { storage.popContainer() }
return try Data(from: self)
case .base64:
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
}
guard let data = Data(base64Encoded: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Encountered Data is not valid Base64."))
}
return data
case let .custom(closure):
storage.push(container: value)
defer { storage.popContainer() }
return try closure(self)
}
}
internal func unbox(_ value: Any, as _: Decimal.Type) throws -> Decimal? {
guard !(value is NSNull) else { return nil }
// Attempt to bridge from NSDecimalNumber.
let doubleValue = try unbox(value, as: Double.self)!
return Decimal(doubleValue)
}
internal func unbox<T: Decodable>(_ value: Any, as type: T.Type) throws -> T? {
let decoded: T
if type == Date.self || type == NSDate.self {
guard let date = try unbox(value, as: Date.self) else { return nil }
decoded = date as! T
} else if type == Data.self || type == NSData.self {
guard let data = try unbox(value, as: Data.self) else { return nil }
decoded = data as! T
} else if type == URL.self || type == NSURL.self {
guard let urlString = try unbox(value, as: String.self) else {
return nil
}
guard let url = URL(string: urlString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "Invalid URL string."))
}
decoded = (url as! T)
} else if type == Decimal.self || type == NSDecimalNumber.self {
guard let decimal = try unbox(value, as: Decimal.self) else { return nil }
decoded = decimal as! T
} else {
storage.push(container: value)
defer { storage.popContainer() }
return try type.init(from: self)
}
return decoded
}
}