-
Notifications
You must be signed in to change notification settings - Fork 3
/
cbor.d
2514 lines (2215 loc) · 76.5 KB
/
cbor.d
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
/**
Copyright: Copyright (c) 2014-2018 Andrey Penechko.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Andrey Penechko.
Concise Binary Object Representation (CBOR) for D lang.
The Concise Binary Object Representation (CBOR) is a data format
whose design goals include the possibility of extremely small code
size, fairly small message size, and extensibility without the need
for version negotiation. These design goals make it different from
earlier binary serializations such as ASN.1 and MessagePack.
Standards: Conforms to RFC 7049.
*/
module cbor;
private import std.string : format;
private import std.traits : Unqual, hasUDA, isArray, isAssociativeArray, isBoolean, isDynamicArray,
isExpressionTuple, isFloatingPoint, isIntegral, isSomeChar, isStaticArray, isUnsigned;
public import std.typecons : Flag, Yes, No;
private import std.range : ElementEncodingType, hasLength, save, tee;
private import std.conv : to;
private import std.utf : byChar;
version(unittest) {
version = Cbor_Debug;
}
//------------------------------------------------------------------------------
// EEEEEEE NN NN CCCCC OOOOO DDDDD IIIII NN NN GGGG
// EE NNN NN CC C OO OO DD DD III NNN NN GG GG
// EEEEE NN N NN CC OO OO DD DD III NN N NN GG
// EE NN NNN CC C OO OO DD DD III NN NNN GG GG
// EEEEEEE NN NN CCCCC OOOO0 DDDDDD IIIII NN NN GGGGGG
//------------------------------------------------------------------------------
private import std.range : isInputRange, isOutputRange, ElementType;
private import std.typecons : isTuple;
//------------------------------------------------------------------------------
// Simple types (int, float, bool, null, undefined, break, simple)
//------------------------------------------------------------------------------
// Encode integer types as separate type or as part of arrays or map.
private size_t encodeLongType(R)(auto ref R sink, ubyte majorType, ulong length)
if(isOutputRange!(R, ubyte))
{
import std.bitmanip : nativeToBigEndian;
majorType <<= 5;
if (length < 24) {
putChecked(sink, cast(ubyte)(majorType | length));
return 1;
} else if (length <= ubyte.max) {
putChecked(sink, cast(ubyte)(majorType | 24));
putChecked(sink, cast(ubyte)length);
return 2;
} else if (length <= ushort.max) {
putChecked(sink, cast(ubyte)(majorType | 25));
putChecked(sink, nativeToBigEndian!ushort(cast(ushort)length)[]);
return 3;
} else if (length <= uint.max) {
putChecked(sink, cast(ubyte)(majorType | 26));
putChecked(sink, nativeToBigEndian!uint(cast(uint)length)[]);
return 5;
} else { // if (length <= ulong.max)
putChecked(sink, cast(ubyte)(majorType | 27));
putChecked(sink, nativeToBigEndian!ulong(cast(ulong)length)[]);
return 9;
}
}
/// Encodes integer.
size_t encodeCborInt(R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) && isIntegral!E)
{
ulong val;
ubyte majorType;
if (value < 0) {
val = -cast(long)value - 1;
majorType = 1;
} else {
val = value;
majorType = 0;
}
return encodeLongType(sink, majorType, val);
}
/// Encodes floating.
size_t encodeCborFloat(R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) && isFloatingPoint!E)
{
import std.bitmanip : nativeToBigEndian;
enum majorType = 7 << 5;
static if (is(Unqual!E == float))
{
__FloatRep flt;
flt.f = value;
putChecked(sink, cast(ubyte)(majorType | 26));
putChecked(sink, nativeToBigEndian!uint(flt.u)[]);
return 5;
}
else static if (is(Unqual!E == double) || is(Unqual!E == real))
{
__DoubleRep dbl;
dbl.d = cast(double)value;
putChecked(sink, cast(ubyte)(majorType | 27));
putChecked(sink, nativeToBigEndian!ulong(dbl.u)[]);
return 9;
}
}
/// Encodes boolean.
size_t encodeCborBool(R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) && isBoolean!E)
{
if (value)
putChecked(sink, cast(ubyte)0xf5);
else
putChecked(sink, cast(ubyte)0xf4);
return 1;
}
/// Encodes null.
size_t encodeCborNull(R)(auto ref R sink)
if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0xf6);
return 1;
}
/// Encodes undefined.
size_t encodeCborUndefined(R)(auto ref R sink) if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0xf7);
return 1;
}
/// Encodes break. Use after all items of indefinite-length sequence were encoded.
size_t encodeCborBreak(R)(auto ref R sink) if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0xff);
return 1;
}
/// Encodes simple. Simple data type is essentially a number that has special meaning.
/// Value must lie in range [0..23] or [32..255].
size_t encodeCborSimple(R)(auto ref R sink, ubyte simple) if(isOutputRange!(R, ubyte))
{
enum ubyte majorType = 7 << 5;
if (simple < 24) {
putChecked(sink, cast(ubyte)(majorType | simple));
return 1;
} else if (simple > 31) {
putChecked(sink, cast(ubyte)0xf8);
putChecked(sink, simple);
return 2;
} else {
assert(false, format("Invalid simple value %s", simple));
}
}
//------------------------------------------------------------------------------
// Complex data (byte-string, text-string, array, map)
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
size_t encodeCborBytesHeader(R)(auto ref R sink, ulong bytesLength) if(isOutputRange!(R, ubyte))
{
return encodeLongType(sink, 2, bytesLength);
}
size_t encodeCborBytesHeader(R)(auto ref R sink) if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0x5f);
return 1;
}
size_t encodeCborStringHeader(R)(auto ref R sink, ulong textLength) if(isOutputRange!(R, ubyte))
{
return encodeLongType(sink, 3, textLength);
}
size_t encodeCborStringHeader(R)(auto ref R sink) if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0x7f);
return 1;
}
size_t encodeCborArrayHeader(R)(auto ref R sink, ulong arrayLength) if(isOutputRange!(R, ubyte))
{
return encodeLongType(sink, 4, arrayLength);
}
size_t encodeCborArrayHeader(R)(auto ref R sink) if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0x9f);
return 1;
}
size_t encodeCborMapHeader(R)(auto ref R sink, ulong mapLength) if(isOutputRange!(R, ubyte))
{
return encodeLongType(sink, 5, mapLength);
}
size_t encodeCborMapHeader(R)(auto ref R sink) if(isOutputRange!(R, ubyte))
{
putChecked(sink, cast(ubyte)0xbf);
return 1;
}
//------------------------------------------------------------------------------
// Items
//------------------------------------------------------------------------------
/// Writes range of ubyte to the sink. Needs to go after a call to encodeCborBytesHeader.
/// The length of supplied range must be equal to one provided to encodeCborBytesHeader.
size_t encodeCborBytesItems(R, D)(auto ref R sink, D bytes)
if(isOutputRange!(R, ubyte) &&
(isArray!D || isInputRange!D) && is(Unqual!(ElementType!D) == ubyte))
{
static if (hasLength!D) {
static if (isStaticArray!D)
putChecked(sink, bytes[]);
else
putChecked(sink, bytes);
return bytes.length;
} else {
size_t count;
putChecked(sink, tee!((a){++count;})(bytes));
return count;
}
}
//------------------------------------------------------------------------------
// Tag
//------------------------------------------------------------------------------
///
size_t encodeCborTag(R)(auto ref R sink, ulong value) if(isOutputRange!(R, ubyte))
{
return encodeLongType(sink, 6, value);
}
//------------------------------------------------------------------------------
// SSSSS EEEEEEE RRRRRR IIIII AAA LL IIIII ZZZZZ AAA TTTTTTT IIIII OOOOO NN NN
// SS EE RR RR III AAAAA LL III ZZ AAAAA TTT III OO OO NNN NN
// SSSSS EEEEE RRRRRR III AA AA LL III ZZ AA AA TTT III OO OO NN N NN
// SS EE RR RR III AAAAAAA LL III ZZ AAAAAAA TTT III OO OO NN NNN
// SSSSS EEEEEEE RR RR IIIII AA AA LLLLLLL IIIII ZZZZZ AA AA TTT IIIII OOOO0 NN NN
//------------------------------------------------------------------------------
/// Encodes value E into output range sink.
/// Returns number of bytes written to sink.
/// If flatten flag is yes then static arrays and structs will be encoded in place without headers.
size_t encodeCbor(Flag!"Flatten" flatten = No.Flatten, R, E)(auto ref R sink, auto ref const E value)
if(isOutputRange!(R, ubyte))
{
import std.typecons : isTuple;
static if (isIntegral!E)
{
return encodeCborInt(sink, value);
}
else static if (isSomeChar!E)
{
return encodeCborInt(sink, cast(ulong)value);
}
else static if (isFloatingPoint!E)
{
return encodeCborFloat(sink, value);
}
else static if (isBoolean!E)
{
return encodeCborBool(sink, value);
}
else static if (is(Unqual!E == typeof(null)))
{
return encodeCborNull(sink);
}
else static if ((isArray!E || isInputRange!E) && is(Unqual!(ElementType!E) == ubyte))
{
return encodeCborBytes!(flatten)(sink, value);
}
else static if ((isArray!E || isInputRange!E) && isSomeChar!(Unqual!(ElementEncodingType!E)))
{
return encodeCborString!(flatten)(sink, value);
}
else static if (isInputRange!E || isArray!E || isTuple!E ||
is(E == class) || is(E == struct))
{
return encodeCborArray!(flatten)(sink, value);
}
else static if (isAssociativeArray!E)
{
return encodeCborMap(sink, value);
}
else
{
static assert(false, "Unable to encode " ~ E.stringof);
}
}
/// Encodes range of ubytes.
size_t encodeCborBytes(Flag!"Flatten" flatten = No.Flatten, R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) &&
(isArray!E || isInputRange!E) && is(Unqual!(ElementType!E) == ubyte))
{
size_t size = 0;
// drop type and length for static arrays in flatten mode
static if (!needsFlattening!(E, flatten))
{
size = encodeCborBytesHeader(sink, value.length);
}
size += encodeCborBytesItems(sink, value);
return size;
}
/// Encodes string.
size_t encodeCborString(Flag!"Flatten" flatten = No.Flatten, R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) && isSomeChar!(Unqual!(ElementEncodingType!E)))
{
size_t size = 0;
// drop type and length for static arrays in flatten mode
static if (!needsFlattening!(E, flatten))
{
size = encodeCborStringHeader(sink, value.length);
}
size += value.length;
static if (is(Unqual!(ElementEncodingType!E) == char))
{
putChecked(sink, cast(ubyte[])value);
}
else
{
foreach(char elem; value[].byChar)
{
putChecked(sink, cast(ubyte)elem);
}
}
return size;
}
/// Encodes array of any items or a tuple as cbor array.
size_t encodeCborArray(Flag!"Flatten" flatten = No.Flatten, R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) &&
(isInputRange!E || isArray!E || isTuple!E))
{
static if (isArray!E && is(Unqual!(ElementType!E) == void)) // accept []
{
return encodeCborArrayHeader(sink, 0);
}
else
{
size_t size = 0;
// drop type and length for static arrays and expression tuples in flatten mode
static if (!needsFlattening!(E, flatten))
size = encodeCborArrayHeader(sink, value.length);
foreach(item; value)
size += encodeCbor!(flatten)(sink, item);
return size;
}
}
/// Encodes structs and classes as cbor array.
size_t encodeCborArray(Flag!"Flatten" flatten = No.Flatten, R, A)(auto ref R sink, A aggregate)
if(isOutputRange!(R, ubyte) &&
(is(A == struct) || is(A == class)) &&
!isTuple!A)
{
return encodeCborAggregate!(Flag!"WithFieldName".no, flatten)(sink, aggregate);
}
/// Encodes asociative array as cbor map.
size_t encodeCborMap(R, E)(auto ref R sink, E value)
if(isOutputRange!(R, ubyte) && isAssociativeArray!E)
{
size_t size = encodeCborMapHeader(sink, value.length);
foreach(key, element; value)
{
size += encodeCbor(sink, key);
size += encodeCbor(sink, element);
}
return size;
}
/// Encodes structs and classes as cbor map.
/// Note, that decoding of structs and classes from maps is not supported (yet).
size_t encodeCborMap(Flag!"Flatten" flatten = Flag!"Flatten".no, R, A)(auto ref R sink, A aggregate)
if(isOutputRange!(R, ubyte) && (is(A == struct) || is(A == class)) && !isTuple!A)
{
return encodeCborAggregate!(Flag!"WithFieldName".yes, flatten)(sink, aggregate);
}
/// Encodes classes and structs. If withFieldName is yes, than value is encoded as map.
/// If withFieldName is no, then value is encoded as an array.
/// If flatten flag is yes then static arrays and structs will be encoded in place without headers.
size_t encodeCborAggregate(
Flag!"WithFieldName" withFieldName,
Flag!"Flatten" flatten = Flag!"Flatten".no,
R,
A)(
auto ref R sink,
auto ref A aggregate)
if (isOutputRange!(R, ubyte) && (is(A == struct) || is(A == class)))
{
size_t size;
static if (is(A == class))
if (aggregate is null)
return encodeCbor(sink, null);
// flatten structs only
static if (!needsFlattening!(A, flatten))
{
static if (withFieldName)
size += encodeCborMapHeader(sink, numEncodableMembers!A);
else
size += encodeCborArrayHeader(sink, numEncodableMembers!A);
}
foreach(i, member; aggregate.tupleof)
{
static if (isEncodedField!(aggregate.tupleof[i]))
{
// when encoded as map order is unspecified and flatten is not possible
static if (withFieldName)
{
size += encodeCborString(sink, __traits(identifier, aggregate.tupleof[i]));
size += encodeCbor(sink, member);
}
else
size += encodeCbor!flatten(sink, member);
}
}
return size;
}
//------------------------------------------------------------------------------
// SSSSS TTTTTTT OOOOO RRRRRR AAA GGGG EEEEEEE
// SS TTT OO OO RR RR AAAAA GG GG EE
// SSSSS TTT OO OO RRRRRR AA AA GG EEEEE
// SS TTT OO OO RR RR AAAAAAA GG GG EE
// SSSSS TTT OOOO0 RR RR AA AA GGGGGG EEEEEEE
//------------------------------------------------------------------------------
///
enum CborTokenType : ubyte
{
/// CborToken.uinteger stores array length.
/// Indefinite-length array has no length.
/// Header is followed by zero or more data items, terminated by break.
arrayHeader = 0b000,
arrayIndefiniteHeader = 0b001, /// ditto
/// CborToken.uinteger stores map's pair count.
/// Indefinite-length map has no length.
/// Header is followed by zero or more pairs, terminated by break.
mapHeader = 0b010,
mapIndefiniteHeader = 0b011, /// ditto
/// CborToken.uinteger stores byte string length.
/// Indefinite-length byte string has no length.
/// Header is follower by zero or more definite-length byte strings terminated by break.
bytesHeader = 0b100,
bytesIndefiniteHeader = 0b101, /// ditto
/// CborToken.uinteger stores text string length.
/// Indefinite-length text string has no length.
/// Header is follower by zero or more definite-length text strings terminated by break.
textHeader = 0b110,
textIndefiniteHeader = 0b111, /// ditto
undefined, /// CborToken value is undefined.
nil, /// CborToken value is null.
boolean, /// CborToken.boolean stores actual value.
tag, /// uinteger stores tag value.
simple, /// Simple value is integer in range [0-255], stored in uinteger.
breakCode, /// "break" stop code, used to terminate indefinite-length sequences.
posinteger, /// CborToken.uinteger stores actual value.
neginteger, /// CborToken.integer stores actual value.
floating, /// CborToken.floating stores actual value.
}
///
struct CborToken
{
CborTokenType type;
union
{
bool boolean;
long integer;
double floating;
// used for storing positive integers, array, map, raw and text size
ulong uinteger;
}
this(CborTokenType t) @nogc {
type = t;
}
this(CborTokenType t, bool v) @nogc {
type = t;
boolean = v;
}
this(CborTokenType t, long v) @nogc {
type = t;
integer = v;
}
this(CborTokenType t, double v) @nogc {
type = t;
floating = v;
}
bool opEquals(const CborToken other) const @nogc {
ubyte[] thisRep = (cast(ubyte*)(&this))[0..this.sizeof];
ubyte[] otherRep = (cast(ubyte*)(&other))[0..other.sizeof];
return thisRep == otherRep;
}
string toString() const
{
import std.string : format;
final switch(type) with(CborTokenType)
{
case boolean: return format("CborToken(%s)", boolean);
case nil: return "CborToken(null)";
case undefined: return "CborToken(undefined)";
case tag: return format("CborToken(tag, %s)", type, uinteger);
case simple: return format("CborToken(simple, %s)", uinteger);
case breakCode: return format("CborToken(break)");
case posinteger: return format("CborToken(%s, %s)", type, uinteger);
case neginteger: return format("CborToken(%s, %s)", type, integer);
case floating: return format("CborToken(%s, %s)", type, floating);
case arrayHeader: return format("CborToken(array, %s)", uinteger);
case arrayIndefiniteHeader: return format("CborToken(arrayIndefiniteLength, _)");
case mapHeader: return format("CborToken(map, %s)", uinteger);
case mapIndefiniteHeader: return format("CborToken(mapIndefiniteLength, _)");
case bytesHeader: return format("CborToken(byteString, %s)", uinteger);
case bytesIndefiniteHeader: return format("CborToken(byteStringIndefiniteLength, _)");
case textHeader: return format("CborToken(textString, %s)", uinteger);
case textIndefiniteHeader: return format("CborToken(textStringIndefiniteLength, _)");
}
}
}
//------------------------------------------------------------------------------
// DDDDD EEEEEEE CCCCC OOOOO DDDDD IIIII NN NN GGGG
// DD DD EE CC C OO OO DD DD III NNN NN GG GG
// DD DD EEEEE CC OO OO DD DD III NN N NN GG
// DD DD EE CC C OO OO DD DD III NN NNN GG GG
// DDDDDD EEEEEEE CCCCC OOOO0 DDDDDD IIIII NN NN GGGGGG
//------------------------------------------------------------------------------
CborToken decodeCborToken(R)(auto ref R input)
if(isInputRange!R && is(ElementType!R == ubyte))
{
import std.array;
if (input.empty) onInsufficientInput();
ubyte item = input.front;
input.popFront;
switch(item)
{
case 0x00: .. case 0x17: // Integer 0x00..0x17 (0..23)
return CborToken(CborTokenType.posinteger, item);
case 0x18: // Unsigned integer (one-byte uint8_t follows)
return CborToken(CborTokenType.posinteger, readInteger!ubyte(input));
case 0x19: // Unsigned integer (two-byte uint16_t follows)
return CborToken(CborTokenType.posinteger, readInteger!ushort(input));
case 0x1a: // Unsigned integer (four-byte uint32_t follows)
return CborToken(CborTokenType.posinteger, readInteger!uint(input));
case 0x1b: // Unsigned integer (eight-byte uint64_t follows)
return CborToken(CborTokenType.posinteger, readInteger!ulong(input));
case 0x20: .. case 0x37: // Negative integer -1-0x00..-1-0x17 (-1..-24)
return CborToken(CborTokenType.neginteger, cast(byte)(-1 - item + 0x20));
case 0x38: // Negative integer -1-n (one-byte uint8_t for n follows)
return CborToken(CborTokenType.neginteger, -1 - cast(long)readInteger!ubyte(input));
case 0x39: // Negative integer -1-n (two-byte uint16_t for n follows)
return CborToken(CborTokenType.neginteger, -1 - cast(long)readInteger!ushort(input));
case 0x3a: // Negative integer -1-n (four-byte uint32_t for n follows)
return CborToken(CborTokenType.neginteger, -1 - cast(long)readInteger!uint(input));
case 0x3b: // Negative integer -1-n (eight-byte uint64_t for n follows)
return CborToken(CborTokenType.neginteger, -1 - cast(long)readInteger!ulong(input));
case 0x40: .. case 0x57: // byte string (0x00..0x17 bytes follow)
return CborToken(CborTokenType.bytesHeader, item - 0x40);
case 0x58: // byte string (one-byte uint8_t for n, and then n bytes follow)
return CborToken(CborTokenType.bytesHeader, readInteger!ubyte(input));
case 0x59: // byte string (two-byte uint16_t for n, and then n bytes follow)
return CborToken(CborTokenType.bytesHeader, readInteger!ushort(input));
case 0x5a: // byte string (four-byte uint_t for n, and then n bytes follow)
return CborToken(CborTokenType.bytesHeader, readInteger!uint(input));
case 0x5b: // byte string (eight-byte uint64_t for n, and then n bytes follow)
return CborToken(CborTokenType.bytesHeader, readInteger!ulong(input));
case 0x5f: // indefinite-length byte string, byte strings follow, terminated by "break"
return CborToken(CborTokenType.bytesIndefiniteHeader);
case 0x60: .. case 0x77: // UTF-8 string (0x00..0x17 bytes follow)
return CborToken(CborTokenType.textHeader, item - 0x60);
case 0x78: // UTF-8 string (one-byte uint8_t for n, and then n bytes follow)
return CborToken(CborTokenType.textHeader, readInteger!ubyte(input));
case 0x79: // UTF-8 string (two-byte uint16_t for n, and then n bytes follow)
return CborToken(CborTokenType.textHeader, readInteger!ushort(input));
case 0x7a: // UTF-8 string (four-byte uint_t for n, and then n bytes follow)
return CborToken(CborTokenType.textHeader, readInteger!uint(input));
case 0x7b: // UTF-8 string (eight-byte uint64_t for n, and then n bytes follow)
return CborToken(CborTokenType.textHeader, readInteger!ulong(input));
case 0x7f: // indefinite-length UTF-8 string, UTF-8 strings follow, terminated by "break"
return CborToken(CborTokenType.textIndefiniteHeader);
case 0x80: .. case 0x97: // array (0x00..0x17 data items follow)
return CborToken(CborTokenType.arrayHeader, item - 0x80);
case 0x98: // array (one-byte uint8_t for n, and then n data items follow)
return CborToken(CborTokenType.arrayHeader, readInteger!ubyte(input));
case 0x99: // array (two-byte uint16_t for n, and then n data items follow)
return CborToken(CborTokenType.arrayHeader, readInteger!ushort(input));
case 0x9a: // array (four-byte uint_t for n, and then n data items follow)
return CborToken(CborTokenType.arrayHeader, readInteger!uint(input));
case 0x9b: // array (eight-byte uint64_t for n, and then n data items follow)
return CborToken(CborTokenType.arrayHeader, readInteger!ulong(input));
case 0x9f: // indefinite-length array, data items follow, terminated by "break"
return CborToken(CborTokenType.arrayIndefiniteHeader);
case 0xa0: .. case 0xb7: // map (0x00..0x17 pairs of data items follow)
return CborToken(CborTokenType.mapHeader, item - 0xa0);
case 0xb8: // map (one-byte uint8_t for n, and then n pairs of data items follow)
return CborToken(CborTokenType.mapHeader, readInteger!ubyte(input));
case 0xb9: // map (two-byte uint16_t for n, and then n pairs of data items follow)
return CborToken(CborTokenType.mapHeader, readInteger!ushort(input));
case 0xba: // map (four-byte uint_t for n, and then n pairs of data items follow)
return CborToken(CborTokenType.mapHeader, readInteger!uint(input));
case 0xbb: // map (eight-byte uint64_t for n, and then n pairs of data items follow)
return CborToken(CborTokenType.mapHeader, readInteger!ulong(input));
case 0xbf: // indefinite-length map, pairs of data items follow, terminated by "break"
return CborToken(CborTokenType.mapIndefiniteHeader);
case 0xc0: .. case 0xd7: // (tagged item)
return CborToken(CborTokenType.tag, item - 0xc0);
case 0xd8: // 1-byte tag
return CborToken(CborTokenType.tag, readInteger!ubyte(input));
case 0xd9: // 2-byte tag
return CborToken(CborTokenType.tag, readInteger!ushort(input));
case 0xda: // 4-byte tag
return CborToken(CborTokenType.tag, readInteger!uint(input));
case 0xdb: // 8-byte tag
return CborToken(CborTokenType.tag, readInteger!ulong(input));
case 0xe0: .. case 0xf3: // (simple value)
return CborToken(CborTokenType.simple, item - 0xe0);
case 0xf4: // False
return CborToken(CborTokenType.boolean, false);
case 0xf5: // True
return CborToken(CborTokenType.boolean, true);
case 0xf6: // Null
return CborToken(CborTokenType.nil);
case 0xf7: // Undefined
return CborToken(CborTokenType.undefined);
case 0xf8: // (simple value, one byte follows)
return CborToken(CborTokenType.simple, readInteger!ubyte(input));
case 0xf9: // Half-Precision Float (two-byte IEEE 754)
ushort u = readInteger!ushort(input);
return CborToken(CborTokenType.floating, halfToFloat(u));
case 0xfa: // Single-Precision Float (four-byte IEEE 754)
__FloatRep fr = {u : readInteger!uint(input)};
return CborToken(CborTokenType.floating, fr.f);
case 0xfb: // Double-Precision Float (eight-byte IEEE 754)
__DoubleRep dr = {u : readInteger!ulong(input)};
return CborToken(CborTokenType.floating, dr.d);
case 0xff: // "break" stop code
return CborToken(CborTokenType.breakCode);
default:
onUnsupportedTag(item);
}
assert(false);
}
//------------------------------------------------------------------------------
// DDDDD EEEEEEE SSSSS EEEEEEE RRRRRR IIIII AAA LL IIIII ZZZZZ EEEEEEE
// DD DD EE SS EE RR RR III AAAAA LL III ZZ EE
// DD DD EEEEE SSSSS EEEEE RRRRRR III AA AA LL III ZZ EEEEE
// DD DD EE SS EE RR RR III AAAAAAA LL III ZZ EE
// DDDDDD EEEEEEE SSSSS EEEEEEE RR RR IIIII AA AA LLLLLLL IIIII ZZZZZ EEEEEEE
//------------------------------------------------------------------------------
// If duplicate is true then dups incoming byte arrays and utf-8 string.
// If duplicate is false and input is array, then resulting byte arrays (ubyte[]) and
// utf-8 strings (char[], string) are slices of the input range.
void decodeCbor(
Flag!"Duplicate" duplicate = Yes.Duplicate,
Flag!"Flatten" flatten = No.Flatten,
R,
T)
(auto ref R input, ref T outValue)
if(isInputRange!R && is(ElementType!R == ubyte))
{
import std.typecons : isTuple;
CborToken token;
static if (isIntegral!T) {
token = decodeCborToken(input);
if (token.type == CborTokenType.neginteger) {
outValue = cast(T)token.integer;
return;
} else if (token.type == CborTokenType.posinteger) {
outValue = cast(T)token.uinteger;
return;
}
onCastErrorToFrom!T(token.type);
} else static if (isSomeChar!T) {
token = decodeCborToken(input);
if (token.type == CborTokenType.posinteger) {
outValue = cast(T)token.uinteger;
return;
}
onCastErrorToFrom!T(token.type);
} else static if (isFloatingPoint!T) {
token = decodeCborToken(input);
if (token.type == CborTokenType.floating) {
outValue = cast(T)token.floating;
return;
}
onCastErrorToFrom!T(token.type);
} else static if (isBoolean!T) {
token = decodeCborToken(input);
if (token.type == CborTokenType.boolean) {
outValue = token.boolean;
return;
}
onCastErrorToFrom!T(token.type);
} else static if ((isArray!T || isOutputRange!(T, ubyte)) && is(Unqual!(ElementType!T) == ubyte)) {
decodeCborExactByteArray!(duplicate, flatten)(input, outValue);
return;
} else static if (isArray!T && isSomeChar!(Unqual!(ElementEncodingType!T))) {
decodeString!(duplicate, flatten)(input, outValue);
return;
} else static if (isArray!T) {
decodeSequence!(duplicate, flatten)(input, outValue);
return;
} else static if (is(T == class) || is(T == struct) || isTuple!T) {
decodeAggregate!(duplicate, flatten)(input, outValue);
return;
} else static if (isAssociativeArray!T) {
token = decodeCborToken(input);
if (token.type == CborTokenType.nil) {
outValue = null;
return;
}
alias K = typeof(T.init.keys[0]);
alias V = typeof(T.init.values[0]);
if (token.type == CborTokenType.mapHeader) {
foreach (_; 0..token.uinteger) {
K key;
V value;
decodeCbor!(duplicate, flatten)(input, key);
decodeCbor!(duplicate, flatten)(input, value);
outValue[key] = value;
}
} else if (token.type == CborTokenType.mapIndefiniteHeader) {
while (true) {
token = decodeCborToken(input.save);
if (token.type == CborTokenType.breakCode) {
break;
} else {
K key;
V value;
decodeCbor!(duplicate, flatten)(input, key);
decodeCbor!(duplicate, flatten)(input, value);
outValue[key] = value;
}
}
}
return;
} else {
static assert(false, "Unable to decode " ~ T.stringof);
}
assert(false);
}
private void decodeString(
Flag!"Duplicate" duplicate = Yes.Duplicate,
Flag!"Flatten" flatten = No.Flatten,
R,
T)
(auto ref R input, ref T outValue)
if(isInputRange!R && is(ElementType!R == ubyte))
{
enum bool flat = needsFlattening!(T, flatten);
static if (flat)
{
static assert(isStaticArray!T, "Only static arrays can be flat");
ubyte[] bytes = readBytes(input, T.length);
readStaticString(bytes, outValue);
return;
}
else
{
CborToken token = decodeCborToken(input);
bool definite = !(token.type & 0b001);
if (definite) {
static if (isDynamicArray!T)
{
ubyte[] bytes = readBytes(input, cast(size_t)token.uinteger);
outValue = to!T(cast(char[])bytes);
static if (is(Unqual!(ElementEncodingType!T) == ubyte) && duplicate)
outValue = outValue.dup; // TODO allocation
return;
}
else static if (isStaticArray!T)
{
ubyte[] bytes = readBytes(input, cast(size_t)token.uinteger);
if (bytes.length != T.length) onCastErrorToFrom!T(token.type);
readStaticString(bytes, outValue);
return;
}
}
else
{
static if (isDynamicArray!T)
{
alias Unqualified = Unqual!(ElementEncodingType!T)[];
Unqualified output;
size_t i;
while (true) {
token = decodeCborToken(input.save);
if (token.type == CborTokenType.breakCode) {
import std.range : dropExactly;
dropExactly(input, 1);
break;
} else {
decodeCborToken(input);
if (token.type != CborTokenType.textHeader)
throw new CborException(format("Expected textHeader but got %s", token.type));
output.length += cast(size_t)token.uinteger - (output.length - i); // TODO allocation
ubyte[] innerBytes = readBytes(input, token.uinteger);
i += readStaticString(innerBytes, output[i..$]);
}
}
output.length = i;
outValue = cast(T)output;
return;
}
else static if (isStaticArray!T)
assert(false, "TODO");
}
assert(false, "TODO");
}
}
private size_t readStaticString(T)(ubyte[] bytes, auto ref T outValue)
{
static if (is(Unqual!(ElementEncodingType!T) == char))
{
outValue[] = cast(ElementEncodingType!T[])(bytes[]);
return bytes.length;
}
else
{
import std.utf : byChar, byWchar, byDchar;
alias V = Unqual!(ElementEncodingType!T);
static if (is(V == char))
alias byElem = byChar;
else static if (is(V == wchar))
alias byElem = byWchar;
else static if (is(V == dchar))
alias byElem = byDchar;
size_t i;
foreach(c; byElem(cast(char[])bytes)) {
outValue[i] = c;
++i;
}
return i;
}
}
private void decodeSequence(
Flag!"Duplicate" duplicate = Yes.Duplicate,
Flag!"Flatten" flatten = No.Flatten,
R,
T)
(auto ref R input, ref T outValue)
if(isInputRange!R && is(ElementType!R == ubyte))
{
enum bool flat = needsFlattening!(T, flatten);
enum bool dynamicArray = isDynamicArray!T;
enum bool staticArray = isStaticArray!T;
enum bool range = !(staticArray || dynamicArray);
//------------------------------------------------------------------------------
// Flat. Without header. Read only elements.
static if (flat)
{
static assert(isStaticArray!T, "Only static arrays can be flat");
foreach (ref elem; outValue)
decodeCbor!(duplicate, flatten)(input, elem);
return;
}
else
{
//------------------------------------------------------------------------------
// non-flat. Read header.
CborToken token = decodeCborToken(input);
bool definite = !(token.type & 0b001);
if (definite) {
static if (dynamicArray)
{
ulong lengthToRead = token.uinteger;
checkArraySize(lengthToRead);
if (outValue.length != cast(size_t)lengthToRead)
outValue.length = cast(size_t)token.uinteger;
foreach (ref elem; outValue)
decodeCbor!(duplicate, flatten)(input, elem);
return;
}
else static if (staticArray)
{
foreach (ref elem; outValue)
decodeCbor!(duplicate, flatten)(input, elem);
return;
}
}
else // indefinite
{
static if (dynamicArray)
{
alias Unqualified = Unqual!(ElementEncodingType!T)[];
Unqualified output;
output.length = 1;
size_t i;
while (true) {
token = decodeCborToken(input.save);
if (token.type == CborTokenType.breakCode) {
import std.range : dropExactly;
dropExactly(input, 1);
break;
} else {
if (output.length == i)
output.length = output.length * 2; // TODO allocation
decodeCbor!(No.Duplicate, flatten)(input, output[i]);
}
++i;
}
output.length = i;
outValue = cast(T)output;
return;
}
else static if (staticArray)
assert(false, "TODO");
}
assert(false, "TODO");
}
}
private void decodeCborExactByteArray(
Flag!"Duplicate" duplicate = Yes.Duplicate,
Flag!"Flatten" flatten = No.Flatten,
R,
T)
(auto ref R input, ref T outValue)
if(isInputRange!R && is(ElementType!R == ubyte))
{
static if (needsFlattening!(T, flatten))
{
outValue[] = cast(ElementEncodingType!T[])(readBytes(input, T.length));
return;
}
else
{
CborToken token = decodeCborToken(input);
if (token.type == CborTokenType.bytesHeader)
{
ubyte[] data = readBytes(input, token.uinteger);
static if (isDynamicArray!T) {
outValue = cast(T)data;
static if (duplicate)
outValue = outValue.dup;
} else static if (isStaticArray!T) {
if (data.length != T.length)
onCastErrorToFrom!T(token.type);
outValue[] = data;
} else {
static assert(false);
}
return;
}
else if (token.type == CborTokenType.bytesIndefiniteHeader)