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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
//! additional DAG-CBOR codec tests ported from atmos (Go implementation).
//!
//! focuses on spec compliance, edge cases, and error paths not covered
//! by the inline tests in cbor.zig.
const std = @import("std");
const cbor = @import("cbor.zig");
const Value = cbor.Value;
const Cid = cbor.Cid;
// === non-minimal encoding rejection ===
//
// DAG-CBOR requires shortest-form encoding. values that fit in a smaller
// representation must not be encoded with a larger one.
test "reject non-minimal unsigned: 0 encoded as 1-byte" {
// 0x18 0x00 = unsigned(0) with 1-byte additional, but 0 fits in additional field directly
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x18, 0x00 }));
}
test "reject non-minimal unsigned: 23 encoded as 1-byte" {
// 0x18 0x17 = unsigned(23) with 1-byte additional, but 23 fits in additional field
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x18, 0x17 }));
}
test "reject non-minimal unsigned: 255 encoded as 2-byte" {
// 0x19 0x00 0xff = unsigned(255) with 2-byte additional, but fits in 1-byte
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x19, 0x00, 0xff }));
}
test "reject non-minimal unsigned: 256 encoded as 4-byte" {
// 0x1a 0x00 0x00 0x01 0x00 = unsigned(256) with 4-byte additional, but fits in 2-byte
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x1a, 0x00, 0x00, 0x01, 0x00 }));
}
test "reject non-minimal unsigned: 65535 encoded as 4-byte" {
// 0x1a 0x00 0x00 0xff 0xff = unsigned(65535) with 4-byte, but fits in 2-byte
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x1a, 0x00, 0x00, 0xff, 0xff }));
}
test "reject non-minimal unsigned: 1 encoded as 8-byte" {
// 0x1b 0x00..0x01 = unsigned(1) with 8-byte additional
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }));
}
test "reject non-minimal negative: -1 encoded as 1-byte" {
// 0x38 0x00 = negative(-1) with 1-byte additional, but -1 fits in additional field (0x20)
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x38, 0x00 }));
}
test "reject non-minimal negative: -24 encoded as 1-byte" {
// 0x38 0x17 = negative(-24) with 1-byte additional, but fits in additional field (0x37)
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x38, 0x17 }));
}
test "reject non-minimal text string length: empty string as 1-byte length" {
// 0x78 0x00 = text(0) with 1-byte length, but 0 fits in additional field (0x60)
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x78, 0x00 }));
}
test "reject non-minimal byte string length" {
// 0x58 0x00 = bytes(0) with 1-byte length, but 0 fits in additional field (0x40)
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x58, 0x00 }));
}
test "reject non-minimal array length" {
// 0x98 0x00 = array(0) with 1-byte length, but 0 fits in additional field (0x80)
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0x98, 0x00 }));
}
test "reject non-minimal map length" {
// 0xb8 0x00 = map(0) with 1-byte length, but 0 fits in additional field (0xa0)
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.NonMinimalEncoding, cbor.decode(arena.allocator(), &.{ 0xb8, 0x00 }));
}
// === trailing bytes rejection ===
test "decodeAll rejects trailing bytes" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// integer 1 followed by extra byte 0x02
try std.testing.expectError(error.TrailingBytes, cbor.decodeAll(arena.allocator(), &.{ 0x01, 0x02 }));
}
// === tag restriction ===
//
// DAG-CBOR only allows tag 42 (CID links). all other tags must be rejected.
test "reject tag 0 (date/time)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xc0 0x60 = tag(0) wrapping empty text string
try std.testing.expectError(error.UnsupportedTag, cbor.decode(arena.allocator(), &.{ 0xc0, 0x60 }));
}
test "reject tag 1 (epoch time)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xc1 0x01 = tag(1) wrapping integer 1
try std.testing.expectError(error.UnsupportedTag, cbor.decode(arena.allocator(), &.{ 0xc1, 0x01 }));
}
test "reject tag 2 (positive bignum)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xc2 0x41 0x01 = tag(2) wrapping byte string [0x01]
try std.testing.expectError(error.UnsupportedTag, cbor.decode(arena.allocator(), &.{ 0xc2, 0x41, 0x01 }));
}
test "reject tag 3 (negative bignum)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnsupportedTag, cbor.decode(arena.allocator(), &.{ 0xc3, 0x41, 0x01 }));
}
test "reject tag 55799 (self-describe CBOR)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xd9 0xd9 0xf7 0x01 = tag(55799) wrapping integer 1
try std.testing.expectError(error.UnsupportedTag, cbor.decode(arena.allocator(), &.{ 0xd9, 0xd9, 0xf7, 0x01 }));
}
// === map key ordering validation ===
//
// DAG-CBOR requires map keys sorted by byte length (shorter first),
// then lexicographically.
test "reject unsorted map keys: wrong lexicographic order" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// {"b": 1, "a": 2} — same length, wrong lex order
try std.testing.expectError(error.UnsortedMapKeys, cbor.decode(arena.allocator(), &.{
0xa2, // map(2)
0x61, 'b', 0x01, // "b": 1
0x61, 'a', 0x02, // "a": 2 (should come before "b")
}));
}
test "reject unsorted map keys: longer key before shorter" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// {"bb": 1, "a": 2} — 2-char key before 1-char key
try std.testing.expectError(error.UnsortedMapKeys, cbor.decode(arena.allocator(), &.{
0xa2, // map(2)
0x62, 'b', 'b', 0x01, // "bb": 1
0x61, 'a', 0x02, // "a": 2 (shorter, should come first)
}));
}
test "accept correctly sorted map keys" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// {"a": 1, "b": 2, "cc": 3} — correct order: short first, then lex
const result = try cbor.decode(arena.allocator(), &.{
0xa3, // map(3)
0x61, 'a', 0x01, // "a": 1
0x61, 'b', 0x02, // "b": 2
0x62, 'c', 'c', 0x03, // "cc": 3
});
try std.testing.expectEqual(@as(u64, 1), result.value.get("a").?.unsigned);
try std.testing.expectEqual(@as(u64, 2), result.value.get("b").?.unsigned);
try std.testing.expectEqual(@as(u64, 3), result.value.get("cc").?.unsigned);
}
// === duplicate map key rejection ===
test "reject duplicate map keys" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// {"a": 1, "a": 2} — duplicate key "a"
try std.testing.expectError(error.DuplicateMapKey, cbor.decode(arena.allocator(), &.{
0xa2, // map(2)
0x61, 'a', 0x01, // "a": 1
0x61, 'a', 0x02, // "a": 2 (duplicate!)
}));
}
// === float rejection (all variants) ===
test "reject float16" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnsupportedFloat, cbor.decode(arena.allocator(), &.{ 0xf9, 0x00, 0x00 }));
}
test "reject float32" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xfa 0x47 0xc3 0x50 0x00 = float32(100000.0)
try std.testing.expectError(error.UnsupportedFloat, cbor.decode(arena.allocator(), &.{ 0xfa, 0x47, 0xc3, 0x50, 0x00 }));
}
test "float64: finite round-trips, non-finite and narrow floats reject" {
// DAG-CBOR permits f64 only; the reference implementation (atmos
// cbor decoding.go/encoding.go) accepts finite values and rejects
// NaN, Infinity, float16, and float32. mirrored exactly.
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
// 0xfb + 8 bytes = float64(1.0) decodes
const one = try cbor.decode(a, &.{ 0xfb, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
try std.testing.expectEqual(@as(f64, 1.0), one.value.float);
// encode(1.5) produces the canonical 9-byte form
const bytes = try cbor.encodeAlloc(a, .{ .float = 1.5 });
try std.testing.expectEqualSlices(u8, &.{ 0xfb, 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, bytes);
const back = try cbor.decode(a, bytes);
try std.testing.expectEqual(@as(f64, 1.5), back.value.float);
// NaN and Infinity reject on both paths
const nan_bytes = [_]u8{ 0xfb, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
try std.testing.expectError(error.NonFiniteFloat, cbor.decode(a, &nan_bytes));
const inf_bytes = [_]u8{ 0xfb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
try std.testing.expectError(error.NonFiniteFloat, cbor.decode(a, &inf_bytes));
// float16 / float32 stay rejected
try std.testing.expectError(error.UnsupportedFloat, cbor.decode(a, &.{ 0xf9, 0x3c, 0x00 }));
try std.testing.expectError(error.UnsupportedFloat, cbor.decode(a, &.{ 0xfa, 0x3f, 0x80, 0x00, 0x00 }));
}
// === simple values rejection ===
test "reject undefined (0xf7)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnsupportedSimpleValue, cbor.decode(arena.allocator(), &.{0xf7}));
}
test "reject simple value 0" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xf8 0x00 = simple(0) — only false/true/null allowed
try std.testing.expectError(error.UnsupportedSimpleValue, cbor.decode(arena.allocator(), &.{ 0xf8, 0x00 }));
}
test "reject simple value 32" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnsupportedSimpleValue, cbor.decode(arena.allocator(), &.{ 0xf8, 0x20 }));
}
test "reject simple value 255" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnsupportedSimpleValue, cbor.decode(arena.allocator(), &.{ 0xf8, 0xff }));
}
// === indefinite-length rejection (all types) ===
test "reject indefinite-length byte string (0x5f)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.IndefiniteLength, cbor.decode(arena.allocator(), &.{0x5f}));
}
test "reject indefinite-length text string (0x7f)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.IndefiniteLength, cbor.decode(arena.allocator(), &.{0x7f}));
}
test "reject indefinite-length array (0x9f)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.IndefiniteLength, cbor.decode(arena.allocator(), &.{0x9f}));
}
test "reject indefinite-length map (0xbf)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.IndefiniteLength, cbor.decode(arena.allocator(), &.{0xbf}));
}
test "reject break stop code (0xff)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.IndefiniteLength, cbor.decode(arena.allocator(), &.{0xff}));
}
// === reserved additional info (28, 29, 30) for all major types ===
test "reject reserved additional info for unsigned" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// additional 28 = 0x1c, 29 = 0x1d, 30 = 0x1e
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x1c}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x1d}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x1e}));
}
test "reject reserved additional info for negative" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x3c}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x3d}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x3e}));
}
test "reject reserved additional info for byte string" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x5c}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x5d}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x5e}));
}
test "reject reserved additional info for text string" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x7c}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x7d}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x7e}));
}
test "reject reserved additional info for array" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x9c}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x9d}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0x9e}));
}
test "reject reserved additional info for map" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0xbc}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0xbd}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0xbe}));
}
test "reject reserved additional info for tag" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0xdc}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0xdd}));
try std.testing.expectError(error.ReservedAdditionalInfo, cbor.decode(arena.allocator(), &.{0xde}));
}
// === integer boundary encode/decode ===
test "integer boundary: 255 (max 1-byte)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// 0x18 0xff = unsigned(255)
try std.testing.expectEqual(@as(u64, 255), (try cbor.decode(alloc, &.{ 0x18, 0xff })).value.unsigned);
// round-trip
const encoded = try cbor.encodeAlloc(alloc, .{ .unsigned = 255 });
try std.testing.expectEqualSlices(u8, &.{ 0x18, 0xff }, encoded);
}
test "integer boundary: 256 (min 2-byte)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// 0x19 0x01 0x00 = unsigned(256)
try std.testing.expectEqual(@as(u64, 256), (try cbor.decode(alloc, &.{ 0x19, 0x01, 0x00 })).value.unsigned);
const encoded = try cbor.encodeAlloc(alloc, .{ .unsigned = 256 });
try std.testing.expectEqualSlices(u8, &.{ 0x19, 0x01, 0x00 }, encoded);
}
test "integer boundary: 65535 (max 2-byte)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
try std.testing.expectEqual(@as(u64, 65535), (try cbor.decode(alloc, &.{ 0x19, 0xff, 0xff })).value.unsigned);
const encoded = try cbor.encodeAlloc(alloc, .{ .unsigned = 65535 });
try std.testing.expectEqualSlices(u8, &.{ 0x19, 0xff, 0xff }, encoded);
}
test "integer boundary: 65536 (min 4-byte)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
try std.testing.expectEqual(@as(u64, 65536), (try cbor.decode(alloc, &.{ 0x1a, 0x00, 0x01, 0x00, 0x00 })).value.unsigned);
const encoded = try cbor.encodeAlloc(alloc, .{ .unsigned = 65536 });
try std.testing.expectEqualSlices(u8, &.{ 0x1a, 0x00, 0x01, 0x00, 0x00 }, encoded);
}
test "integer boundary: 0xffffffff (max 4-byte)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
try std.testing.expectEqual(@as(u64, 0xffffffff), (try cbor.decode(alloc, &.{ 0x1a, 0xff, 0xff, 0xff, 0xff })).value.unsigned);
const encoded = try cbor.encodeAlloc(alloc, .{ .unsigned = 0xffffffff });
try std.testing.expectEqualSlices(u8, &.{ 0x1a, 0xff, 0xff, 0xff, 0xff }, encoded);
}
test "integer boundary: 0x100000000 (min 8-byte)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
try std.testing.expectEqual(@as(u64, 0x100000000), (try cbor.decode(alloc, &.{ 0x1b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 })).value.unsigned);
const encoded = try cbor.encodeAlloc(alloc, .{ .unsigned = 0x100000000 });
try std.testing.expectEqualSlices(u8, &.{ 0x1b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 }, encoded);
}
test "integer boundary: max u64" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const max_u64: u64 = std.math.maxInt(u64);
try std.testing.expectEqual(max_u64, (try cbor.decode(alloc, &.{ 0x1b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff })).value.unsigned);
}
// === negative integer boundary tests ===
test "negative boundary: -24 (max inline)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// -24 = major 1, additional 23 → 0x37
try std.testing.expectEqual(@as(i64, -24), (try cbor.decode(alloc, &.{0x37})).value.negative);
const encoded = try cbor.encodeAlloc(alloc, .{ .negative = -24 });
try std.testing.expectEqualSlices(u8, &.{0x37}, encoded);
}
test "negative boundary: -25 (min 1-byte additional)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// -25 = major 1, additional 24 → 0x38 0x18
try std.testing.expectEqual(@as(i64, -25), (try cbor.decode(alloc, &.{ 0x38, 0x18 })).value.negative);
const encoded = try cbor.encodeAlloc(alloc, .{ .negative = -25 });
try std.testing.expectEqualSlices(u8, &.{ 0x38, 0x18 }, encoded);
}
test "negative boundary: -256 (max 1-byte additional)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// -256 = -1 - 255 → 0x38 0xff
try std.testing.expectEqual(@as(i64, -256), (try cbor.decode(alloc, &.{ 0x38, 0xff })).value.negative);
const encoded = try cbor.encodeAlloc(alloc, .{ .negative = -256 });
try std.testing.expectEqualSlices(u8, &.{ 0x38, 0xff }, encoded);
}
test "negative boundary: -257 (min 2-byte additional)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// -257 = -1 - 256 → 0x39 0x01 0x00
try std.testing.expectEqual(@as(i64, -257), (try cbor.decode(alloc, &.{ 0x39, 0x01, 0x00 })).value.negative);
const encoded = try cbor.encodeAlloc(alloc, .{ .negative = -257 });
try std.testing.expectEqualSlices(u8, &.{ 0x39, 0x01, 0x00 }, encoded);
}
test "negative boundary: -65537 (min 4-byte additional)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// -65537 = -1 - 65536 → 0x3a 0x00 0x01 0x00 0x00
try std.testing.expectEqual(@as(i64, -65537), (try cbor.decode(alloc, &.{ 0x3a, 0x00, 0x01, 0x00, 0x00 })).value.negative);
const encoded = try cbor.encodeAlloc(alloc, .{ .negative = -65537 });
try std.testing.expectEqualSlices(u8, &.{ 0x3a, 0x00, 0x01, 0x00, 0x00 }, encoded);
}
test "negative boundary: min i64 (-2^63)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const min_i64: i64 = std.math.minInt(i64);
// -2^63 = -1 - (2^63 - 1) → 0x3b 0x7f 0xff 0xff 0xff 0xff 0xff 0xff 0xff
try std.testing.expectEqual(min_i64, (try cbor.decode(alloc, &.{ 0x3b, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff })).value.negative);
}
// === negative integer overflow ===
test "reject negative integer overflow: -(2^63 + 1)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x3b 0x80 0x00 ... 0x00 = -1 - 2^63 = -(2^63 + 1), overflows i64
try std.testing.expectError(error.Overflow, cbor.decode(arena.allocator(), &.{ 0x3b, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }));
}
test "reject negative integer overflow: -(2^64)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x3b 0xff ... 0xff = -1 - (2^64 - 1) = -2^64, overflows i64
try std.testing.expectError(error.Overflow, cbor.decode(arena.allocator(), &.{ 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }));
}
// === truncated data handling ===
test "reject empty input" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{}));
}
test "reject truncated 1-byte unsigned header" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x18 needs 1 more byte
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{0x18}));
}
test "reject truncated 2-byte unsigned header" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x19 needs 2 more bytes
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{0x19}));
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{ 0x19, 0x01 }));
}
test "reject truncated 4-byte unsigned header" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{0x1a}));
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{ 0x1a, 0x00, 0x00 }));
}
test "reject truncated 8-byte unsigned header" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{0x1b}));
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{ 0x1b, 0x00, 0x00, 0x00, 0x00 }));
}
test "reject truncated text string payload" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x65 = text(5) but only 3 bytes follow
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{ 0x65, 'h', 'e', 'l' }));
}
test "reject truncated byte string payload" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x44 = bytes(4) but only 2 bytes follow
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{ 0x44, 0x01, 0x02 }));
}
test "reject truncated array elements" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x83 = array(3) but only 2 elements
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{ 0x83, 0x01, 0x02 }));
}
test "reject truncated map entries" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0xa2 = map(2) but only 1 entry
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{
0xa2,
0x61,
'a',
0x01,
}));
}
// === string/bytes at encoding boundaries ===
test "text string at encoding boundaries" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// 23-byte string (max inline length)
const s23 = "12345678901234567890123";
const encoded23 = try cbor.encodeAlloc(alloc, .{ .text = s23 });
try std.testing.expectEqual(@as(u8, 0x77), encoded23[0]); // 0x60 + 23
const decoded23 = try cbor.decodeAll(alloc, encoded23);
try std.testing.expectEqualStrings(s23, decoded23.text);
// 24-byte string (first to use 1-byte length)
const s24 = "123456789012345678901234";
const encoded24 = try cbor.encodeAlloc(alloc, .{ .text = s24 });
try std.testing.expectEqual(@as(u8, 0x78), encoded24[0]); // text + 1-byte length
try std.testing.expectEqual(@as(u8, 24), encoded24[1]);
const decoded24 = try cbor.decodeAll(alloc, encoded24);
try std.testing.expectEqualStrings(s24, decoded24.text);
}
test "byte string at encoding boundaries" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// 23-byte bytes (max inline length)
const b23 = &@as([23]u8, @splat(0xaa));
const encoded23 = try cbor.encodeAlloc(alloc, .{ .bytes = b23 });
try std.testing.expectEqual(@as(u8, 0x57), encoded23[0]); // 0x40 + 23
const decoded23 = try cbor.decodeAll(alloc, encoded23);
try std.testing.expectEqualSlices(u8, b23, decoded23.bytes);
// 24-byte bytes (first to use 1-byte length)
const b24 = &@as([24]u8, @splat(0xbb));
const encoded24 = try cbor.encodeAlloc(alloc, .{ .bytes = b24 });
try std.testing.expectEqual(@as(u8, 0x58), encoded24[0]); // bytes + 1-byte length
try std.testing.expectEqual(@as(u8, 24), encoded24[1]);
const decoded24 = try cbor.decodeAll(alloc, encoded24);
try std.testing.expectEqualSlices(u8, b24, decoded24.bytes);
}
// === CID edge cases ===
test "reject tag 42 wrapping non-bytes" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// tag(42) + text string "hello" instead of byte string
try std.testing.expectError(error.InvalidCid, cbor.decode(arena.allocator(), &.{
0xd8, 0x2a, // tag(42)
0x65, 'h', 'e', 'l', 'l', 'o', // text "hello" (should be bytes)
}));
}
test "reject tag 42 with empty bytes" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// tag(42) + empty byte string (missing 0x00 prefix)
try std.testing.expectError(error.InvalidCid, cbor.decode(arena.allocator(), &.{
0xd8, 0x2a, // tag(42)
0x40, // bytes(0) — empty, no 0x00 prefix
}));
}
test "reject tag 42 with wrong prefix" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// tag(42) + byte string with 0x01 prefix instead of 0x00
try std.testing.expectError(error.InvalidCid, cbor.decode(arena.allocator(), &.{
0xd8, 0x2a, // tag(42)
0x42, 0x01, 0xaa, // bytes [0x01, 0xaa] — wrong prefix
}));
}
// === complex nested round-trips ===
test "round-trip: mixed array with all types" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// [42, -7, "hello", true, false, null, [1, 2], {"k": 0}]
const original: Value = .{ .array = &.{
.{ .unsigned = 42 },
.{ .negative = -7 },
.{ .text = "hello" },
.{ .boolean = true },
.{ .boolean = false },
.null,
.{ .array = &.{ .{ .unsigned = 1 }, .{ .unsigned = 2 } } },
.{ .map = &.{.{ .key = "k", .value = .{ .unsigned = 0 } }} },
} };
const encoded = try cbor.encodeAlloc(alloc, original);
const decoded = try cbor.decodeAll(alloc, encoded);
const arr = decoded.array;
try std.testing.expectEqual(@as(usize, 8), arr.len);
try std.testing.expectEqual(@as(u64, 42), arr[0].unsigned);
try std.testing.expectEqual(@as(i64, -7), arr[1].negative);
try std.testing.expectEqualStrings("hello", arr[2].text);
try std.testing.expectEqual(true, arr[3].boolean);
try std.testing.expectEqual(false, arr[4].boolean);
try std.testing.expectEqual(Value.null, arr[5]);
try std.testing.expectEqual(@as(usize, 2), arr[6].array.len);
try std.testing.expectEqual(@as(u64, 0), arr[7].get("k").?.unsigned);
}
test "round-trip: deeply nested maps" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// {"a": {"b": {"c": {"d": 42}}}}
const original: Value = .{ .map = &.{
.{ .key = "a", .value = .{ .map = &.{
.{ .key = "b", .value = .{ .map = &.{
.{ .key = "c", .value = .{ .map = &.{
.{ .key = "d", .value = .{ .unsigned = 42 } },
} } },
} } },
} } },
} };
const encoded = try cbor.encodeAlloc(alloc, original);
const decoded = try cbor.decodeAll(alloc, encoded);
const d = decoded.get("a").?.get("b").?.get("c").?.get("d").?.unsigned;
try std.testing.expectEqual(@as(u64, 42), d);
}
test "round-trip: unicode text strings" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const cases = [_][]const u8{
"",
"a",
"IETF",
"\"\\\u{00fc}\u{6c34}",
"\xc3\xbc", // ü
"\xe6\xb0\xb4", // 水
"\xf0\x9f\x98\x80", // 😀
"\xf0\x9f\x91\xa8\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7\xe2\x80\x8d\xf0\x9f\x91\xa7", // family ZWJ emoji
};
for (cases) |text| {
const encoded = try cbor.encodeAlloc(alloc, .{ .text = text });
const decoded = try cbor.decodeAll(alloc, encoded);
try std.testing.expectEqualStrings(text, decoded.text);
}
}
test "round-trip: empty containers" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// empty array
const empty_arr = try cbor.encodeAlloc(alloc, .{ .array = &.{} });
try std.testing.expectEqualSlices(u8, &.{0x80}, empty_arr);
const decoded_arr = try cbor.decodeAll(alloc, empty_arr);
try std.testing.expectEqual(@as(usize, 0), decoded_arr.array.len);
// empty map
const empty_map = try cbor.encodeAlloc(alloc, .{ .map = &.{} });
try std.testing.expectEqualSlices(u8, &.{0xa0}, empty_map);
const decoded_map = try cbor.decodeAll(alloc, empty_map);
try std.testing.expectEqual(@as(usize, 0), decoded_map.map.len);
}
test "round-trip: map with empty key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const original: Value = .{ .map = &.{
.{ .key = "", .value = .{ .unsigned = 1 } },
.{ .key = "a", .value = .{ .unsigned = 2 } },
} };
const encoded = try cbor.encodeAlloc(alloc, original);
const decoded = try cbor.decodeAll(alloc, encoded);
// empty key should sort first (shorter)
try std.testing.expectEqualStrings("", decoded.map[0].key);
try std.testing.expectEqualStrings("a", decoded.map[1].key);
try std.testing.expectEqual(@as(u64, 1), decoded.get("").?.unsigned);
try std.testing.expectEqual(@as(u64, 2), decoded.get("a").?.unsigned);
}
// === byte-identical re-encoding ===
test "canonical re-encoding: encode then decode then re-encode is identical" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// build a non-trivially-ordered map
const original: Value = .{ .map = &.{
.{ .key = "z", .value = .{ .unsigned = 26 } },
.{ .key = "a", .value = .{ .text = "first" } },
.{ .key = "mm", .value = .{ .array = &.{
.{ .boolean = true },
.null,
.{ .negative = -100 },
} } },
} };
const first_encode = try cbor.encodeAlloc(alloc, original);
const decoded = try cbor.decodeAll(alloc, first_encode);
const second_encode = try cbor.encodeAlloc(alloc, decoded);
try std.testing.expectEqualSlices(u8, first_encode, second_encode);
}
test "deterministic encoding: 10 iterations produce identical bytes" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const value: Value = .{ .map = &.{
.{ .key = "type", .value = .{ .text = "app.bsky.feed.post" } },
.{ .key = "text", .value = .{ .text = "Hello, world!" } },
.{ .key = "createdAt", .value = .{ .text = "2024-01-01T00:00:00Z" } },
.{ .key = "langs", .value = .{ .array = &.{.{ .text = "en" }} } },
} };
const first = try cbor.encodeAlloc(alloc, value);
for (0..10) |_| {
const again = try cbor.encodeAlloc(alloc, value);
try std.testing.expectEqualSlices(u8, first, again);
}
}
// === single-byte exhaustive scan ===
//
// every possible single-byte CBOR input should either decode or return
// a well-defined error — never panic or trigger undefined behavior.
test "single-byte exhaustive: no panics on any byte value" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
var byte: u16 = 0;
while (byte <= 255) : (byte += 1) {
const data = [_]u8{@intCast(byte)};
_ = cbor.decode(alloc, &data) catch continue;
}
}
// === non-string map key rejection ===
test "reject integer map key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// map(1) with integer key: {1: 2}
try std.testing.expectError(error.InvalidMapKey, cbor.decode(arena.allocator(), &.{
0xa1, // map(1)
0x01, // key: integer 1 (not text!)
0x02, // value: 2
}));
}
test "reject bytes map key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// map(1) with byte string key
try std.testing.expectError(error.InvalidMapKey, cbor.decode(arena.allocator(), &.{
0xa1, // map(1)
0x41, 0x01, // key: bytes [0x01] (not text!)
0x02, // value: 2
}));
}
test "reject array map key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.InvalidMapKey, cbor.decode(arena.allocator(), &.{
0xa1, // map(1)
0x80, // key: empty array (not text!)
0x02, // value: 2
}));
}
test "reject boolean map key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expectError(error.InvalidMapKey, cbor.decode(arena.allocator(), &.{
0xa1, // map(1)
0xf5, // key: true (not text!)
0x02, // value: 2
}));
}
// === map key ordering: comprehensive DAG-CBOR rules ===
test "map key ordering: length takes priority over lexicographic" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// "z" (1 byte) must come before "aa" (2 bytes), even though "aa" < "z" lexicographically
const original: Value = .{ .map = &.{
.{ .key = "aa", .value = .{ .unsigned = 2 } },
.{ .key = "z", .value = .{ .unsigned = 1 } },
} };
const encoded = try cbor.encodeAlloc(alloc, original);
const decoded = try cbor.decodeAll(alloc, encoded);
try std.testing.expectEqualStrings("z", decoded.map[0].key);
try std.testing.expectEqualStrings("aa", decoded.map[1].key);
}
test "map key ordering: empty key sorts first" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const original: Value = .{ .map = &.{
.{ .key = "a", .value = .{ .unsigned = 2 } },
.{ .key = "", .value = .{ .unsigned = 1 } },
.{ .key = "bb", .value = .{ .unsigned = 3 } },
} };
const encoded = try cbor.encodeAlloc(alloc, original);
const decoded = try cbor.decodeAll(alloc, encoded);
try std.testing.expectEqualStrings("", decoded.map[0].key);
try std.testing.expectEqualStrings("a", decoded.map[1].key);
try std.testing.expectEqualStrings("bb", decoded.map[2].key);
}
// === UTF-8 validation ===
//
// CBOR text strings (major type 3) must contain valid UTF-8.
// DAG-CBOR inherits this requirement.
test "reject invalid UTF-8 in text string: 0xff byte" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// text(1) containing 0xff — not valid UTF-8
try std.testing.expectError(error.InvalidUtf8, cbor.decode(arena.allocator(), &.{ 0x61, 0xff }));
}
test "reject invalid UTF-8 in text string: truncated multi-byte sequence" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// text(1) containing 0xc3 — start of 2-byte sequence but missing continuation
try std.testing.expectError(error.InvalidUtf8, cbor.decode(arena.allocator(), &.{ 0x61, 0xc3 }));
}
test "reject invalid UTF-8 in text string: lone continuation byte" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// text(1) containing 0x80 — continuation byte without start
try std.testing.expectError(error.InvalidUtf8, cbor.decode(arena.allocator(), &.{ 0x61, 0x80 }));
}
test "reject invalid UTF-8 in text string: surrogate half (U+D800)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// text(3) containing ED A0 80 — UTF-8 encoding of U+D800 (surrogate)
try std.testing.expectError(error.InvalidUtf8, cbor.decode(arena.allocator(), &.{ 0x63, 0xed, 0xa0, 0x80 }));
}
test "reject invalid UTF-8 in text string: overlong encoding" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// text(2) containing C0 80 — overlong encoding of U+0000
try std.testing.expectError(error.InvalidUtf8, cbor.decode(arena.allocator(), &.{ 0x62, 0xc0, 0x80 }));
}
test "reject invalid UTF-8 in map key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// map(1) with key containing invalid UTF-8
try std.testing.expectError(error.InvalidUtf8, cbor.decode(arena.allocator(), &.{
0xa1, // map(1)
0x61, 0xff, // key: text(1) with 0xff — invalid UTF-8
0x01, // value: 1
}));
}
test "accept valid UTF-8 text: café" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// "café" = 63 61 66 c3 a9 — valid UTF-8
const result = try cbor.decode(arena.allocator(), &.{ 0x65, 'c', 'a', 'f', 0xc3, 0xa9 });
try std.testing.expectEqualStrings("caf\xc3\xa9", result.value.text);
}
test "accept valid UTF-8 text: CJK and emoji" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// encode and decode a string with multi-byte characters
const text = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xf0\x9f\x98\x80"; // 日本語😀
const encoded = try cbor.encodeAlloc(alloc, .{ .text = text });
const decoded = try cbor.decodeAll(alloc, encoded);
try std.testing.expectEqualStrings(text, decoded.text);
}
// === nesting depth limit ===
test "accept nesting at max_depth - 1" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// build array(1) nested max_depth - 1 times, with 0 at the bottom
var buf: [cbor.max_depth + 1]u8 = undefined;
for (0..cbor.max_depth - 1) |i| {
buf[i] = 0x81; // array(1)
}
buf[cbor.max_depth - 1] = 0x00; // integer 0 at the bottom
const result = try cbor.decodeAll(arena.allocator(), buf[0..cbor.max_depth]);
// verify outermost is an array
try std.testing.expectEqual(@as(usize, 1), result.array.len);
}
test "reject nesting beyond max_depth" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// build array(1) nested max_depth + 1 times
var buf: [cbor.max_depth + 2]u8 = undefined;
for (0..cbor.max_depth + 1) |i| {
buf[i] = 0x81; // array(1)
}
buf[cbor.max_depth + 1] = 0x00;
try std.testing.expectError(error.MaxDepthExceeded, cbor.decodeAll(arena.allocator(), buf[0 .. cbor.max_depth + 2]));
}
// === huge allocation rejection ===
//
// the decoder should reject claims for impossibly large collections
// without attempting to allocate.
test "reject huge array allocation claim" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// 0x9b + 8 bytes claiming 2^32 elements, but only a few bytes of data follow
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{
0x9b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, // array(2^32)
0x00, // just one byte of data
}));
}
test "reject huge map allocation claim" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// map claiming 2^32 entries with minimal data
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{
0xbb, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, // map(2^32)
0x61, 'a', 0x01, // one entry
}));
}
test "reject huge byte string claim" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// bytes claiming 2^32 length with minimal data
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{
0x5b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, // bytes(2^32)
0x00, // just one byte
}));
}
test "reject huge text string claim" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// text claiming 2^32 length with minimal data
try std.testing.expectError(error.UnexpectedEof, cbor.decode(arena.allocator(), &.{
0x7b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, // text(2^32)
0x00, // just one byte
}));
}
// === Cid method edge cases ===
test "Cid.version returns null for empty raw" {
const cid = Cid{ .raw = &.{} };
try std.testing.expect(cid.version() == null);
try std.testing.expect(cid.codec() == null);
try std.testing.expect(cid.hashFn() == null);
try std.testing.expect(cid.digest() == null);
}
test "Cid.version returns null for single byte" {
const cid = Cid{ .raw = &.{0x01} };
try std.testing.expect(cid.version() == null);
}
test "Cid.digest returns null for truncated CIDv0" {
// CIDv0 starts with 0x12 0x20 but needs 34 bytes total
const cid = Cid{ .raw = &.{ 0x12, 0x20, 0xaa, 0xbb } }; // only 4 bytes, need 34
try std.testing.expect(cid.version().? == 0); // version parses ok
try std.testing.expect(cid.digest() == null); // but digest is truncated
}
test "Cid.digest returns correct slice for valid CIDv1" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const cid = try Cid.forDagCbor(arena.allocator(), "test");
const d = cid.digest().?;
try std.testing.expectEqual(@as(usize, 32), d.len);
// verify it's actually SHA-256 of "test"
const Sha256 = std.crypto.hash.sha2.Sha256;
var expected: [32]u8 = undefined;
Sha256.hash("test", &expected, .{});
try std.testing.expectEqualSlices(u8, &expected, d);
}
// === readUvarint edge cases ===
test "readUvarint returns null on empty input" {
var pos: usize = 0;
try std.testing.expect(cbor.readUvarint(&.{}, &pos) == null);
}
test "readUvarint returns null on truncated continuation" {
// 0x80 = continuation bit set, needs more bytes
var pos: usize = 0;
try std.testing.expect(cbor.readUvarint(&.{0x80}, &pos) == null);
}
test "readUvarint decodes max single byte (127)" {
var pos: usize = 0;
try std.testing.expectEqual(@as(u64, 127), cbor.readUvarint(&.{0x7f}, &pos).?);
try std.testing.expectEqual(@as(usize, 1), pos);
}
test "readUvarint decodes multi-byte value" {
// 128 = 0x80 0x01
var pos: usize = 0;
try std.testing.expectEqual(@as(u64, 128), cbor.readUvarint(&.{ 0x80, 0x01 }, &pos).?);
try std.testing.expectEqual(@as(usize, 2), pos);
}
// === Value getter edge cases ===
test "getUint returns null for negative value" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const val: Value = .{ .map = &.{
.{ .key = "n", .value = .{ .negative = -5 } },
} };
// -5 can't be represented as u64
try std.testing.expect(val.getUint("n") == null);
}
test "getInt returns null for u64 > max i64" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const val: Value = .{ .map = &.{
.{ .key = "n", .value = .{ .unsigned = std.math.maxInt(u64) } },
} };
// max u64 can't be represented as i64
try std.testing.expect(val.getInt("n") == null);
}
test "getCid returns CID for cid value" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const cid = try Cid.forDagCbor(alloc, "data");
const val: Value = .{ .map = &.{
.{ .key = "link", .value = .{ .cid = cid } },
} };
const got = val.getCid("link").?;
try std.testing.expectEqualSlices(u8, cid.raw, got.raw);
}
test "getCid returns null for non-cid value" {
const val: Value = .{ .map = &.{
.{ .key = "x", .value = .{ .unsigned = 42 } },
} };
try std.testing.expect(val.getCid("x") == null);
}
test "get returns null for non-map value" {
const val: Value = .{ .unsigned = 42 };
try std.testing.expect(val.get("anything") == null);
try std.testing.expect(val.getString("anything") == null);
try std.testing.expect(val.getInt("anything") == null);
}
// === negative integer encode round-trip at min i64 ===
// === readUvarint 10th byte overflow rejection ===
test "readUvarint rejects 10th byte with value > 1" {
// 9 continuation bytes (0x80) + 10th byte with value 2 (bit 1 set, would overflow u64)
const data = @as([9]u8, @splat(0x80)) ++ [_]u8{0x02};
var pos: usize = 0;
try std.testing.expect(cbor.readUvarint(&data, &pos) == null);
}
test "readUvarint accepts 10th byte with value 1 (max u64)" {
// 9 continuation bytes (0xff = 0x7f data + continuation) + 10th byte 0x01
// This encodes 2^63 + (lower 63 bits all set) = max u64
const data = @as([9]u8, @splat(0xff)) ++ [_]u8{0x01};
var pos: usize = 0;
const val = cbor.readUvarint(&data, &pos);
try std.testing.expect(val != null);
try std.testing.expectEqual(std.math.maxInt(u64), val.?);
}
// === CID minimum size ===
test "reject tag 42 with only 0x00 prefix (empty CID)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// tag(42) + bytes([0x00]) — prefix present but no actual CID bytes
try std.testing.expectError(error.InvalidCid, cbor.decode(arena.allocator(), &.{
0xd8, 0x2a, // tag(42)
0x41, 0x00, // bytes(1) with just the 0x00 prefix
}));
}
test "reject tag 42 with only prefix + 1 byte (too short for CID)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// tag(42) + bytes([0x00, 0x01]) — only 1 CID byte, need at least version + codec
try std.testing.expectError(error.InvalidCid, cbor.decode(arena.allocator(), &.{
0xd8, 0x2a, // tag(42)
0x42, 0x00, 0x01, // bytes(2) — prefix + 1 byte
}));
}
// === allocation failure safety (checkAllAllocationFailures) ===
fn decodeSimpleImpl(backing: std.mem.Allocator, data: []const u8) !void {
// use an arena over the backing allocator — checkAllAllocationFailures
// tracks the backing allocator's alloc/free calls. the arena batches
// frees on deinit, so OOM from any arena allocation correctly frees
// everything allocated so far.
var arena = std.heap.ArenaAllocator.init(backing);
defer arena.deinit();
_ = try cbor.decodeAll(arena.allocator(), data);
}
test "checkAllAllocationFailures: decode flat map" {
var setup_arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer setup_arena.deinit();
const encoded = try cbor.encodeAlloc(setup_arena.allocator(), .{ .map = &.{
.{ .key = "a", .value = .{ .unsigned = 1 } },
.{ .key = "b", .value = .{ .text = "hello" } },
} });
try std.testing.checkAllAllocationFailures(std.testing.allocator, decodeSimpleImpl, .{encoded});
}
fn decodeNestedImpl(backing: std.mem.Allocator, data: []const u8) !void {
var arena = std.heap.ArenaAllocator.init(backing);
defer arena.deinit();
_ = try cbor.decodeAll(arena.allocator(), data);
}
test "checkAllAllocationFailures: decode nested record" {
var setup_arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer setup_arena.deinit();
const sa = setup_arena.allocator();
const record: Value = .{ .map = &.{
.{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } },
.{ .key = "langs", .value = .{ .array = &.{.{ .text = "en" }} } },
.{ .key = "text", .value = .{ .text = "hello" } },
} };
const encoded = try cbor.encodeAlloc(sa, record);
try std.testing.checkAllAllocationFailures(std.testing.allocator, decodeNestedImpl, .{encoded});
}
fn decodeArrayImpl(backing: std.mem.Allocator, data: []const u8) !void {
var arena = std.heap.ArenaAllocator.init(backing);
defer arena.deinit();
_ = try cbor.decodeAll(arena.allocator(), data);
}
test "checkAllAllocationFailures: decode array" {
var setup_arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer setup_arena.deinit();
const encoded = try cbor.encodeAlloc(setup_arena.allocator(), .{ .array = &.{
.{ .unsigned = 1 },
.{ .unsigned = 2 },
.{ .text = "three" },
} });
try std.testing.checkAllAllocationFailures(std.testing.allocator, decodeArrayImpl, .{encoded});
}
// === negative integer encode round-trip at min i64 ===
test "round-trip encode min i64" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const min_i64: i64 = std.math.minInt(i64);
const encoded = try cbor.encodeAlloc(alloc, .{ .negative = min_i64 });
const decoded = try cbor.decodeAll(alloc, encoded);
try std.testing.expectEqual(min_i64, decoded.negative);
}
// === strict CID parsing (atproto-blessed profile) ===
test "Cid.fromString round-trips a known CID" {
const a = std.testing.allocator;
const s = "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm";
const cid = try Cid.fromString(a, s);
defer a.free(cid.raw);
const out = try cid.toString(a);
defer a.free(out);
try std.testing.expectEqualStrings(s, out);
try std.testing.expectEqual(@as(?u64, 1), cid.version());
try std.testing.expectEqual(@as(?u64, cbor.Codec.dag_cbor), cid.codec());
}
test "Cid.fromString rejects empty, bad prefix, bad base32" {
const a = std.testing.allocator;
try std.testing.expectError(error.InvalidCid, Cid.fromString(a, ""));
try std.testing.expectError(error.UnsupportedEncoding, Cid.fromString(a, "zafyrei"));
try std.testing.expectError(error.InvalidCharacter, Cid.fromString(a, "b!!!!"));
}
test "Cid.fromBytes rejects CIDv0" {
var v0: [34]u8 = undefined;
v0[0] = 0x12;
v0[1] = 0x20;
@memset(v0[2..], 0xaa);
try std.testing.expectError(error.UnsupportedCidVersion, Cid.fromBytes(&v0));
}
test "Cid.fromBytes rejects wrong version, codec, hash, length, trailing bytes" {
const a = std.testing.allocator;
const valid = try Cid.forDagCbor(a, "hello");
defer a.free(valid.raw);
_ = try Cid.fromBytes(valid.raw);
var buf: [40]u8 = undefined;
// version 2
@memcpy(buf[0..valid.raw.len], valid.raw);
buf[0] = 0x02;
try std.testing.expectError(error.UnsupportedCidVersion, Cid.fromBytes(buf[0..valid.raw.len]));
// dag-pb codec
@memcpy(buf[0..valid.raw.len], valid.raw);
buf[1] = 0x70;
try std.testing.expectError(error.UnsupportedCodec, Cid.fromBytes(buf[0..valid.raw.len]));
// blake3 hash code
@memcpy(buf[0..valid.raw.len], valid.raw);
buf[2] = 0x1e;
try std.testing.expectError(error.UnsupportedHash, Cid.fromBytes(buf[0..valid.raw.len]));
// digest length 31
@memcpy(buf[0..valid.raw.len], valid.raw);
buf[3] = 31;
try std.testing.expectError(error.InvalidCid, Cid.fromBytes(buf[0..valid.raw.len]));
// trailing byte
@memcpy(buf[0..valid.raw.len], valid.raw);
buf[valid.raw.len] = 0x00;
try std.testing.expectError(error.InvalidCid, Cid.fromBytes(buf[0 .. valid.raw.len + 1]));
// truncated digest
try std.testing.expectError(error.InvalidCid, Cid.fromBytes(valid.raw[0 .. valid.raw.len - 1]));
}
test "Cid.fromBytes rejects non-minimal varint encoding" {
const a = std.testing.allocator;
const valid = try Cid.forDagCbor(a, "hello");
defer a.free(valid.raw);
// re-encode the version varint (1) as overlong 0x81 0x00
var buf: [64]u8 = undefined;
buf[0] = 0x81;
buf[1] = 0x00;
@memcpy(buf[2 .. 1 + valid.raw.len], valid.raw[1..]);
try std.testing.expectError(error.InvalidCid, Cid.fromBytes(buf[0 .. 1 + valid.raw.len]));
}
test "Cid.create rejects a hash code it does not compute" {
const a = std.testing.allocator;
try std.testing.expectError(
error.UnsupportedHash,
Cid.create(a, 1, cbor.Codec.dag_cbor, 0x1e, "hello"),
);
const cid = try Cid.create(a, 1, cbor.Codec.raw, cbor.HashFn.sha2_256, "hello");
defer a.free(cid.raw);
_ = try Cid.fromBytes(cid.raw);
}
test "Cid.fromSha256Digest equals Cid.create over the same bytes" {
const a = std.testing.allocator;
const data = "blob bytes hashed while streaming";
var digest: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(data, &digest, .{});
for ([_]u64{ cbor.Codec.raw, cbor.Codec.dag_cbor }) |codec| {
const want = try Cid.create(a, 1, codec, cbor.HashFn.sha2_256, data);
defer a.free(want.raw);
const got = try Cid.fromSha256Digest(a, codec, &digest);
defer a.free(got.raw);
try std.testing.expectEqualSlices(u8, want.raw, got.raw);
_ = try Cid.fromBytes(got.raw);
try std.testing.expectEqual(codec, got.codec().?);
try std.testing.expectEqualSlices(u8, &digest, got.digest().?);
}
try std.testing.expectError(error.UnsupportedCodec, Cid.fromSha256Digest(a, cbor.Codec.dag_pb, &digest));
}
test "readUvarintMinimal rejects overlong and oversized encodings" {
var pos: usize = 0;
try std.testing.expectEqual(@as(?u64, 1), cbor.readUvarintMinimal(&.{0x01}, &pos));
pos = 0;
try std.testing.expectEqual(@as(?u64, null), cbor.readUvarintMinimal(&.{ 0x81, 0x00 }, &pos));
pos = 0;
const too_long = @as([9]u8, @splat(0x80)) ++ [_]u8{0x01};
try std.testing.expectEqual(@as(?u64, null), cbor.readUvarintMinimal(&too_long, &pos));
}
// === fromJson (atmos cbor/json.go FromJSON) ===
test "fromJson: scalars, number semantics, sentinels, nesting" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const parsed = try std.json.parseFromSlice(std.json.Value, a,
\\{"text":"hi","truthy":true,"nothing":null,"whole":42.0,"neg":-7,
\\ "ratio":1.5,"blob":{"$bytes":"3q2+7w"},
\\ "ref":{"$link":"bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a"},
\\ "list":[1,"two"],
\\ "not_sentinel":{"$link":"bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a","extra":1}}
, .{});
defer parsed.deinit();
const v = try cbor.fromJson(a, parsed.value);
const map = v.map;
try std.testing.expectEqualStrings("hi", findEntry(map, "text").text);
try std.testing.expect(findEntry(map, "truthy").boolean);
try std.testing.expect(findEntry(map, "nothing") == .null);
// whole float within +/- 2^53 converts to an integer (atmos fromJSONValue)
try std.testing.expectEqual(@as(u64, 42), findEntry(map, "whole").unsigned);
try std.testing.expectEqual(@as(i64, -7), findEntry(map, "neg").negative);
try std.testing.expectEqual(@as(f64, 1.5), findEntry(map, "ratio").float);
// $bytes: unpadded standard base64 (atmos RawStdEncoding)
try std.testing.expectEqualSlices(u8, &.{ 0xde, 0xad, 0xbe, 0xef }, findEntry(map, "blob").bytes);
// $link: parsed CID
try std.testing.expect(findEntry(map, "ref") == .cid);
// arrays recurse
const list = findEntry(map, "list").array;
try std.testing.expectEqual(@as(u64, 1), list[0].unsigned);
try std.testing.expectEqualStrings("two", list[1].text);
// a $link object with EXTRA keys is a plain map, not a sentinel
try std.testing.expect(findEntry(map, "not_sentinel") == .map);
// the converted tree encodes canonically (round-trip through decode)
const bytes = try cbor.encodeAlloc(a, v);
const back = try cbor.decode(a, bytes);
try std.testing.expectEqual(@as(f64, 1.5), findEntry(back.value.map, "ratio").float);
try std.testing.expectEqual(@as(u64, 42), findEntry(back.value.map, "whole").unsigned);
}
test "fromJson: $bytes padding is optional" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const accepted = [_]struct { b64: []const u8, want: []const u8 }{
.{ .b64 = "", .want = "" },
.{ .b64 = "AQ", .want = &.{0x01} },
.{ .b64 = "AQ==", .want = &.{0x01} },
.{ .b64 = "AQI", .want = &.{ 0x01, 0x02 } },
.{ .b64 = "AQI=", .want = &.{ 0x01, 0x02 } },
.{ .b64 = "AQID", .want = &.{ 0x01, 0x02, 0x03 } },
.{ .b64 = "3q2+7w==", .want = &.{ 0xde, 0xad, 0xbe, 0xef } },
};
for (accepted) |case| {
const json = try std.fmt.allocPrint(a, "{{\"$bytes\":\"{s}\"}}", .{case.b64});
const parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{});
try std.testing.expectEqualSlices(u8, case.want, (try cbor.fromJson(a, parsed.value)).bytes);
}
const rejected = [_][]const u8{
"AQ=", // incomplete padding
"AQ===", // too much padding
"AQI==", // padding past the final group
"AQID=", // padding after a complete group
"AQ=I", // = before the end
"A=Q=", // = inside the final group
"=", // padding alone
"A", // a single trailing character encodes no byte
"3q2-7w", // base64url alphabet
"3q2+7w== ", // trailing whitespace
};
for (rejected) |b64| {
const json = try std.fmt.allocPrint(a, "{{\"$bytes\":\"{s}\"}}", .{b64});
const parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{});
_ = cbor.fromJson(a, parsed.value) catch |err| {
try std.testing.expectEqual(error.InvalidBytesSentinel, err);
continue;
};
std.debug.print("accepted invalid $bytes {s}\n", .{b64});
return error.TestUnexpectedResult;
}
}
test "fromJson: malformed sentinels error" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const bad_b64 = try std.json.parseFromSlice(std.json.Value, a, "{\"$bytes\":\"!!not-base64!!\"}", .{});
try std.testing.expectError(error.InvalidBytesSentinel, cbor.fromJson(a, bad_b64.value));
const bad_cid = try std.json.parseFromSlice(std.json.Value, a, "{\"$link\":\"zzzz\"}", .{});
try std.testing.expectError(error.InvalidLinkSentinel, cbor.fromJson(a, bad_cid.value));
const non_string = try std.json.parseFromSlice(std.json.Value, a, "{\"$bytes\":7}", .{});
try std.testing.expectError(error.InvalidBytesSentinel, cbor.fromJson(a, non_string.value));
}
// === toJson ===
test "toJson: writes atproto JSON" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const cid = try Cid.fromString(a, "bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a");
const value: cbor.Value = .{ .map = &.{
.{ .key = "n", .value = .{ .unsigned = 7 } },
.{ .key = "neg", .value = .{ .negative = -9223372036854775808 } },
.{ .key = "big", .value = .{ .unsigned = std.math.maxInt(u64) } },
.{ .key = "s", .value = .{ .text = "quote \" slash \\ nl \n" } },
.{ .key = "b", .value = .{ .bytes = &.{0x01} } },
.{ .key = "b2", .value = .{ .bytes = &.{ 0x01, 0x02 } } },
.{ .key = "b3", .value = .{ .bytes = &.{ 0x01, 0x02, 0x03 } } },
.{ .key = "empty", .value = .{ .bytes = "" } },
.{ .key = "ref", .value = .{ .cid = cid } },
.{ .key = "list", .value = .{ .array = &.{ .{ .boolean = true }, .{ .boolean = false }, .null } } },
.{ .key = "nested", .value = .{ .map = &.{} } },
} };
try std.testing.expectEqualStrings(
\\{"n":7,"neg":-9223372036854775808,"big":18446744073709551615,"s":"quote \" slash \\ nl \n",
++
\\"b":{"$bytes":"AQ"},"b2":{"$bytes":"AQI"},"b3":{"$bytes":"AQID"},"empty":{"$bytes":""},
++
\\"ref":{"$link":"bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a"},
++
\\"list":[true,false,null],"nested":{}}
, try cbor.toJsonAlloc(a, value));
}
test "toJson: CID text matches Cid.toString at every length" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var raw: [97]u8 = undefined;
for (&raw, 0..) |*byte, i| byte.* = @truncate(i * 37 + 11);
for (0..raw.len + 1) |len| {
const cid: Cid = .{ .raw = raw[0..len] };
const want = try std.fmt.allocPrint(a, "{{\"$link\":\"{s}\"}}", .{try cid.toString(a)});
try std.testing.expectEqualStrings(want, try cbor.toJsonAlloc(a, .{ .cid = cid }));
}
}
test "toJson: round-trips through fromJson" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const inputs = [_][]const u8{
\\{"text":"hi \u00e9 \"q\"","n":-7,"z":0,"max":9223372036854775807,
\\ "blob":{"$type":"blob","ref":{"$link":"bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy"},"mimeType":"image/png","size":3},
\\ "raw":{"$bytes":"3q2+7w"},"list":[1,[2,[3]],{"a":null}],"t":true}
,
"[]",
"{}",
"\"\"",
"{\"$bytes\":\"\"}",
};
for (inputs) |input| {
const parsed = try std.json.parseFromSlice(std.json.Value, a, input, .{});
const value = try cbor.fromJson(a, parsed.value);
const json = try cbor.toJsonAlloc(a, value);
const reparsed = try std.json.parseFromSlice(std.json.Value, a, json, .{});
const again = try cbor.fromJson(a, reparsed.value);
try std.testing.expectEqualSlices(u8, try cbor.encodeAlloc(a, value), try cbor.encodeAlloc(a, again));
try std.testing.expectEqualStrings(json, try cbor.toJsonAlloc(a, again));
}
// padded input comes back unpadded
const padded = try std.json.parseFromSlice(std.json.Value, a, "{\"$bytes\":\"3q2+7w==\"}", .{});
try std.testing.expectEqualStrings("{\"$bytes\":\"3q2+7w\"}", try cbor.toJsonAlloc(a, try cbor.fromJson(a, padded.value)));
}
test "toJson: decoded floats are written as JSON numbers" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const cases = [_]struct { f: f64, want: []const u8 }{
.{ .f = 1.5, .want = "1.5" },
.{ .f = -0.25, .want = "-0.25" },
.{ .f = 2.0, .want = "2" },
.{ .f = 1e300, .want = "1e300" },
.{ .f = -1.5e-7, .want = "-1.5e-7" },
.{ .f = 1e21, .want = "1e21" },
};
for (cases) |case| {
const f = case.f;
const json = try cbor.toJsonAlloc(a, .{ .float = f });
try std.testing.expectEqualStrings(case.want, json);
const parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{});
try std.testing.expectEqual(f, switch (parsed.value) {
.float => |v| v,
.integer => |i| @as(f64, @floatFromInt(i)),
else => return error.TestUnexpectedResult,
});
}
}
test "toJson: reports writer failure" {
var buf: [4]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try std.testing.expectError(error.WriteFailed, cbor.toJson(&w, .{ .text = "too long for the buffer" }));
}
// === collectBlobRefs ===
test "collectBlobRefs finds typed blob refs at any depth" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const parsed = try std.json.parseFromSlice(std.json.Value, a,
\\{"$type":"app.bsky.feed.post","text":"two images",
\\ "embed":{"$type":"app.bsky.embed.images","images":[
\\ {"alt":"one","image":{"$type":"blob","ref":{"$link":"bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy"},"mimeType":"image/png","size":3}},
\\ {"alt":"two","image":{"$type":"blob","ref":{"$link":"bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku"},"mimeType":"image/jpeg","size":5}}]},
\\ "legacy":{"cid":"bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy","mimeType":"image/png"},
\\ "notblob":{"$type":"app.example.thing","ref":{"$link":"bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy"}},
\\ "badref":{"$type":"blob","ref":"bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy","mimeType":"image/png","size":3},
\\ "noref":{"$type":"blob","mimeType":"image/png","size":3}}
, .{});
const record = try cbor.fromJson(a, parsed.value);
var refs: std.ArrayList(Cid) = .empty;
try cbor.collectBlobRefs(a, record, &refs);
try std.testing.expectEqual(@as(usize, 2), refs.items.len);
try std.testing.expectEqualStrings("bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy", try refs.items[0].toString(a));
try std.testing.expectEqualStrings("bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku", try refs.items[1].toString(a));
// a decoded record yields the same refs
const decoded = try cbor.decodeAll(a, try cbor.encodeAlloc(a, record));
var decoded_refs: std.ArrayList(Cid) = .empty;
try cbor.collectBlobRefs(a, decoded, &decoded_refs);
try std.testing.expectEqual(@as(usize, 2), decoded_refs.items.len);
var none: std.ArrayList(Cid) = .empty;
try cbor.collectBlobRefs(a, .{ .text = "blob" }, &none);
try std.testing.expectEqual(@as(usize, 0), none.items.len);
}
fn findEntry(entries: []const cbor.Value.MapEntry, key: []const u8) cbor.Value {
for (entries) |entry| {
if (std.mem.eql(u8, entry.key, key)) return entry.value;
}
unreachable;
}