-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcbor.pas
2421 lines (2065 loc) · 73.3 KB
/
cbor.pas
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
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2019, Michael R. . All rights reserved.
// ####
// #### Unless required by applicable law or agreed to in writing, software
// #### distributed under the License is distributed on an "AS IS" BASIS,
// #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// #### See the License for the specific language governing permissions and
// #### limitations under the License.
// ###################################################################
unit cbor;
// conversion of cbor encoded data to a TCborItem
// note: there is no tagging yet implemented!!
// note: if the items are used as a map only whereas the
// names are all UTF8Strings a conversion "ToString" brings a
// nice valid JSON string conversion of the items.
// the decoding handles unknown "simple" values (maj type 7) as simple
// integer values.
// the library uses some stuff from the indy project namely the base64 encoders/decoders
// a limitation of this little library is that the negivative number actually uses an
// int64 to encode the negative values -> negative values below -2^63 will raise exceptions
// simple value opcode `$f7 is not implemented -> it's undefined in the original RFC
interface
uses SysUtils, Classes, Contnrs;
type
ECBorNotImplmented = class(Exception);
ECborDecodeError = class(Exception);
const cCborSerializationTag : Array[0..2] of byte = ($D9, $D9, $F7);
// major cbor types. Note major type 7 actually is the "simple" value type with subtype
// floating point, null and boolean
type
TCBORType = ( majUnsignedInt = 0, majNegInt = 1, majByteStr = 2, majUTFEncStr = 3,
majArray = 4, majMap = 5, majTag = 6, majFloat = 7 );
type
// object list for arrays and maps
TCborItemList = class;
// base class
TCborItem = class(TObject)
private
fCBORType : TCBORType; // determines which field is valid
public
property CBorType : TCBORType read fCBORType;
procedure CBOREncode( toStream : TStream ); virtual; abstract;
function ToString : string; override;
end;
// ############################################
// #### integral types (pos neg integers)
TCborUINTItem = class(TCborItem)
private
fuIntVal : UInt64;
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Value : UInt64 read fUIntVal;
constructor Create( uVal : UInt64 );
end;
TCborNegIntItem = class(TCborItem)
private
fnegIntVal : Int64;
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Value : Int64 read fnegIntVal;
// needs to be negative!!!
constructor Create( negVal : Int64 );
end;
// binary data
TCborByteString = class(TCborItem)
private
fbyteStr : RawByteString;
public
function ToString : string; override;
procedure CBOREncode( toStream : TStream ); override;
function ToBytes : TBytes;
property Value : RawByteString read fbyteStr;
constructor Create( str : RawByteString );
end;
// utf8 strings
TCborUtf8String = class(TCborItem)
private
futfStr : UTF8String;
function EscapeJSON( jsonString : string ) : string;
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Value : UTF8String read futfStr;
constructor Create( str : UTF8String );
end;
// #########################################################
// #### Arrays and dictionaries (map)
TCborArr = class(TCborItem)
private
farr : TCborItemList;
function GetCount: integer;
function GetItem(index: integer): TCborItem;
public
procedure Add( item : TCborItem );
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Count : integer read GetCount;
property Items[ index : integer ] : TCborItem read GetItem; default;
constructor Create;
destructor Destroy; override;
end;
TCborMap = class(TCborItem)
private
// map
fNames : TCborItemList;
fvalue : TCborItemList;
function GetCount: integer;
function GetName(index: integer): TCborItem;
function GetValue(index: integer): TCborItem;
function GetValueByName(name: string): TCborItem;
public
procedure Add( name : TCborItem; value : TCborItem );
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
function IndexOfName( name : string ) : integer;
property Count : integer read GetCount;
property Names[ index : integer ] : TCborItem read GetName;
property Values[ index : integer ] : TCborItem read GetValue;
property ValueByName[ name : string ] : TCborItem read GetValueByName;
constructor Create;
destructor Destroy; override;
end;
// ################################################
// #### floating point and simple numbers
TCborFloat = class(TCborItem)
private
ffloatVal : double;
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Value : double read ffloatVal;
constructor Create( val : Double );
end;
// major type 7 (float) simple types
TCborBoolean = class(TCborItem)
private
fBoolVal : boolean;
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Value : boolean read fBoolVal;
constructor Create( val : boolean );
end;
TCborNULL = class(TCborItem)
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
constructor Create;
end;
TCborSimpleValue = class(TCborItem)
private
fSimpleVal : byte;
public
procedure CBOREncode( toStream : TStream ); override;
function ToString : string; override;
property Value : byte read fSimpleVal;
constructor Create( aVal : byte );
end;
// #########################################################
// #### Helper list class for maps and arrays
TCborItemList = class(TObjectList)
private
function GetCBORItem(index: integer): TCborItem;
public
property Items[ index : integer ] : TCborItem read GetCBORItem; default;
procedure Encode( toStream : TStream );
constructor Create;
end;
// #####################################################################
// #### Encoding/Decoding
// #####################################################################
type
TCborDecoding = class(TObject)
private
type
TCBORdecodeFunc = function( stream : TStream ) : TCborItem;
protected
class var cborDecodeTbl : Array[0..255] of TCBORdecodeFunc;
class procedure InitDecodeTable;
public
// decoding a stream (e.g. file)
class function Decode( stream : TStream; checkForCeborMagicNr : boolean = False ) : TCborItem;
// naked pointer based decoding
class function DecodeData( data : PByte; len : integer ) : TCborItem; overload;
class function DecodeData( data : RawByteString ) : TCborItem; overload;
class function DecodeData( data : PByte; len : integer; var bytesDecoded : integer ) : TCborItem; overload;
class function DecodeData( data : RawByteString; var bytesDecoded : integer ) : TCborItem; overload;
// base64 data or base634url encoded data
class function DecodeBase64( data : String ) : TCborItem;
class function DecodeBase64Url( data : String ) : TCborItem;
class function DecodeBase64UrlEx( data : string; var restBuffer : TBytes ) : TCborItem;
end;
function Base64Decode( s : string ) : RawByteString;
function Base64DecodeToBytes( s : string ) : TBytes;
function Base64URLDecode( s : String ) : RawByteString;
function Base64URLDecodeToBytes( s : String ) : TBytes;
function Base64URLEncode( aData : String ) : string; overload;
function Base64URLEncode( aData : RawByteString ) : String; overload;
function Base64URLEncode( aData : TBytes ) : String; overload;
function Base64URLEncode( pData : PByte; len : integer ) : string; overload;
function Base64Encode( aData : RawByteString ) : String; overload;
function Base64Encode( pData : PByte; len : integer ) : string; overload;
function Base64UrlFixup(base64Str: string): string;
implementation
uses Math, idCoderMime, StrUtils;
const cCBORTypeMask = $E0;
cCBORValMask = $1F;
cCBORBreak = $ff;
// ###############################################################
// #### BASE64 auxilary functions
// ###############################################################
// wrapper around a pointer + length variabl that does not alter the content
// but allows to access the pointer as stream
type
TWrapMemoryStream = class(TCustomMemoryStream)
public
function Write(const Buffer; Count: Longint): Longint; override;
constructor Create(aData : Pointer; len : integer);
end;
{ TWrapMemoryStream }
constructor TWrapMemoryStream.Create(aData: Pointer; len: integer);
begin
inherited Create;
SetPointer(aData, len);
end;
function TWrapMemoryStream.Write(const Buffer; Count: Integer): Longint;
begin
raise Exception.Create('Not allowed');
end;
function Base64UrlFixup(base64Str: string): string;
var sFixup : string;
i : integer;
begin
// url encoding
sFixup := stringReplace(base64Str, '+', '-', [rfReplaceAll]);
sFixup := StringReplace(sfixup, '/', '_', [rfReplaceAll]);
// strip the '='
i := Length(sFixup);
while (i > 0) and (sfixup[i] = '=') do
begin
delete(sFixup, i, 1);
dec(i);
end;
Result := sFixup;
end;
// this function uses the standard base64 encoding and basically strips the
// trailing == as well as changes the '+' and '/' elemets (uri compatiblilty)
function Base64URLEncode( aData : RawByteString ) : String;
begin
Result := Base64URLEncode( PByte( PAnsiChar( aData ) ), Length(aData) );
end;
function Base64URLEncode( aData : TBytes ) : String; overload;
begin
Result := Base64URLEncode( @aData[0], Length(aData) );
end;
function Base64URLEncode( aData : String ) : string; overload;
var s : UTF8String;
begin
s := UTF8String(aData);
Result := '';
if s <> '' then
Result := Base64URLEncode( @s[1], Length(s) );
end;
function Base64URLEncode( pData : PByte; len : integer ) : string;
var sFixup : string;
wrapMem : TWrapMemoryStream;
begin
if len = 0 then
exit('');
wrapMem := TWrapMemoryStream.Create( pData, len );
try
with TIdEncoderMIME.Create(nil) do
try
sFixup := Encode( wrapMem );
finally
Free;
end;
finally
wrapMem.Free;
end;
Result := Base64UrlFixup(sFixup);
end;
function Base64Encode( aData : RawByteString ) : String;
begin
Result := Base64Encode( PByte( PAnsiChar( aData ) ), length(aData) );
end;
function Base64Encode( pData : PByte; len : integer ) : string;
var wrapMem : TWrapMemoryStream;
begin
wrapMem := TWrapMemoryStream.Create( pData, len );
try
with TIdEncoderMIME.Create(nil) do
try
Result := Encode( wrapMem );
finally
Free;
end;
finally
wrapMem.Free;
end;
end;
function Base64Decode( s : string ) : RawByteString;
var aWrapStream : TWrapMemoryStream;
sconvStr : UTF8String;
lStream : TMemoryStream;
begin
sConvStr := UTF8String( s );
aWrapStream := TWrapMemoryStream.Create( @sConvStr[1], Length(sConvStr) );
lStream := TMemoryStream.Create;
try
with TIdDecoderMIME.Create(nil) do
try
DecodeBegin(lStream);
Decode( aWrapStream );
DecodeEnd;
SetLength(Result, lStream.Size );
if lStream.Size > 0 then
Move( PByte(lStream.Memory)^, Result[1], lStream.Size);
finally
Free;
end;
finally
lStream.Free;
end;
aWrapStream.Free;
end;
function Base64DecodeToBytes( s : string ) : TBytes;
var aWrapStream : TWrapMemoryStream;
sconvStr : UTF8String;
lStream : TMemoryStream;
begin
sConvStr := UTF8String( s );
aWrapStream := TWrapMemoryStream.Create( @sConvStr[1], Length(sConvStr) );
lStream := TMemoryStream.Create;
try
with TIdDecoderMIME.Create(nil) do
try
DecodeBegin(lStream);
Decode( aWrapStream );
DecodeEnd;
SetLength(Result, lStream.Size );
if lStream.Size > 0 then
Move( PByte(lStream.Memory)^, Result[0], lStream.Size);
finally
Free;
end;
finally
lStream.Free;
end;
aWrapStream.Free;
end;
function Base64URLDecode( s : String ) : RawByteString;
var sFixup : string;
aWrapStream : TWrapMemoryStream;
sconvStr : UTF8String;
lStream : TMemoryStream;
begin
if s = '' then
exit('');
// fixup
sfixup := String(s) + StringOfChar( '=', (4 - Length(s) mod 4) mod 4 );
sFixup := stringReplace(sfixup, '-', '+', [rfReplaceAll]);
sFixup := StringReplace(sfixup, '_', '/', [rfReplaceAll]);
sConvStr := UTF8String( sFixup );
aWrapStream := TWrapMemoryStream.Create( @sConvStr[1], Length(sConvStr) );
lStream := TMemoryStream.Create;
try
with TIdDecoderMIME.Create(nil) do
try
DecodeBegin(lStream);
Decode( aWrapStream );
DecodeEnd;
SetLength(Result, lStream.Size );
if lStream.Size > 0 then
Move( PByte(lStream.Memory)^, Result[1], lStream.Size);
finally
Free;
end;
finally
lStream.Free;
end;
aWrapStream.Free;
end;
function Base64URLDecodeToBytes( s : String ) : TBytes;
var res : RawByteString;
begin
res := Base64URLDecode( s );
Result := nil;
if res <> '' then
begin
SetLength(Result, Length(res));
Move( Res[1], Result[0], Length(Res));
end;
end;
// ##########################################################
// #### float 16 bit conversion from single and back
// ##########################################################
// based on: https://galfar.vevb.net/wp/2011/16bit-half-float-in-pascaldelphi/
function FloatToHalf(Float: Single): Word;
var Src: LongWord;
Sign, Exp, Mantissa: LongInt;
begin
Src := PLongWord(@Float)^;
// Extract sign, exponent, and mantissa from Single number
Sign := Src shr 31;
Exp := LongInt((Src and $7F800000) shr 23) - 127 + 15;
Mantissa := Src and $007FFFFF;
if (Exp > 0) and (Exp < 30)
then
// Simple case - round the significand and combine it with the sign and exponent
Result := (Sign shl 15) or (Exp shl 10) or ((Mantissa + $00001000) shr 13)
else if Src = 0
then
// Input float is zero - return zero
Result := 0
else
begin
// Difficult case - lengthy conversion
if Exp <= 0 then
begin
if Exp < -10
then
// Input float's value is less than HalfMin, return zero
Result := 0
else
begin
// Float is a normalized Single whose magnitude is less than HalfNormMin.
// We convert it to denormalized half.
Mantissa := (Mantissa or $00800000) shr (1 - Exp);
// Round to nearest
if (Mantissa and $00001000) > 0 then
Mantissa := Mantissa + $00002000;
// Assemble Sign and Mantissa (Exp is zero to get denormalized number)
Result := (Sign shl 15) or (Mantissa shr 13);
end;
end
else if Exp = 255 - 127 + 15 then
begin
if Mantissa = 0
then
// Input float is infinity, create infinity half with original sign
Result := (Sign shl 15) or $7C00
else
// Input float is NaN, create half NaN with original sign and mantissa
Result := (Sign shl 15) or $7C00 or (Mantissa shr 13);
end
else
begin
// Exp is > 0 so input float is normalized Single
// Round to nearest
if (Mantissa and $00001000) > 0 then
begin
Mantissa := Mantissa + $00002000;
if (Mantissa and $00800000) > 0 then
begin
Mantissa := 0;
Exp := Exp + 1;
end;
end;
if Exp > 30 then
begin
// Exponent overflow - return infinity half
Result := (Sign shl 15) or $7C00;
end
else
// Assemble normalized half
Result := (Sign shl 15) or (Exp shl 10) or (Mantissa shr 13);
end;
end;
end;
function HalfToFloat(Half: word): Single;
var Dst, Sign, Mantissa: LongWord;
Exp: LongInt;
begin
// Extract sign, exponent, and mantissa from half number
Sign := Half shr 15;
Exp := (Half and $7C00) shr 10;
Mantissa := Half and 1023;
if (Exp > 0) and (Exp < 31) then
begin
// Common normalized number
Exp := Exp + (127 - 15);
Mantissa := Mantissa shl 13;
Dst := (Sign shl 31) or (LongWord(Exp) shl 23) or Mantissa;
// Result := Power(-1, Sign) * Power(2, Exp - 15) * (1 + Mantissa / 1024);
end
else if (Exp = 0) and (Mantissa = 0) then
begin
// Zero - preserve sign
Dst := Sign shl 31;
end
else if (Exp = 0) and (Mantissa <> 0) then
begin
// Denormalized number - renormalize it
while (Mantissa and $00000400) = 0 do
begin
Mantissa := Mantissa shl 1;
Dec(Exp);
end;
Inc(Exp);
Mantissa := Mantissa and not $00000400;
// Now assemble normalized number
Exp := Exp + (127 - 15);
Mantissa := Mantissa shl 13;
Dst := (Sign shl 31) or (LongWord(Exp) shl 23) or Mantissa;
// Result := Power(-1, Sign) * Power(2, -14) * (Mantissa / 1024);
end
else if (Exp = 31) and (Mantissa = 0) then
begin
// +/- infinity
Dst := (Sign shl 31) or $7F800000;
end
else //if (Exp = 31) and (Mantisa <> 0) then
begin
// Not a number - preserve sign and mantissa
Dst := (Sign shl 31) or $7F800000 or (Mantissa shl 13);
end;
// Reinterpret LongWord as Single
Result := PSingle(@Dst)^;
end;
// reads a byte from the stream and reverst the position
function PeekFromStream( stream : TStream; var buf : byte ) : byte;
begin
stream.ReadBuffer(buf, sizeof(Buf));
stream.Seek(-sizeof(buf), soCurrent);
Result := buf;
end;
// cbor uses network byte order which maps to the just inverse byte order for intel machines
procedure RevertByteOrder( stream : PByte; numBytes : integer);
var i: Integer;
pEnd : PByte;
tmp : byte;
begin
pEnd := stream;
inc(pEnd, numBytes - 1);
for i := 0 to numBytes div 2 - 1 do
begin
tmp := stream^;
stream^ := pEnd^;
pEnd^ := tmp;
inc(stream);
dec(pEnd);
end;
end;
// #################################################################
// #### cbor decoder
// #################################################################
class function TCborDecoding.Decode(stream: TStream; checkForCeborMagicNr : boolean = False): TCborItem;
var opCode : Byte;
hea : Array[0..2] of byte;
begin
InitDecodeTable;
Result := nil;
if (stream = nil) then
exit;
if checkForCeborMagicNr then
begin
stream.ReadBuffer(hea, sizeof(hea));
// if no serialization header indicator is found just try the standard decoding
if not CompareMem( @hea[0], @cCborSerializationTag[0], sizeof(cCborSerializationTag) ) then
stream.Seek(-sizeof(cCborSerializationTag), soCurrent);
end;
PeekFromStream(stream, opCode);
Result := cborDecodeTbl[ opCode ](stream);
end;
class function TCborDecoding.DecodeData(data: PByte;
len: integer): TCborItem;
var dummy : integer;
begin
Result := DecodeData(data, len, dummy);
end;
class function TCborDecoding.DecodeData(data: RawByteString;
var bytesDecoded: integer): TCborItem;
begin
Result := DecodeData( PByte( PAnsiChar( data ) ), Length(data), bytesDecoded );
end;
class function TCborDecoding.DecodeData(data: PByte; len: integer;
var bytesDecoded: integer): TCborItem;
var memStream : TWrapMemoryStream;
begin
memStream := TWrapMemoryStream.Create(data, len);
try
Result := Decode(memStream);
bytesDecoded := Integer(memStream.Position);
finally
memStream.Free;
end;
end;
class function TCborDecoding.DecodeData(data: RawByteString): TCborItem;
begin
Result := DecodeData( PByte( PAnsiChar( data ) ), Length(data) );
end;
class function TCborDecoding.DecodeBase64(data: String): TCborItem;
var decoded : RawByteString;
begin
decoded := Base64Decode(data);
Result := nil;
if decoded <> '' then
Result := DecodeData( PByte(PAnsiChar(decoded)), Length(decoded));
end;
class function TCborDecoding.DecodeBase64Url(data: String): TCborItem;
var decoded : RawByteString;
i: integer;
begin
decoded := Base64URLDecode(data);
Result := nil;
with TStringStream.Create('') do
try
for i := 1 to Length(decoded) do
WriteString(IntToHex( Byte( decoded[i]), 2 ) + ' ' );
SaveToFile('d:\cbor_attestObj.txt');
finally
Free;
end;
if decoded <> '' then
Result := DecodeData( PByte(PAnsiChar(decoded)), Length(decoded));
end;
class function TCborDecoding.DecodeBase64UrlEx(data: string;
var restBuffer: TBytes): TCborItem;
var decoded : RawByteString;
bytesDecoded : integer;
begin
decoded := Base64URLDecode(data);
Result := nil;
bytesDecoded := 0;
if decoded <> '' then
Result := DecodeData( PByte(PAnsiChar(decoded)), Length(decoded), bytesDecoded);
SetLength( restBuffer, length(decoded) - bytesDecoded );
if Length(restBuffer) > 0 then
Move( decoded[bytesDecoded], restBuffer[0], Length(restBuffer));
end;
// ##############################################################
// #### cbor objects
// ##############################################################
{ TCborFloat }
constructor TCborFloat.Create(val: Double);
begin
inherited Create;
fCBORType := majFloat;
ffloatVal := val;
end;
function TCborFloat.ToString: string;
var fmt : TFormatSettings;
begin
{$IF (CompilerVersion <= 21)}
GetLocaleFormatSettings(0, fmt);
{$ELSE}
fmt := TFormatSettings.Create;
{$IFEND}
fmt.DecimalSeparator := '.';
Result := FormatFloat( '%f', fFloatVal, fmt);
end;
procedure TCborFloat.CBOREncode(toStream: TStream);
var opCode : Byte;
val : Double;
sVal : single;
dVal : double;
wVal : Word;
wtoSval : single;
begin
val := ffloatVal;
sVal := ffloatVal; // simply cast to single and back to double -> if it's the same we use single
dVal := sVal;
wVal := FloatToHalf( sVal );
wtoSVal := HalfToFloat( wVal );
// needs double encoding?
if ffloatVal <> dVal then
begin
RevertByteOrder(@val, sizeof(val));
// write double
opCode := $FB;
toStream.WriteBuffer(opCode, sizeof(opCode));
toStream.WriteBuffer(val, sizeof(val));
end // 16bit float sufficient?
else if wtoSVal = sVal then
begin
RevertByteOrder( @wVal, sizeof(wVal));
// write half single
opcode := $F9;
toStream.WriteBuffer(opCode, sizeof(opcode));
toStream.WriteBuffer(wval, sizeof(wVal));
end
else
begin
RevertByteOrder(@sVal, sizeof(sVal));
// write single
opCode := $FA;
toStream.WriteBuffer(opCode, sizeof(opCode));
toStream.WriteBuffer(sval, sizeof(sval));
end;
end;
{ TCborMap }
constructor TCborMap.Create;
begin
inherited Create;
fCBORType := majMap;
fNames := TCborItemList.Create;
fvalue := TCborItemList.Create;
end;
procedure TCborMap.Add(name, value: TCborItem);
begin
fNames.Add(name);
fvalue.Add(value);
end;
destructor TCborMap.Destroy;
begin
fNames.Free;
fvalue.Free;
inherited;
end;
function TCborMap.ToString: string;
var i: Integer;
begin
Result := '{';
for i := 0 to fNames.Count - 1 do
begin
Result := Result + ifthen(fNames[i] is TCborUtf8String, '', '"') +
fNames[i].ToString +
ifthen(fNames[i] is TCborUtf8String, '', '"') +
':' + fvalue[i].ToString;
if i <> fNames.Count - 1 then
Result := Result + ',';
end;
Result := Result + '}';
end;
procedure TCborMap.CBOREncode(toStream: TStream);
var len : int64;
opCode : Byte;
bLen : Byte;
wLen : word;
dwLen : LongWord;
i : Integer;
begin
len := fNames.Count;
if len <= $17 then
begin
opCode := Byte($A0 + len);
toStream.WriteBuffer(opCode, sizeof(opCode));
end
else if len <= High(Byte) then
begin
opCode := $B8;
toStream.WriteBuffer(opCode, sizeof(opCode));
bLen := Byte(len);
toStream.WriteBuffer(bLen, sizeof(bLen));
end
else if len <= High(Word) then
begin
opCode := $B9;
toStream.WriteBuffer(opCode, sizeof(opCode));
wLen := Word(len);
RevertByteOrder( @wLen, sizeof(wLen));
toStream.WriteBuffer(wLen, sizeof(wLen));
end
else if len <= High(LongWord) then
begin
opCode := $BA;
toStream.WriteBuffer(opCode, sizeof(opCode));
dwLen := LongWord(len);
RevertByteOrder( @dwLen, sizeof(dwLen));
toStream.WriteBuffer(dwLen, sizeof(dwLen));
end
else
raise Exception.Create('To long list...!');
for i := 0 to fNames.Count - 1 do
begin
fNames[i].CBOREncode(toStream);
fvalue[i].CBOREncode(toStream);
end;
end;
function TCborMap.GetCount: integer;
begin
Result := fNames.Count;
end;
function TCborMap.GetName(index: integer): TCborItem;
begin
Result := fNames[index];
end;
function TCborMap.GetValue(index: integer): TCborItem;
begin
Result := fvalue[index];
end;
function TCborMap.GetValueByName(name: string): TCborItem;
var i: Integer;
begin
// works only for utf names
Result := nil;
i := IndexOfName(Name);
if i >= 0 then
Result := fValue[i];
end;
function TCborMap.IndexOfName(name: string): integer;
var i : integer;
begin
Result := -1;
for i := 0 to GetCount - 1 do
begin
if (Names[i] is TCborUtf8String) then
begin
if SameStr( String((Names[i] as TCborUtf8String).Value), name) then
begin
Result := i;
break;
end;
end
else if (Names[i] is TCborUINTItem) then
begin
if name = IntToStr( (Names[i] as TCborUINTItem).Value ) then
begin
Result := i;
break;
end;
end
else if (Names[i] is TCborNegIntItem) then
begin
if name = IntToStr( (Names[i] as TCborNegIntItem).Value ) then
begin
Result := i;
break;
end;
end;
end;
end;
{ TCborArr }
constructor TCborArr.Create;
begin
inherited Create;
fCBORType := majArray;
farr := TCborItemList.Create;
end;
procedure TCborArr.Add(item: TCborItem);
begin
farr.Add(item);
end;
destructor TCborArr.Destroy;
begin
farr.Free;
inherited;
end;