-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathCBORParser.swift
More file actions
1292 lines (1027 loc) · 54.8 KB
/
CBORParser.swift
File metadata and controls
1292 lines (1027 loc) · 54.8 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
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// CBORParser.swift
// CBORCoding
//
// Copyright © 2021 SomeRandomiOSDev. All rights reserved.
//
import Foundation
@_implementationOnly import Half
// MARK: - CBORParser Definition
internal class CBORParser {
// MARK: Internal Methods
// swiftlint:disable function_body_length
internal class func parse(_ data: Data, codingPath: [CodingKey] = []) throws -> Any? {
guard !data.isEmpty else { return nil }
var storage = Storage()
var index = data.startIndex
do {
while index < data.endIndex {
let majorType = CBOR.majorType(for: data[index])
switch majorType {
case .unsigned:
let unsigned = try decode(UInt64.self, from: data[index...])
try storage.append(unsigned.value)
index += unsigned.decodedBytes
case .negative:
let signed: (value: Any, decodedBytes: Int)
do {
let result = try decode(Int64.self, from: data[index...])
signed = (result.value, result.decodedBytes)
} catch let firstError {
do {
let result = try decode(CBOR.NegativeUInt64.self, from: data[index...])
signed = (result.value, result.decodedBytes)
} catch {
throw firstError
}
}
try storage.append(signed.value)
index += signed.decodedBytes
case .bytes:
let bytes = try decode(Data.self, from: data[index...])
try storage.append(bytes.value)
index += bytes.decodedBytes
case .string:
let string = try decode(String.self, from: data[index...])
try storage.append(string.value)
index += string.decodedBytes
case .array:
let additionalInfo = CBOR.additionalInfo(for: data[index])
if additionalInfo == 31 { // Indefinite length array
try storage.startUnkeyedContainer(ofLength: nil)
index += 1
} else {
let unsigned = try decode(UInt64.self, from: data[index...], knownMajorType: majorType)
try storage.startUnkeyedContainer(ofLength: unsigned.value)
index += unsigned.decodedBytes
}
case .map:
let additionalInfo = CBOR.additionalInfo(for: data[index])
if additionalInfo == 31 { // Indefinite length map
try storage.startKeyedContainer(ofLength: nil)
index += 1
} else {
let unsigned = try decode(UInt64.self, from: data[index...], knownMajorType: majorType)
try storage.startKeyedContainer(ofLength: unsigned.value)
index += unsigned.decodedBytes
}
case .tag:
if let tag = CBOR.Tag(bits: data[index...]) {
index += tag.bits.count
switch tag {
case .standardDateTime, .epochDateTime:
let date = try decode(Date.self, tag: tag, from: data[index...])
try storage.append(date.value)
index += date.decodedBytes
case .positiveBignum, .negativeBignum:
let bignum = try decode(CBOR.Bignum.self, tag: tag, from: data[index...])
try storage.append(bignum.value)
index += bignum.decodedBytes
case .decimalFraction:
let decimal = try decode(CBOR.DecimalFraction<Int64, Int64>.self, from: data[index...])
try storage.append(decimal.value)
index += decimal.decodedBytes
case .bigfloat:
let bigfloat = try decode(CBOR.Bigfloat<Int64, Int64>.self, from: data[index...])
try storage.append(bigfloat.value)
index += bigfloat.decodedBytes
case .base64URLConversion, .base64Conversion, .base16Conversion:
do {
let string = try decode(String.self, from: data[index...])
try storage.append(string.value)
index += string.decodedBytes
} catch {
do {
let bytes = try decode(Data.self, from: data[index...])
try storage.append(bytes.value)
index += bytes.decodedBytes
} catch {
throw CBOR.DecodingError.dataCorrupted(description: "Unable to decode string or data for tag \"\(tag.description)\"")
}
}
case .encodedCBORData:
let bytes = try decode(Data.self, from: data[index...])
try storage.append(bytes.value)
index += bytes.decodedBytes
case .uri:
let url = try decode(URL.self, from: data[index...])
try storage.append(url.value)
index += url.decodedBytes
case .base64URL, .base64, .regularExpression:
let string = try decode(String.self, from: data[index...])
let decodedString = try string.value.decodedStringValue()
if tag == .base64URL {
let data = Data(base64Encoded: decodedString.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
.appending(String(repeating: "=", count: decodedString.count % 4)))
guard let validatedData = data else {
throw CBOR.DecodingError.dataCorrupted(description: "Invalid Base64-URL encoded string")
}
try storage.append(validatedData)
} else if tag == .base64 {
guard let data = Data(base64Encoded: decodedString) else {
throw CBOR.DecodingError.dataCorrupted(description: "Invalid Base64 encoded string")
}
try storage.append(data)
} else /* if tag == .regularExpression */ {
guard (try? NSRegularExpression(pattern: decodedString, options: [])) != nil else {
throw CBOR.DecodingError.dataCorrupted(description: "Invalid Regular Expression")
}
try storage.append(decodedString)
}
index += string.decodedBytes
case .mimeMessage:
let string = try decode(String.self, from: data[index...])
try storage.append(string.value)
index += string.decodedBytes
case .selfDescribedCBOR:
break // skip the tag and continue
}
} else {
let unsigned: UInt64
do {
unsigned = try decode(UInt64.self, from: data[index...], knownMajorType: .tag).value
} catch {
throw CBOR.DecodingError.dataCorrupted(description: "Invalid CBOR tag")
}
throw CBOR.DecodingError.dataCorrupted(description: "Invalid CBOR tag <\(unsigned)>")
}
case .additonal:
let additionalInfo = CBOR.additionalInfo(for: data[index])
switch additionalInfo {
case 0...19:
try storage.append(CBOR.SimpleValue(rawValue: additionalInfo))
index += 1
case 20:
try storage.append(false)
index += 1
case 21:
try storage.append(true)
index += 1
case 22:
try storage.append(CBOR.Null())
index += 1
case 23:
try storage.append(CBOR.Undefined())
index += 1
case 24:
let simple = try decode(CBOR.SimpleValue.self, from: data[index...])
try storage.append(simple.value)
index += simple.decodedBytes
case 25:
let half = try decode(Half.self, from: data[index...])
try storage.append(half.value)
index += half.decodedBytes
case 26:
let float = try decode(Float.self, from: data[index...])
try storage.append(float.value)
index += float.decodedBytes
case 27:
let double = try decode(Double.self, from: data[index...])
try storage.append(double.value)
index += double.decodedBytes
case 31: // Break
try storage.endCurrentContainer()
index += 1
default:
throw CBOR.DecodingError.dataCorrupted(description: "Invalid decoded value for major type 7 (\(additionalInfo))")
}
}
}
} catch let error as CBOR.DecodingError {
throw Swift.DecodingError(internalError: error, at: codingPath)
}
return try storage.finalize()
}
internal class func type(for bytes: Data) throws -> Any.Type {
do {
guard !bytes.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: nil)
}
let type: Any.Type
let majorType = CBOR.majorType(for: bytes[bytes.startIndex])
let additionalInfo = CBOR.additionalInfo(for: bytes[bytes.startIndex])
switch majorType {
case .unsigned:
switch additionalInfo {
case 0...24: type = UInt8.self
case 25: type = UInt16.self
case 26: type = UInt32.self
case 27: type = UInt64.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded length for expected unsigned integer")
}
case .negative:
switch additionalInfo {
case 0...24: type = Int8.self
case 25: type = Int16.self
case 26: type = Int32.self
case 27: type = Int64.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded length for expected signed integer")
}
case .bytes:
switch additionalInfo {
case 0...27: type = Data.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded byte length for expected data")
}
case .string:
switch additionalInfo {
case 0...27: type = String.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded byte length for expected string")
}
case .array:
switch additionalInfo {
case 0...27: type = Array<Any>.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded byte length for expected array")
}
case .map:
switch additionalInfo {
case 0...27: type = Dictionary<String, Any>.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded byte length for expected map")
}
case .tag:
switch additionalInfo {
case 0, 1: type = Date.self
case 2, 3: type = Data.self
case 4, 5: type = Array<Int>.self
case 21...23: type = Data.self
case 24:
guard bytes.count > 1 else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: nil)
}
switch bytes[bytes.index(after: bytes.startIndex)] {
case 24: type = Data.self
case 32...36: type = String.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded tag")
}
case 25:
guard bytes.count > 2 else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: nil)
}
switch (bytes[bytes.index(bytes.startIndex, offsetBy: 1)], bytes[bytes.index(bytes.startIndex, offsetBy: 2)]) {
case (0xD9, 0xF7): type = Data.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded tag")
}
default:
throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded tag")
}
case .additonal:
switch additionalInfo {
case 0...19: type = CBOR.SimpleValue.self
case 20, 21: type = Bool.self
case 22: type = CBOR.Null.self
case 23: type = CBOR.Undefined.self
case 24: type = CBOR.SimpleValue.self
case 25, 26: type = Float.self
case 27: type = Double.self
case 31: type = CBOR.Break.self
default: throw CBOR.DecodingError.dataCorrupted(description: "Invalid encoded data type")
}
}
return type
} catch let error as CBOR.DecodingError {
throw Swift.DecodingError(internalError: error, at: [])
}
}
// swiftlint:enable function_body_length
// MARK: Private Methods
// swiftlint:disable function_body_length
private class func decode(_ type: String.Type, from data: Data) throws -> (value: CBORDecodedString, decodedBytes: Int) {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .string else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let additionalInfo = CBOR.additionalInfo(for: data[data.startIndex])
let result: (value: CBORDecodedString, decodedBytes: Int)
if additionalInfo == 31 {
// Indefinite length string
guard data.count > 1 else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
var index = data.index(after: data.startIndex)
var resultString = CBOR.IndefiniteLengthString()
while true {
guard index < data.endIndex else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
guard data[index] != CBOR.Bits.break.rawValue else {
index = data.index(after: index) // for the `break` byte
break
}
let count = try decode(UInt64.self, from: Data(data[index...]), knownMajorType: majorType)
if count.value == 0 {
resultString.chunks.append(Data())
index += count.decodedBytes
} else {
guard let nextIndex = data.index(index, offsetBy: count.decodedBytes + Int(count.value), limitedBy: data.endIndex), data.endIndex > nextIndex else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let utf8Data = Data(data[data.index(index, offsetBy: count.decodedBytes) ..< nextIndex])
resultString.chunks.append(utf8Data)
index = nextIndex
}
}
result = (resultString, data.distance(from: data.startIndex, to: index))
} else {
// Definite length string
let count = try decode(UInt64.self, from: data, knownMajorType: majorType)
if count.value == 0 {
result = ("", count.decodedBytes)
} else {
guard let nextIndex = data.index(data.startIndex, offsetBy: Int(count.value + UInt64(count.decodedBytes)), limitedBy: data.endIndex), data.endIndex >= nextIndex else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let utf8Data = Data(data[data.index(data.startIndex, offsetBy: count.decodedBytes) ..< nextIndex])
guard let string = String(data: utf8Data, encoding: .utf8) else {
throw CBOR.DecodingError.invalidUTF8String
}
result = (string, count.decodedBytes + Int(count.value))
}
}
return result
}
// swiftlint:enable function_body_length
private class func decode(_ type: Data.Type, from data: Data) throws -> (value: CBORDecodedData, decodedBytes: Int) {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .bytes else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let additionalInfo = CBOR.additionalInfo(for: data[data.startIndex])
let result: (value: CBORDecodedData, decodedBytes: Int)
if additionalInfo == 31 {
// Indefinite length byte data
guard data.count > 1 else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
var index = data.index(after: data.startIndex)
var resultData = CBOR.IndefiniteLengthData()
repeat {
guard index < data.endIndex else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
guard data[index] != CBOR.Bits.break.rawValue else {
index = data.index(after: index) // for the `break` byte
break
}
let decoded = try decode(type, from: Data(data[index...]))
resultData.chunks.append(decoded.value.decodedDataValue())
index = data.index(index, offsetBy: decoded.decodedBytes)
} while true
result = (resultData, data.distance(from: data.startIndex, to: index))
} else {
// Definite length byte data
let count = try decode(UInt64.self, from: data, knownMajorType: majorType)
if count.value == 0 {
result = (Data(), count.decodedBytes)
} else {
guard let nextIndex = data.index(data.startIndex, offsetBy: count.decodedBytes + Int(count.value), limitedBy: data.endIndex), data.endIndex >= nextIndex else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
result = (data[data.index(data.startIndex, offsetBy: count.decodedBytes) ..< nextIndex], count.decodedBytes + Int(count.value))
}
}
return result
}
private class func decode(_ type: Date.Type, tag: CBOR.Tag, from data: Data) throws -> (value: Date, decodedBytes: Int) {
precondition(tag == .standardDateTime || tag == .epochDateTime)
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let result: (value: Date, decodedBytes: Int)
if tag == .standardDateTime { // RFC3339
let dateString = try decode(String.self, from: data)
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
guard let date = formatter.date(from: try dateString.value.decodedStringValue()) else {
throw CBOR.DecodingError.invalidRFC3339DateString
}
result = (date, dateString.decodedBytes)
} else /* if tag == .epochDateTime */ { // Epoch
do {
let timeInterval = try decode(Double.self, from: data)
result = (Date(timeIntervalSince1970: TimeInterval(timeInterval.value)), timeInterval.decodedBytes)
} catch {
do {
let timeInterval = try decode(Int64.self, from: data)
result = (Date(timeIntervalSince1970: TimeInterval(timeInterval.value)), timeInterval.decodedBytes)
} catch {
do {
let timeInterval = try decode(UInt64.self, from: data)
result = (Date(timeIntervalSince1970: TimeInterval(timeInterval.value)), timeInterval.decodedBytes)
} catch {
throw CBOR.DecodingError.typeMismatch(expected: [TimeInterval.self, Int.self, UInt.self], actual: try self.type(for: data))
}
}
}
}
return result
}
private class func decode(_ type: URL.Type, from data: Data) throws -> (value: URL, decodedBytes: Int) {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .string else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let string = try decode(String.self, from: data)
guard let url = URL(string: try string.value.decodedStringValue()) else {
throw CBOR.DecodingError.dataCorrupted(description: "Invalid URL string.")
}
return (url, string.decodedBytes)
}
private class func decode(_ type: CBOR.NegativeUInt64.Type, from data: Data) throws -> (value: CBOR.NegativeUInt64, decodedBytes: Int) {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .negative else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let unsigned = try decode(UInt64.self, from: data, knownMajorType: majorType)
return (CBOR.NegativeUInt64(rawValue: unsigned.value == .max ? .min : (unsigned.value + 1)), unsigned.decodedBytes)
}
private class func decode(_ type: CBOR.SimpleValue.Type, from data: Data) throws -> (value: CBOR.SimpleValue, decodedBytes: Int) {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .additonal else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let additionalInfo = CBOR.additionalInfo(for: data[data.startIndex])
let result: (value: CBOR.SimpleValue, decodedBytes: Int)
switch additionalInfo {
case 24:
guard data.count > 1 else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
result = (CBOR.SimpleValue(rawValue: data[data.index(after: data.startIndex)]), 2)
default:
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
return result
}
private class func decode(_ type: CBOR.Bignum.Type, tag: CBOR.Tag, from data: Data) throws -> (value: CBOR.Bignum, decodedBytes: Int) {
precondition(tag == .positiveBignum || tag == .negativeBignum)
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let bytes = try decode(Data.self, from: data)
return (CBOR.Bignum(isPositive: tag == .positiveBignum, content: bytes.value.decodedDataValue()), bytes.decodedBytes)
}
// swiftlint:disable function_body_length
private class func decode<T>(_ type: T.Type, from data: Data) throws -> (value: T, decodedBytes: Int) where T: BinaryFloatingPoint, T.RawExponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let header = data[data.startIndex]
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .additonal else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let result: (value: T, decodedBytes: Int)
if header == CBOR.Bits.half.rawValue { // Half
if data.count >= 3 {
// swiftlint:disable force_unwrapping
let half = data[data.index(data.startIndex, offsetBy: 1) ..< data.index(data.startIndex, offsetBy: 3)].reversed().withUnsafeBytes { $0.bindMemory(to: Half.self).baseAddress!.pointee }
// swiftlint:enable force_unwrapping
if half.isNaN {
if half.isSignalingNaN {
result = (.signalingNaN, 3)
} else {
result = (.nan, 3)
}
} else if half.isInfinite {
if half.sign == .minus {
result = (-.infinity, 3)
} else {
result = (.infinity, 3)
}
} else if let value = T(exactly: half) {
result = (value, 3)
} else {
throw CBOR.DecodingError.dataCorrupted(description: "Decoded number <\(half)> does not fit in \(type).")
}
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else if header == CBOR.Bits.float.rawValue { // Single
if data.count >= 5 {
// swiftlint:disable force_unwrapping
let float = data[data.index(data.startIndex, offsetBy: 1) ..< data.index(data.startIndex, offsetBy: 5)].reversed().withUnsafeBytes { $0.bindMemory(to: Float.self).baseAddress!.pointee }
// swiftlint:enable force_unwrapping
if float.isNaN {
if float.isSignalingNaN {
result = (.signalingNaN, 5)
} else {
result = (.nan, 5)
}
} else if float.isInfinite {
if float.sign == .minus {
result = (-.infinity, 5)
} else {
result = (.infinity, 5)
}
} else if let value = T(exactly: float) {
result = (value, 5)
} else {
throw CBOR.DecodingError.dataCorrupted(description: "Decoded number <\(float)> does not fit in \(type).")
}
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else if header == CBOR.Bits.double.rawValue { // Double
if data.count >= 9 {
// swiftlint:disable force_unwrapping
let double = data[data.index(data.startIndex, offsetBy: 1) ..< data.index(data.startIndex, offsetBy: 9)].reversed().withUnsafeBytes { $0.bindMemory(to: Double.self).baseAddress!.pointee }
// swiftlint:enable force_unwrapping
if double.isNaN {
if double.isSignalingNaN {
result = (.signalingNaN, 9)
} else {
result = (.nan, 9)
}
} else if double.isInfinite {
if double.sign == .minus {
result = (-.infinity, 9)
} else {
result = (.infinity, 9)
}
} else if let value = T(exactly: double) {
result = (value, 9)
} else {
throw CBOR.DecodingError.dataCorrupted(description: "Decoded number <\(double)> does not fit in \(type).")
}
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
return result
}
private class func decode<T>(_ type: T.Type, from data: Data, knownMajorType: CBOR.MajorType = .unsigned) throws -> (value: T, decodedBytes: Int) where T: UnsignedInteger & FixedWidthInteger {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == knownMajorType else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let additionalInfo = CBOR.additionalInfo(for: data[data.startIndex])
let result: (value: T?, decodedBytes: Int)
if additionalInfo <= 23 {
result = (T(exactly: additionalInfo), 1)
} else if additionalInfo == 24 {
if data.count >= 2 {
result = (T(exactly: data[data.index(data.startIndex, offsetBy: 1)]), 2)
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else if additionalInfo == 25 {
if data.count >= 3 {
result = (T(exactly: UInt16(data[data.index(data.startIndex, offsetBy: 1)]) << 8 |
UInt16(data[data.index(data.startIndex, offsetBy: 2)])), 3)
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else if additionalInfo == 26 {
if data.count >= 5 {
let upper = UInt32(data[data.index(data.startIndex, offsetBy: 1)]) << 24 |
UInt32(data[data.index(data.startIndex, offsetBy: 2)]) << 16
let lower = UInt32(data[data.index(data.startIndex, offsetBy: 3)]) << 8 |
UInt32(data[data.index(data.startIndex, offsetBy: 4)])
result = (T(exactly: upper | lower), 5)
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else if additionalInfo == 27 {
if data.count >= 9 {
let upper: UInt64, lower: UInt64
do {
let upper1 = UInt64(data[data.index(data.startIndex, offsetBy: 1)]) << 56 |
UInt64(data[data.index(data.startIndex, offsetBy: 2)]) << 48
let upper2 = UInt64(data[data.index(data.startIndex, offsetBy: 3)]) << 40 |
UInt64(data[data.index(data.startIndex, offsetBy: 4)]) << 32
upper = upper1 | upper2
}
do {
let lower1 = UInt64(data[data.index(data.startIndex, offsetBy: 5)]) << 24 |
UInt64(data[data.index(data.startIndex, offsetBy: 6)]) << 16
let lower2 = UInt64(data[data.index(data.startIndex, offsetBy: 7)]) << 8 |
UInt64(data[data.index(data.startIndex, offsetBy: 8)])
lower = lower1 | lower2
}
result = (T(exactly: upper | lower), 9)
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
} else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
guard let value = result.value else {
throw CBOR.DecodingError.dataCorrupted(description: "Decoded number does not fit in \(type).")
}
return (value, result.decodedBytes)
}
// swiftlint:enable function_body_length
private class func decode<T>(_ type: T.Type, from data: Data) throws -> (value: T, decodedBytes: Int) where T: SignedInteger & FixedWidthInteger {
guard !data.isEmpty else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
let majorType = CBOR.majorType(for: data[data.startIndex])
guard majorType == .negative else {
throw CBOR.DecodingError.typeMismatch(expected: [type], actual: try self.type(for: data))
}
let result: (value: T?, decodedBytes: Int)
do {
let unsigned = try decode(UInt64.self, from: data, knownMajorType: .negative)
result = (T(exactly: unsigned.value), unsigned.decodedBytes)
} catch CBOR.DecodingError.insufficientEncodedBytes {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: type)
}
guard let value = result.value else {
let error: CBOR.DecodingError
if T.bitWidth == 64 {
error = CBOR.DecodingError.dataCorrupted(description: "Decoded number does not fit in \(type). Try using \(CBOR.NegativeUInt64.self) instead")
} else {
error = CBOR.DecodingError.dataCorrupted(description: "Decoded number does not fit in \(type).")
}
throw error
}
return (value == .max ? .min : (-1 - value), result.decodedBytes)
}
// swiftlint:disable function_body_length
private class func decode<I1, I2>(_: CBOR.DecimalFraction<I1, I2>.Type, from data: Data) throws -> (value: [Any], decodedBytes: Int) where I1: FixedWidthInteger, I2: FixedWidthInteger {
guard data.count >= 3 else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: Array<Any>.self)
}
guard CBOR.majorType(for: data[data.startIndex]) == .array else {
throw CBOR.DecodingError.typeMismatch(expected: [Array<Any>.self], actual: try self.type(for: data))
}
guard CBOR.additionalInfo(for: data[data.startIndex]) == 2 else {
throw CBOR.DecodingError.dataCorrupted(description: "Expected to decode array containing exactly two elements, found array containing \((try? decode(UInt64.self, from: data, knownMajorType: .array))?.value ?? 0) elements")
}
var result: (value: [Any], decodedBytes: Int) = ([CBOR.Tag.decimalFraction], 1)
var majorType = CBOR.majorType(for: data[data.index(after: data.startIndex)])
switch majorType {
case .unsigned:
let unsigned = try decode(UInt64.self, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(unsigned.value)
result.decodedBytes += unsigned.decodedBytes
case .negative:
do {
let signed = try decode(Int64.self, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(signed.value)
result.decodedBytes += signed.decodedBytes
} catch let int64Error {
do {
let signed = try decode(CBOR.NegativeUInt64.self, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(signed.value)
result.decodedBytes += signed.decodedBytes
} catch {
throw int64Error
}
}
default:
throw CBOR.DecodingError.typeMismatch(expected: [UInt64.self, Int64.self], actual: try self.type(for: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...])))
}
guard data.count > result.decodedBytes else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: Array<Any>.self)
}
majorType = CBOR.majorType(for: data[data.index(data.startIndex, offsetBy: result.decodedBytes)])
switch majorType {
case .unsigned:
let unsigned = try decode(UInt64.self, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(unsigned.value)
result.decodedBytes += unsigned.decodedBytes
case .negative:
do {
let signed = try decode(Int64.self, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(signed.value)
result.decodedBytes += signed.decodedBytes
} catch let int64Error {
do {
let signed = try decode(CBOR.NegativeUInt64.self, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(signed.value)
result.decodedBytes += signed.decodedBytes
} catch {
throw int64Error
}
}
case .tag:
guard let tag = CBOR.Tag(bits: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...])) else {
throw CBOR.DecodingError.dataCorrupted(description: "Invalid CBOR tag")
}
switch tag {
case .positiveBignum, .negativeBignum:
guard data.count > result.decodedBytes + tag.bits.count else {
throw CBOR.DecodingError.insufficientEncodedBytes(expected: Array<Any>.self)
}
result.decodedBytes += tag.bits.count
let bignum = try decode(CBOR.Bignum.self, tag: tag, from: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...]))
result.value.append(bignum.value)
result.decodedBytes += bignum.decodedBytes
default:
throw CBOR.DecodingError.typeMismatch(expected: [UInt64.self, Int64.self, CBOR.Bignum.self], actual: try self.type(for: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...])))
}
default:
throw CBOR.DecodingError.typeMismatch(expected: [UInt64.self, Int64.self, CBOR.Bignum.self], actual: try self.type(for: Data(data[data.index(data.startIndex, offsetBy: result.decodedBytes)...])))
}
return result
}
// swiftlint:enable function_body_length
private class func decode<I1, I2>(_: CBOR.Bigfloat<I1, I2>.Type, from data: Data) throws -> (value: [Any], decodedBytes: Int) where I1: FixedWidthInteger, I2: FixedWidthInteger {
var result = try decode(CBOR.DecimalFraction<I1, I2>.self, from: data)
result.value[0] = CBOR.Tag.bigfloat
return result
}
// MARK: Unit Testing
#if DEBUG
// The only method that the consumer of CBORParser should be able to call is
// `parse(_:)` but we'd still like to be able to unit test the private method.
// These proxies will allow us to directly test edge cases inside of the private
// methods without exposing the private methods to any consumer of the class
internal class func testDecode(_ type: String.Type, from data: Data) throws -> (value: CBORDecodedString, decodedBytes: Int) {
return try decode(type, from: data)
}
internal class func testDecode(_ type: Data.Type, from data: Data) throws -> (value: CBORDecodedData, decodedBytes: Int) {
return try decode(type, from: data)
}
internal class func testDecode(_ type: Date.Type, tag: CBOR.Tag, from data: Data) throws -> (value: Date, decodedBytes: Int) {
return try decode(type, tag: tag, from: data)
}
internal class func testDecode(_ type: URL.Type, from data: Data) throws -> (value: URL, decodedBytes: Int) {
return try decode(type, from: data)
}
internal class func testDecode(_ type: CBOR.NegativeUInt64.Type, from data: Data) throws -> (value: CBOR.NegativeUInt64, decodedBytes: Int) {
return try decode(type, from: data)
}
internal class func testDecode(_ type: CBOR.SimpleValue.Type, from data: Data) throws -> (value: CBOR.SimpleValue, decodedBytes: Int) {
return try decode(type, from: data)
}
internal class func testDecode(_ type: CBOR.Bignum.Type, tag: CBOR.Tag, from data: Data) throws -> (value: CBOR.Bignum, decodedBytes: Int) {
return try decode(type, tag: tag, from: data)
}
internal class func testDecode<T>(_ type: T.Type, from data: Data) throws -> (value: T, decodedBytes: Int) where T: BinaryFloatingPoint, T.RawExponent: FixedWidthInteger, T.RawSignificand: FixedWidthInteger {
return try decode(type, from: data)
}
internal class func testDecode<T>(_ type: T.Type, from data: Data, knownMajorType: CBOR.MajorType = .unsigned) throws -> (value: T, decodedBytes: Int) where T: UnsignedInteger & FixedWidthInteger {
return try decode(type, from: data, knownMajorType: knownMajorType)
}
internal class func testDecode<T>(_ type: T.Type, from data: Data) throws -> (value: T, decodedBytes: Int) where T: SignedInteger & FixedWidthInteger {
return try decode(type, from: data)
}
internal class func testDecode<I1, I2>(_ type: CBOR.DecimalFraction<I1, I2>.Type, from data: Data) throws -> (value: [Any], decodedBytes: Int) where I1: FixedWidthInteger, I2: FixedWidthInteger {
return try decode(type, from: data)
}
internal class func testDecode<I1, I2>(_ type: CBOR.Bigfloat<I1, I2>.Type, from data: Data) throws -> (value: [Any], decodedBytes: Int) where I1: FixedWidthInteger, I2: FixedWidthInteger {
return try decode(type, from: data)
}
internal class func testCreateCodingKey(from value: Any) throws -> Swift.CodingKey {
var storage = Storage()
try storage.startKeyedContainer()
try storage.append(value) // Key
try storage.append(value) // Value
try storage.endCurrentContainer()
// swiftlint:disable force_cast force_unwrapping
let dictionary = try storage.finalize()! as! CodingKeyDictionary<Any>
// swiftlint:enable force_cast force_unwrapping