-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathbsonTools.pas
1247 lines (1196 loc) · 32.8 KB
/
bsonTools.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
{
TMongoWire: bsonTools.pas
Copyright 2010-2018 Stijn Sanders
Made available under terms described in file "LICENSE"
https://github.com/stijnsanders/TMongoWire
v1.1.1
}
unit bsonTools;
{$WARN SYMBOL_PLATFORM OFF}
{$D-}
{$L-}
interface
uses
ComObj, SysUtils, Classes, jsonDoc;
const
//special prefix with unassigned(?) unicode symbols from the Special range
bsonJavaScriptCodePrefix:WideString=#$FFF1'bsonJavaScriptCode'#$FFF2;
bsonRegExPrefix:WideString=#$FFF1'bsonRegEx'#$FFF2; //see also $IFDEF BSON_SUPPORT_REGEX
bsonObjectIDPrefix:WideString='ObjectID("';
bsonObjectIDSuffix:WideString='")';
bsonObjectID_L=36;//=Length(bsonObjectIDPrefix)+24+Length(bsonObjectIDSuffix);
IID_IBSONDocArray
: TGUID = '{42534F4E-0000-0003-C000-000000000003}';
type
IBSONDocArray=interface(IUnknown)
['{42534F4E-0000-0003-C000-000000000003}']
procedure ReadAll(Data: TStream); stdcall;
procedure WriteAll(Data: TStream); stdcall;
end;
TBSONDocArray=class(TJSONImplBaseObj, IJSONArray, IJSONDocArray,
IBSONDocArray)
private
FData:TStream;
FRef:array of integer;//int64?
FRefIndex,FRefLength:integer;
FCurrent:Variant;
function AddRef(FromSize: boolean): integer;
protected
//IJSONArray
function Get_Item(Index: integer): Variant; stdcall;
procedure Set_Item(Index: integer; const Value: Variant); stdcall;
function ItemsCount: integer; stdcall;
function JSONToString: WideString; stdcall;
function IJSONArray.ToString=JSONToString;
function IJSONDocArray.ToString=JSONToString;
function v0(Index: integer): pointer; stdcall;
property Item[Idx: integer]: Variant read Get_Item write Set_Item; default;
//IJSONDocArray
function Add(const Doc: IJSONDocument): integer; stdcall;
function AddJson(const Data: WideString): integer; stdcall;
procedure LoadItem(Index: integer; const Doc: IJSONDocument); stdcall;
procedure Clear; stdcall;
function GetJSON(Index: integer): WideString; stdcall;
//IBSONDocArray
procedure ReadAll(Data: TStream); stdcall;
procedure WriteAll(Data: TStream); stdcall;
public
constructor Create; overload;
destructor Destroy; override;
end;
function BSONDocArray: IJSONDocArray;
procedure LoadBSON(Data: TStream; const Doc: IJSONDocument);
procedure SaveBSON(const Doc: IJSONDocument; Data: TStream);
type
EBSONException=class(Exception);
implementation
uses
Windows, ActiveX,
{$IFDEF BSON_SUPPORT_REGEX}
VBScript_RegExp_55_TLB,
{$ENDIF}
Variants;
const
BSONArrayBaseIndex=0;//1?
BSONDetectVarArrayType=true;
//bsonElement
bsonDouble = $00000001;
bsonString = $00000002;
bsonEmbeddedDocument = $00000003;
bsonArray = $00000004;
bsonBinary = $00000005;
bsonObjectID = $00000007;
bsonBoolean = $00000008;
bsonUTCDateTime = $00000009;
bsonNULL = $0000000A;
bsonRegEx = $0000000B;
bsonJavaScriptCode = $0000000D;
bsonSymbol = $0000000E;
bsonJavaScriptCodeWithScope = $0000000F;
bsonInt32 = $00000010;
bsonTimestamp = $00000011;
bsonInt64 = $00000012;
bsonMinKey = $FFFFFFFF;
bsonMaxKey = $0000007F;
//bsonBinarySubType
bsonBinaryGeneric = $00;
bsonBinaryFunction = $01;
bsonBinaryBinary_old = $02;
bsonBinaryUUID_old = $03;
bsonBinaryUUID = $04;
bsonBinaryMD5 = $05;
bsonBinaryEncryptedBSON = $06;
bsonBinaryCompressedBSONColumn = $07;
bsonBinaryUserDefined = $80;
{$IF not Declared(UTF8ToWideString)}
function UTF8ToWideString(const s: UTF8String): WideString;
begin
Result:=UTF8Decode(s);
end;
{$IFEND}
function BSONDocArray:IJSONDocArray;
begin
Result:=TBSONDocArray.Create;
end;
procedure LoadBSON(Data: TStream; const Doc: IJSONDocument);
var
i,lstart,ltotal,ltmax:integer;
procedure dRead(p:pointer;s:integer);
begin
if Data.Read(p^,s)<>s then
raise EBSONException.Create('Unexpected end of stream');
inc(ltotal,s);
if ltotal>ltmax then
raise EBSONException.Create('More BSON data than declared');
end;
var //outside of stmReadCString to recycle memory
ss:AnsiString;
sx,sl:integer;
function dReadCString: WideString;
var
c:AnsiChar;
begin
sx:=0;
dRead(@c,1);
while c<>#0 do
begin
if sx=sl then
begin
inc(sl,$100);//grow in steps
SetLength(ss,sl);
end;
inc(sx);
ss[sx]:=c;
dRead(@c,1);
end;
Result:=UTF8ToWideString(Copy(ss,1,sx));
end;
function dReadString: WideString;
var
l:integer;
s:AnsiString;
begin
dRead(@l,4);
if l<2 then s:='' else
begin
SetLength(s,l-1);
dRead(@s[1],l-1);
end;
//read closing null
l:=0;
dRead(@l,1);
if l<>0 then
raise EBSONException.Create('BSON string incorrectly terminated at offset '+IntToHex(lstart,8));
Result:=UTF8ToWideString(s);
end;
{$IFDEF BSON_SUPPORT_REGEX}
function dReadRegEx: IRegExp2;
var
i:integer;
s:string;
begin
Result:=CoRegExp.Create;
Result.Pattern:=stmReadCString;
s:=dReadCString;
for i:=1 to Length(s)-1 do
case s[i] of
'i','I':Result.IgnoreCase:=true;
'm','M':Result.Multiline:=true;
'g','G':Result.Global:=true;
//'x','X':;//verbose
//'l','L':;//locale
//'s','S':;//dotall
//'u','U':;//unicode
else raise EBSONException.Create('Unsupported regex option "'+s+'" at offset '+IntToHex(lstart,8));
end;
end;
{$ENDIF}
const
stackGrowStep=$20;//not too much, not too little (?)
arrGrowStep=$20;
var
IsArray:boolean;
a1,ai,al:integer;
key:WideString;
d:IJSONDocument;
a:array of Variant;
at,vt:TVarType;
procedure SetValue(const v:Variant);
begin
//asset da=nil
if IsArray then
begin
if ai=al then
begin
inc(al,arrGrowStep);//not too much, not too little (?)
SetLength(a,al);
end;
a[ai]:=v;
//detect same type elements array
vt:=TVarData(v).VType;
if at=varEmpty then at:=vt else
case at of
//TODO: what with signed/unsigned mixed?
varSmallint://i2
if not(vt in [varSmallint,
varShortInt,varByte]) then at:=varVariant;
varInteger://i4
if not(vt in [varSmallint,
varInteger,varShortInt,varByte,varWord]) then at:=varVariant;
varWord:
if not(vt in [varSmallint,
varByte,varWord]) then at:=varVariant;
varLongWord:
if not(vt in [varSmallint,
varShortInt,varByte,varWord,varLongWord]) then at:=varVariant;
varInt64:
if not(vt in [varSmallint,varInteger,varShortInt,
varByte,varWord,varLongWord,varInt64]) then at:=varVariant;
varVariant:;//Already creating an VarArray of variants
//TODO: more?
else if at<>vt then at:=varVariant;
end;
inc(ai);
end
else
d[key]:=v;//TODO: v0(key)?
end;
var
stack:array of record
key:WideString;
d:IJSONDocument;
k1,k2:integer;
end;
stackIndex,stackSize:integer;
procedure Push;
begin
if stackIndex=stackSize then
begin
inc(stackSize,stackGrowStep);
SetLength(stack,stackSize);
end;
if IsArray then
begin
stack[stackIndex].d:=nil;
stack[stackIndex].k1:=a1;
stack[stackIndex].k2:=at;
end
else
begin
stack[stackIndex].key:=key;
stack[stackIndex].d:=d;
end;
inc(stackIndex);
end;
var
d1:IJSONDocument;
dr:IJSONDocWithReUse;
da:IJSONDocArray;
dz:IJSONDocument;
d0:integer;
ba:IBSONDocArray;
aa:TJSONArray;
v:Variant;
j:integer;
o:array[0..15] of byte;
ii:int64 absolute o;
dd:double absolute o;
pp:pointer absolute o;
gg:TGUID absolute o;
pv:PVariant;
const
hex:array[0..15] of char='0123456789abcdef';
begin
//Doc.Clear;? let caller decide.
ltotal:=0;
lstart:=0;
ltmax:=4;
dRead(@ltMax,4);
stackSize:=0;
stackIndex:=0;
ai:=0;
a1:=0;
al:=0;
da:=nil;
dz:=nil;
d0:=0;
IsArray:=false;
d:=Doc;
sl:=0;
ss:='';
while (ltotal<ltmax) and (stackIndex<>-1) do
begin
i:=0;
lstart:=ltotal;
dRead(@i,1);
if i<>0 then key:=dReadCString;
case i of
bsonDouble:
begin
dRead(@dd,8);
SetValue(dd);
end;
bsonString:
SetValue(dReadString);
bsonEmbeddedDocument:
begin
if IsArray then
if (da<>nil) and (d0=stackIndex) then
v:=dz //re-use keys
else
begin
if ai=al then
begin
inc(al,arrGrowStep);
SetLength(a,al);
end;
v:=JSON;
a[ai]:=v;
inc(ai);
end
else
begin
if d.QueryInterface(IID_IJSONDocWithReUse,dr)=S_OK then
begin
v:=dr.ReUse(key);
dr:=nil;
end
else
v:=Null;
if (TVarData(v).VType in [varDispatch,varUnknown]) and
(IUnknown(v).QueryInterface(IID_IJSONDocument,d1)=S_OK) then
d1:=nil
else
begin
v:=JSON;
d[key]:=v;
end;
end;
Push;
IsArray:=false;
d:=IUnknown(v) as IJSONDocument;
dRead(@i,4);//document length
//TODO: keep value and check if correct?
end;
bsonArray:
begin
if d.QueryInterface(IID_IJSONDocWithReUse,dr)=S_OK then
begin
v:=dr.ReUse(key);
dr:=nil;
if (da=nil) and (TVarData(v).VType in [varDispatch,varUnknown]) then
if IUnknown(v).QueryInterface(IID_IBSONDocArray,ba)=S_OK then
begin
i:=Data.Position;
ba.ReadAll(Data);
i:=Data.Position-i;
inc(ltotal,i-4);
if ltotal>ltmax then
raise EBSONException.Create('More BSON data than declared');
i:=0;//skip push below
end
else if IUnknown(v).QueryInterface(IID_IJSONDocArray,da)=S_OK then
begin
d0:=stackIndex+1;
if dz=nil then dz:=JSON;
end;
end;
if i=bsonArray then
begin
Push;
IsArray:=true;
a1:=ai;
at:=varEmpty;//used to detect same type elements array
dRead(@i,4);//array document length
//TODO: keep value and check if correct?
end;
end;
bsonBinary:
begin
dRead(@i,4);
dRead(@o[11],1);
//TODO: store value somewhere?
case o[11] of
bsonBinaryGeneric,bsonBinaryBinary_old,bsonBinaryUserDefined:
begin
v:=VarArrayCreate([BSONArrayBaseIndex,i-1+BSONArrayBaseIndex],varByte);
pp:=VarArrayLock(v);
try
dRead(pp,i);
finally
VarArrayUnlock(v);
end;
SetValue(v);
end;
bsonBinaryFunction:
begin
//TODO
raise EInvalidOperation.Create('bsonBinaryFunction: Not Implemented');
end;
bsonBinaryUUID_old,bsonBinaryUUID:
begin
if i<>16 then
raise EBSONException.Create('Unexpected UUID length ('+
IntToStr(i)+') at offset '+IntToHex(lstart,8));
dRead(@gg,16);
//TODO try to rig into varStrArg
SetValue(GUIDToString(gg));
end;
bsonBinaryMD5:
begin
//TODO
raise EInvalidOperation.Create('bsonBinaryMD5: Not Implemented');
end;
else
raise EBSONException.Create('Unknown BSON binary type '+
IntToHex(o[11],2)+' at offset '+IntToHex(lstart,8));
end;
end;
bsonObjectID:
begin
dRead(@o[0],12);
SetValue(bsonObjectIDPrefix+
hex[o[00] shr 4]+hex[o[00] and $F]+
hex[o[01] shr 4]+hex[o[01] and $F]+
hex[o[02] shr 4]+hex[o[02] and $F]+
hex[o[03] shr 4]+hex[o[03] and $F]+
hex[o[04] shr 4]+hex[o[04] and $F]+
hex[o[05] shr 4]+hex[o[05] and $F]+
hex[o[06] shr 4]+hex[o[06] and $F]+
hex[o[07] shr 4]+hex[o[07] and $F]+
hex[o[08] shr 4]+hex[o[08] and $F]+
hex[o[09] shr 4]+hex[o[09] and $F]+
hex[o[10] shr 4]+hex[o[10] and $F]+
hex[o[11] shr 4]+hex[o[11] and $F]+
bsonObjectIDSuffix);
end;
bsonBoolean:
begin
i:=0;
dRead(@i,1);
SetValue(boolean(i<>0));
end;
bsonUTCDateTime:
begin
dRead(@ii,8);
SetValue(VarFromDateTime(ii/MSecsPerDay+UnixDateDelta));
end;
bsonNULL:
SetValue(Null);
bsonRegEx:
begin
{$IFDEF BSON_SUPPORT_REGEX}
v:=dReadRegEx;
{$ELSE}
v:=bsonRegExPrefix+'/'+dReadCString+'/'+dReadCString;
{$ENDIF}
SetValue(v);
end;
bsonJavaScriptCode:
begin
v:=bsonJavaScriptCodePrefix+dReadString;//TODO: find active script interface?µ
SetValue(v);
end;
bsonSymbol:
begin
v:=dReadString;//?
SetValue(v);
end;
bsonJavaScriptCodeWithScope:
begin
//TODO
raise EInvalidOperation.Create('bsonJavaScriptCodeWithScope: Not Implemented');
end;
bsonInt32:
begin
dRead(@i,4);
SetValue(i);
end;
bsonTimestamp:
begin
dRead(@ii,8);
SetValue(ii);//TODO: VarFromDateTime?
end;
bsonInt64:
begin
dRead(@ii,8);
SetValue(ii);
end;
0://doc or array done
begin
if IsArray then
begin
if (da<>nil) and (d0=stackIndex) then
v:=Null
else
if JSON_UseIJSONArray then
begin
aa:=TJSONArray.Create(ai-a1);
i:=a1;
j:=0;
while i<ai do
begin
//aa[j]:=a[i];VarClear(a[i]);
pv:=(aa as IJSONArray).v0(j);
Move(a[i],pv^,SizeOf(TVarData));
ZeroMemory(@a[i],SizeOf(TVarData));
inc(i);
inc(j);
end;
v:=aa as IJSONArray;
end
else
begin
if not(VarTypeIsValidArrayType(at)) then at:=varVariant;
v:=VarArrayCreate([0,ai-a1-1],at);
i:=a1;
j:=0;
while i<ai do
begin
v[j]:=a[i];
VarClear(a[i]);
inc(i);
inc(j);
end;
end;
ai:=a1;
end
else
v:=Null;//assert d embedded document SetValue'd at start
//pop from stack
if stackIndex=0 then
begin
dec(stackIndex);//stackIndex:=-1;
end
else
begin
dec(stackIndex);
if stack[stackIndex].d=nil then
begin
a1:=stack[stackIndex].k1;
at:=stack[stackIndex].k2;
IsArray:=true;
if (da<>nil) and (d0=stackIndex) then
begin
da.AddJSON(dz.ToString);
dz.Clear;
end;
end
else
begin
d:=stack[stackIndex].d;
key:=stack[stackIndex].key;
stack[stackIndex].d:=nil;
IsArray:=false;
if (da<>nil) and (d0-1=stackIndex) then
da:=nil;//done
end;
end;
//set value
if (TVarData(v).VType<>varNull) then SetValue(v);
end;
else
raise EBSONException.Create('Unknown BSON element type '+
IntToHex(i,2)+' at offset '+IntToHex(lstart,8));
end;
end;
if stackIndex<>-1 then raise EBSONException.Create(
'BSON with '+IntToStr(stackIndex+1)+' objects or arrays not closed');
//if <>ltotal then raise?
end;
procedure SaveBSON(const Doc: IJSONDocument; Data: TStream);
var
lstart,ltotal:integer;
procedure dWrite(p:pointer;s:integer);
begin
if Data.Write(p^,s)<>s then
raise EBSONException.Create('Failed to write data to stream');
inc(ltotal,s);
end;
procedure dWriteCString(const s:WideString);
var
sx:UTF8String;
sl:integer;
begin
sx:=UTF8Encode(s);
sl:=Length(sx);
//sx:=sx+#0;
if sl=0 then
dWrite(@sl,1)
else
dWrite(@sx[1],sl+1);
end;
procedure dWriteString(const s:WideString);
var
sx:UTF8String;
sl:integer;
begin
sx:=UTF8Encode(s);
sl:=Length(sx);
inc(sl);
dWrite(@sl,4);
//sx:=sx+#0;
if sl=1 then
begin
sl:=0;
dWrite(@sl,1);
end
else
dWrite(@sx[1],sl);
end;
const
stackGrowStep=$20;//not too much, not too little (?)
var
e:IJSONEnumerator;
IsArray:boolean;
stack:array of record
e:IJSONEnumerator;
p:integer;//int64?
IsArray:boolean;
end;
stackIndex,stackLength:integer;
procedure Push(const NewEnum:IJSONEnumerator; NewIsArray:boolean);
var
i:integer;
begin
if NewIsArray then i:=bsonArray else i:=bsonEmbeddedDocument;
dWrite(@i,1);
dWriteCString(e.Key);
i:=0;
dWrite(@i,4);//don't know total length now, filled in later
//push onto stack
if stackIndex=stackLength then
begin
inc(stackLength,stackGrowStep);
SetLength(stack,stackLength);
end;
stack[stackIndex].e:=e;
stack[stackIndex].IsArray:=IsArray;
stack[stackIndex].p:=ltotal-4;
inc(stackIndex);
e:=NewEnum;
IsArray:=NewIsArray;
end;
var
uu:IUnknown;
function TryWriteJSONDocument:boolean;
var
d:IJSONDocument;
begin
Result:=uu.QueryInterface(IID_IJSONDocument,d)=S_OK;
if Result then Push(JSONEnum(d),false);
end;
function TryWriteBSONDocArray:boolean;
var
a:IBSONDocArray;
p1,p2:int64;
begin
Result:=uu.QueryInterface(IID_IBSONDocArray,a)=S_OK;
if Result then
begin
p1:=Data.Position;
a.WriteAll(Data);
p2:=Data.Position;
inc(ltotal,p2-p1);
end;
end;
function TryWriteJSONArray:boolean;
var
a:IJSONArray;
begin
Result:=uu.QueryInterface(IID_IJSONArray,a)=S_OK;
if Result then Push(TJSONArrayEnumerator.Create(a),true);
end;
{$IFDEF BSON_SUPPORT_REGEX}
function TryWriteRegExp:boolean;
var
i:integer;
w:WideString;
r:IRegExp2;
begin
Result:=uu.QueryInterface(IID_IRegExp2,r)=S_OK;
if Result then
begin
i:=bsonRegEx;
dWrite(@i,1);
dWriteCString(e.Key);
dWriteCString(r.Pattern);
w:='';
if r.Global then w:=w+'g';
if r.IgnoreCase then w:=w+'i';
if r.Multiline then w:=w+'m';
//TODO: other regex flags
dWriteCString(w);
end;
end;
{$ENDIF}
function TryWriteStream:boolean;
const
dSize=$10000;
IID_IStream:TGUID='{0000000C-0000-0000-C000-000000000046}';
var
i:integer;
p1,p2:{$IF CompilerVersion>16}UInt64{$ELSE}Int64{$IFEND};
ss:IStream;
d:array[0..dSize-1] of byte;
begin
Result:=uu.QueryInterface(IID_IStream,ss)=S_OK;
if Result then
begin
i:=bsonBinary;
dWrite(@i,1);
dWriteCString(e.Key);
//seek end to know full size
OleCheck(ss.Seek(0,soFromEnd,p1));
//TODO: check less than 2GB
//seek start for copying
OleCheck(ss.Seek(0,soFromBeginning,p2));
dWrite(@p1,4);
i:=bsonBinaryGeneric;
dWrite(@i,1);
inc(ltotal,p1);
while p1<>0 do
begin
OleCheck(ss.Read(@d[0],dSize,@i));
if i=0 then raise EBSONException.Create('Failed to read from IStream');
if Data.Write(d[0],i)<>i then
raise EBSONException.Create('Failed to write data to stream');
p1:=p1-i;
end;
end;
end;
function TryWritePersistStream:boolean;
const
IID_IPersistStream:TGUID='{00000109-0000-0000-C000-000000000046}';
var
i:integer;
p1,p2:int64;
ps:IPersistStream;
begin
Result:=uu.QueryInterface(IID_IPersistStream,ps)=S_OK;
if Result then
begin
i:=bsonBinary;
dWrite(@i,1);
dWriteCString(e.Key);
p1:=Data.Position;
i:=0;//fill in later
dWrite(@i,4);
i:=bsonBinaryGeneric;
dWrite(@i,1);
ps.Save(TStreamAdapter.Create(Data,soReference),false);
//fill in length
p2:=Data.Position;
i:=p2-p1-5;
Data.Position:=p1;
if Data.Write(i,4)<>4 then
raise EBSONException.Create('Failed to write data to stream');
Data.Position:=p2;
end;
end;
function StartsWith(const a,b:WideString):boolean;
var
i,l1,l2:integer;
begin
i:=1;
l1:=Length(a);
l2:=Length(b);
while (i<=l1) and (i<=l2) and (a[i]=b[i]) do inc(i);
Result:=i=l2+1;
end;
var
v:PVariant;
vt:TVarType;
w:WideString;
i,j,wl:integer;
o:array[0..15] of byte;
ii:int64 absolute o;
gg:TGUID absolute o;
dd:double absolute o;
pp:pointer absolute o;
bb:byte;
begin
stackIndex:=0;
stackLength:=0;
lstart:=Data.Position;//may not be 0!
ltotal:=0;
i:=0;//write now, fill in later
dWrite(@i,4);
e:=JsonEnum(Doc);
IsArray:=false;
while e<>nil do
if e.Next then
begin
v:=PVariant(e.v0);
vt:=TVarData(v^).VType;
if (vt and varArray)=0 then
case vt and varTypeMask of
//varEmpty?
varNull:
begin
i:=bsonNULL;
dWrite(@i,1);
dWriteCString(e.Key);
end;
varSmallint,varInteger,varShortInt,varByte,varWord,varLongWord:
begin
i:=bsonInt32;
dWrite(@i,1);
dWriteCString(e.Key);
i:=v^;
dWrite(@i,4);
end;
varInt64:
begin
i:=bsonInt64;
dWrite(@i,1);
dWriteCString(e.Key);
ii:=v^;
dWrite(@ii,8);
//TODO: detect bsonTimestamp?
end;
varSingle,varDouble,varCurrency:
begin
i:=bsonDouble;
dWrite(@i,1);
dWriteCString(e.Key);
dd:=v^;
dWrite(@dd,8);
end;
varDate:
begin
i:=bsonUTCDateTime;
dWrite(@i,1);
dWriteCString(e.Key);
ii:=Round((VarToDateTime(v^)-UnixDateDelta)*MSecsPerDay);
dWrite(@ii,8);
end;
varOleStr,varString,$0102:
begin
//detect GUID //TODO try to rig varStrArg
w:=VarToWideStr(v^);
wl:=Length(w);
if (wl=38) and (w[1]='{') and (w[38]='}')
and (w[10]='-') and (w[15]='-')
and (w[20]='-') and (w[25]='-') then //and the other are hex digits?
begin
//assume UUID
gg:=StringToGUID(w);
i:=bsonBinary;
dWrite(@i,1);
dWriteCString(e.Key);
i:=16;//SizeOf(TGUID);
dWrite(@i,4);
i:=bsonBinaryUUID;
dWrite(@i,1);
dWrite(@gg,16);
end
else
//detect objectID
if (wl=bsonObjectID_L) and StartsWith(w,bsonObjectIDPrefix) then //and the other are hex digits?
begin
i:=bsonObjectID;
dWrite(@i,1);
dWriteCString(e.Key);
j:=Length(bsonObjectIDPrefix)+1;
for i:=0 to 11 do
begin
bb:=byte(AnsiChar(w[j+i*2]));
if (bb and $F0)=$30 then o[i]:=bb shl 4 else o[i]:=(9+bb) shl 4;
bb:=byte(AnsiChar(w[j+i*2+1]));
if (bb and $F0)=$30 then inc(o[i],bb and $F) else inc(o[i],(9+bb) and $F);
end;
dWrite(@o[0],12);
end
else
//detect javascript
if StartsWith(w,bsonJavaScriptCodePrefix) then
begin
i:=bsonJavaScriptCode;
dWrite(@i,1);
dWriteCString(e.Key);
dWriteString(Copy(w,Length(bsonJavaScriptCodePrefix)+1,Length(w)-Length(bsonJavaScriptCodePrefix)));
end
else
//detect regex
if StartsWith(w,bsonRegExPrefix) then
begin
i:=bsonRegEx;
dWrite(@i,1);
dWriteCString(e.Key);
i:=Length(bsonRegExPrefix)+1;
if (i<=Length(w)) and (w[i]='/') then inc(i);//TODO: support alternate regex delimiter?
j:=i;
while (j<=Length(w)) and (w[i]<>'/') do inc(j);
dWriteCString(Copy(w,i,j-i));
dWriteCString(Copy(w,j+1,Length(w)-j));
end
else
begin
i:=bsonString;
dWrite(@i,1);
dWriteCString(e.Key);
dWriteString(w);
end;
//TODO: bsonJavaScriptCodeWithScope, bsonSymbol ?
end;
//TODO varStrArg as bsonBinaryUUID
varBoolean:
begin
i:=bsonBoolean;
dWrite(@i,1);
dWriteCString(e.Key);
if v^ then i:=1 else i:=0;
dWrite(@i,1);
end;
//varVariant://TODO
varDispatch,varUnknown:
begin
uu:=IUnknown(v^);
if uu<>nil then
if not TryWriteJSONDocument then
if not TryWriteBSONDocArray then
if not TryWriteJSONArray then
{$IFDEF BSON_SUPPORT_REGEX}
if not TryWriteRegExp then
{$ENDIF}
if not TryWriteStream then
if not TryWritePersistStream then
raise EBSONException.Create('No supported interface found on object "'+e.Key+'"');
end;
else raise EBSONException.Create('Unsupported variant type '+IntToHex(vt,4)+' "'+e.Key+'"');
end
else
if (vt and varTypeMask)=varByte then
begin
i:=bsonBinary;
dWrite(@i,1);
dWriteCString(e.Key);
j:=VarArrayHighBound(v^,1)-VarArrayLowBound(v^,1)+1;
dWrite(@j,4);
i:=bsonBinaryGeneric;
dWrite(@i,1);
pp:=VarArrayLock(v^);
try
dWrite(pp,j);
finally
VarArrayUnlock(v^);
end;
end
else
Push(TVarArrayEnumerator.Create(v),true);
end
else
begin
//terminator
i:=0;