forked from stijnsanders/jsonDoc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsonDoc.pas
2475 lines (2319 loc) · 62.6 KB
/
jsonDoc.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
{
jsonDoc.pas
Copyright 2015-2017 Stijn Sanders
Made available under terms described in file "LICENSE"
https://github.com/stijnsanders/jsonDoc
v1.1.1
}
unit jsonDoc;
{$WARN SYMBOL_PLATFORM OFF}
{$D-}
{$L-}
{
Options:
Define here or in the project settings
JSONDOC_JSON_STRICT
to disallow missing quotes around key names
JSONDOC_STOREINDENTING
to make ToString write indentation EOL's and tabs
JSONDOC_THREADSAFE
to make IJSONDocument instances thread-safe
JSONDOC_DEFAULT_USE_IJSONARRAY
to set JSON_UseIJSONArray to true by default
}
interface
uses
ComObj, ActiveX, SysUtils, WinTypes;
const
//COM GUID's
IID_IJSONDocument
: TGUID = '{4A534F4E-0001-0001-C000-000000000001}';
CLASS_JSONDocument
: TGUID = '{4A534F4E-0001-0002-C000-000000000002}';
IID_IJSONEnumerator
: TGUID = '{4A534F4E-0001-0003-C000-000000000003}';
IID_IJSONEnumerable
: TGUID = '{4A534F4E-0001-0004-C000-000000000004}';
IID_IJSONArray
: TGUID = '{4A534F4E-0001-0005-C000-000000000005}';
IID_IJSONDocArray
: TGUID = '{4A534F4E-0001-0006-C000-000000000006}';
IID_IJSONDocWithReUse
: TGUID = '{4A534F4E-0001-0007-C000-000000000007}';
type
{
IJSONDocument interface
the base JSON document interface that provides access to a set of
key-value pairs.
use ToString and Parse to convert JSON to and from string values.
use ToVarArray to access the key-value pairs as a [x,2] variant array.
use Clear to re-use a JSON doc for parsing or building a new similar
document and keep the allocated memory for keys and values.
see also: JSON function
}
IJSONDocument = interface(IUnknown)
['{4A534F4E-0001-0001-C000-000000000001}']
function Get_Item(const Key: WideString): Variant; stdcall;
procedure Set_Item(const Key: WideString; const Value: Variant); stdcall;
function Parse(const JSONData: WideString): IJSONDocument; stdcall;
function ToString: WideString; stdcall;
function ToVarArray: Variant; stdcall;
procedure Clear; stdcall;
property Item[const Key: WideString]: Variant
read Get_Item write Set_Item; default;
procedure Delete(const Key: WideString); stdcall;
end;
{
IJSONEnumerator interface
use IJSONEnumerator to enumerate a document's key-value pairs
see also: JSONEnum function
}
//TODO: IEnumVariant?
IJSONEnumerator = interface(IUnknown)
['{4A534F4E-0001-0003-C000-000000000003}']
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
property Key: WideString read Get_Key;
property Value: Variant read Get_Value write Set_Value;
end;
{
IJSONEnumerable interface
used to get a IJSONEnumerable instance for a document
see also: JSONEnum function
}
IJSONEnumerable = interface(IUnknown)
['{4A534F4E-0001-0004-C000-000000000004}']
function NewEnumerator: IJSONEnumerator; stdcall;
end;
{
IJSONArray interface
When using VarArrayOf (declared in Variants.pas), a SafeArray is
used internally for storage, but as a variant value VarCopy is called
with each use, creating duplicate (deep) copies of the SafeArray.
Use IJSONArray (and the ja function) to create a IJSONArray instance
that uses a single copy of the data. It is also reference counted,
which automates memory clean-up.
}
IJSONArray = interface(IUnknown)
['{4A534F4E-0001-0005-C000-000000000005}']
function Get_Item(Index: integer): Variant; stdcall;
procedure Set_Item(Index: integer; const Value: Variant); stdcall;
function Count: integer; stdcall;
function ToString: WideString; stdcall;
function v0(Index: integer): pointer; stdcall;
property Item[Idx: integer]: Variant read Get_Item write Set_Item; default;
end;
{
IJSONDocArray interface
use IJSONDocArray to build an array of similar documents,
ideally in combination with a single IJSONDocument instance and
IJSONDocument.Clear to re-use the memory allocated for keys and values
see also: JSONDocArr function
}
IJSONDocArray = interface(IJSONArray)
['{4A534F4E-0001-0006-C000-000000000006}']
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;
end;
{
IJSONDocWithReUse interface
used internally to enable re-use of allocated keys
see also: TJSONDocument Parse and Clear
}
IJSONDocWithReUse = interface(IUnknown)
['{4A534F4E-0001-0007-C000-000000000007}']
function ReUse(const Key: WideString): Variant; stdcall;
end;
{
JSON function: JSON document factory
call JSON without parameters do create a new blank document
}
function JSON: IJSONDocument; overload;
{
JSON function: JSON document builder
pass an array of alternately keys and values,
suffix key with opening brace to start an embedded document,
and key of a single closing brace to close it.
}
function JSON(const x: array of Variant): IJSONDocument; overload;
{
JSON function: JSON document converter
pass a single variant to have it converted to an IJSONDocument interface
or a string with JSON parsed into a IJSONDocument
or nil when VarIsNull
}
function JSON(const x: Variant): IJSONDocument; overload;
{
JSONEnum function
get a new enumerator to enumeratare the key-value pairs in the document
}
function JSONEnum(const x: IJSONDocument): IJSONEnumerator; overload; //inline;
function JSONEnum(const x: Variant): IJSONEnumerator; overload;
function JSON(const x: IJSONEnumerator): IJSONDocument; overload; //inline;
function JSONEnum(const x: IJSONEnumerator): IJSONEnumerator; overload; //inline;
{
ja function
create and populate a new IJSONArray instance
or cast a Variant holding a JSONArray instance to the interface reference
}
function ja(const Items:array of Variant): IJSONArray; overload;
function ja(const Item:Variant): IJSONArray; overload;
{
JSONDocArray function
get a new IJSONDocArray instance
}
function JSONDocArray: IJSONDocArray; overload;
function JSONDocArray(const Items:array of IJSONDocument): IJSONDocArray; overload;
{
JSON_UseIJSONArray
switch JSON so it will create IJSONArray instances to hold arrays of values
instead of VarArrayCreate, default false
see also TJSONDocument.UseIJSONArray property
}
var
JSON_UseIJSONArray: boolean;
{
TJSONImplBaseObj
common base object JSON implementation objects inherit
don't use directly
}
type
{$IFDEF JSONDOC_THREADSAFE}
TJSONImplBaseObj = class(TInterfacedObject)
protected
FLock:TRTLCriticalSection;
public
procedure AfterConstruction; override;
destructor Destroy; override;
end;
{$ELSE}
//thread-unsafe anyway, so avoid locking when reference counting:
TJSONImplBaseObj = class(TObject, IInterface)
protected
FRefCount: Integer;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
end;
{$ENDIF}
{
TJSONDocument class
the default IJSONDocument implementation
see also: JSON function
}
TJSONDocument = class(TJSONImplBaseObj, IJSONDocument, IJSONEnumerable,
IJSONDocWithReUse)
private
FElementIndex,FElementSize:integer;
FElements:array of record
SortIndex,LoadIndex:integer;
Key:WideString;
Value:Variant;
end;
FLoadIndex:integer;
{$IFNDEF JSONDOC_THREADSAFE}
FGotIndex,FGotSorted:integer;
FGotMatch:boolean;
{$ENDIF}
FUseIJSONArray:boolean;
function GetKeyIndex(const Key: WideString;
var GotIndex: integer; var GotSorted: integer): boolean;
protected
function Get_Item(const Key: WideString): Variant; stdcall;
procedure Set_Item(const Key: WideString; const Value: Variant); stdcall;
function ReUse(const Key: WideString): Variant; stdcall;
public
procedure AfterConstruction; override;
destructor Destroy; override;
function Parse(const JSONData: WideString): IJSONDocument; stdcall;
function JSONToString: WideString; stdcall;
function IJSONDocument.ToString=JSONToString;
function ToVarArray: Variant; stdcall;
procedure Clear; stdcall;
function NewEnumerator: IJSONEnumerator; stdcall;
procedure Delete(const Key: WideString); stdcall;
property Item[const Key: WideString]: Variant
read Get_Item write Set_Item; default;
property UseIJSONArray:boolean read FUseIJSONArray write FUseIJSONArray;
end;
{
TJSONEnumerator class
the default IJSONEnumerator implementation
see also: JSONEnum function
}
TJSONEnumerator = class(TJSONImplBaseObj, IJSONEnumerator)
private
FData:TJSONDocument;
FIndex: integer;
public
constructor Create(Data: TJSONDocument);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
end;
{
TJSONArray class
Default ILightArray implementation
}
TJSONArray = class(TJSONImplBaseObj, IJSONArray)
private
FData:array of Variant;
protected
function Get_Item(Index: integer): Variant; stdcall;
procedure Set_Item(Index: integer; const Value: Variant); stdcall;
function Count: integer; stdcall;
function JSONToString: WideString; stdcall;
function IJSONArray.ToString=JSONToString;
function v0(Index: integer): pointer; stdcall;
public
constructor Create(Size: integer);
end;
{
TJSONArrayEnumerator
an IJSONEnumerator implementation that iterates over a variant array
used internally to convert to JSON
}
TJSONArrayEnumerator= class(TJSONImplBaseObj, IJSONEnumerator)
private
FData:IJSONArray;
FIndex,FMax:integer;
public
constructor Create(const Data:IJSONArray);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
end;
{
TJSONDocArray class
the default IJSONDocArray implementation
see also: JSONDocArray function
}
TJSONDocArray = class(TJSONImplBaseObj, IJSONArray, IJSONDocArray)
private
FItems:array of WideString;
FItemsCount,FItemsSize,FTotalLength,FCurrentIndex:integer;
FCurrent:Variant;
protected
//IJSONArray
function Get_Item(Index: integer): Variant; stdcall;
procedure Set_Item(Index: integer; const Value: Variant); stdcall;
function Count: integer; stdcall;
function JSONToString: WideString; stdcall;
function IJSONArray.ToString=JSONToString;
function v0(Index: integer): pointer; stdcall;
//function IJSONArray.ToString=JSONToString;
//IJSONDocArray
function Add(const Doc: IJSONDocument): integer; stdcall;
function AddJson(const Data: WideString): integer; stdcall;
procedure LoadItem(Index: integer; const Doc: IJSONDocument); stdcall;
function IJSONDocArray.ToString=JSONToString;
procedure Clear; stdcall;
public
constructor Create;
destructor Destroy; override;
end;
{
TVarArrayEnumerator
an IJSONEnumerator implementation that iterates over a variant array
used internally to convert to JSON
}
TVarArrayEnumerator = class(TJSONImplBaseObj, IJSONEnumerator)
private
FData:PVariant;
FCurrent:Variant;
FIndex,FMax,FCurrentIndex:integer;
public
constructor Create(const Data:PVariant);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
end;
{
TVarJSONArray
an IJSONArray implementation that works on an existing variant array
used internally by the ja function
}
TVarJSONArray = class(TJSONImplBaseObj, IJSONArray)
private
FData,FCurrent:Variant;
v1,v2,FCurrentIndex:integer;
protected
function Get_Item(Index: integer): Variant; stdcall;
procedure Set_Item(Index: integer; const Value: Variant); stdcall;
function Count: integer; stdcall;
function JSONToString: WideString; stdcall;
function IJSONArray.ToString=JSONToString;
function v0(Index: integer): pointer; stdcall;
public
constructor Create(const Data: Variant);
constructor CreateNoCopy(var Data: Variant);
destructor Destroy; override;
end;
{
EJSONException class types
exception types thrown from TJSONDocument's Parse and ToString
}
EJSONException=class(Exception);
EJSONDecodeException=class(EJSONException);
EJSONEncodeException=class(EJSONException);
implementation
uses
Classes, Variants, Windows;
procedure VarMove(var Dest, Src: Variant);
begin
//Dest:=Src;VarClear(Src);
Move(Src,Dest,SizeOf(TVarData));
ZeroMemory(@Src,SizeOf(TVarData));
end;
{ TJSONImplBaseObj }
{$IFDEF JSONDOC_THREADSAFE}
procedure TJSONImplBaseObj.AfterConstruction;
begin
inherited;
InitializeCriticalSection(FLock);
end;
destructor TJSONImplBaseObj.Destroy;
begin
DeleteCriticalSection(FLock);
inherited;
end;
{$ELSE}
procedure TJSONImplBaseObj.AfterConstruction;
begin
inherited;
dec(FRefCount);//see constructor
end;
procedure TJSONImplBaseObj.BeforeDestruction;
begin
inherited;
if RefCount<>0 then System.Error(reInvalidPtr);
end;
class function TJSONImplBaseObj.NewInstance: TObject;
begin
Result:=inherited NewInstance;
//see AfterConstruction, prevent detroy while creating
TJSONImplBaseObj(Result).FRefCount:=1;
end;
function TJSONImplBaseObj.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID,Obj) then Result:=0 else Result:=E_NOINTERFACE;
end;
function TJSONImplBaseObj._AddRef: Integer;
begin
inc(FRefCount);
Result:=FRefCount;
end;
function TJSONImplBaseObj._Release: Integer;
begin
dec(FRefCount);
Result:=FRefCount;
if Result=0 then Destroy;
end;
{$ENDIF}
{ TJSONDocument }
procedure TJSONDocument.AfterConstruction;
begin
inherited;
FElementIndex:=0;
FElementSize:=0;
FLoadIndex:=0;
{$IFNDEF JSONDOC_THREADSAFE}
FGotIndex:=0;
FGotSorted:=0;
FGotMatch:=false;
{$ENDIF}
FUseIJSONArray:=JSON_UseIJSONArray;
end;
destructor TJSONDocument.Destroy;
var
i:integer;
begin
for i:=0 to FElementIndex-1 do VarClear(FElements[i].Value);
inherited;
end;
function TJSONDocument.GetKeyIndex(const Key: WideString;
var GotIndex: integer; var GotSorted: integer): boolean;
var
a,b,c,d,x:integer;
begin
//case sensitivity?
{$IFNDEF JSONDOC_THREADSAFE}
//check last getindex, speeds up set right after get
if FGotMatch and (CompareStr(Key,FElements[FGotIndex].Key)=0) then
begin
//assert FGotIndex=FSorted[FGotSorted];
GotIndex:=FGotIndex;
GotSorted:=FGotSorted;
Result:=true;
end
else
{$ENDIF}
begin
a:=0;
b:=FElementIndex-1;
d:=FElementIndex;
Result:=false;//default
while b>=a do
begin
c:=(a+b) div 2;
d:=FElements[c].SortIndex;
//if c=a? c=b?
x:=CompareStr(Key,FElements[d].Key);
if x=0 then
begin
a:=c;
b:=c-1;
Result:=true;
end
else
if x<0 then
if b=c then dec(b) else b:=c
else
if a=c then inc(a) else a:=c;
end;
GotSorted:=a;
GotIndex:=d;
{$IFNDEF JSONDOC_THREADSAFE}
FGotSorted:=a;
FGotIndex:=d;
FGotMatch:=Result;
{$ENDIF}
end;
end;
function TJSONDocument.Get_Item(const Key: WideString): Variant;
var
GotIndex,GotSorted:integer;
begin
{$IFDEF JSONDOC_THREADSAFE}
EnterCriticalSection(FLock);
try
{$ENDIF}
if (Self<>nil) and GetKeyIndex(Key,GotIndex,GotSorted)
and (FElements[GotIndex].LoadIndex=FLoadIndex) then
Result:=FElements[GotIndex].Value
else
Result:=Null;
{$IFDEF JSONDOC_THREADSAFE}
finally
LeaveCriticalSection(FLock);
end;
{$ENDIF}
end;
function TJSONDocument.ReUse(const Key: WideString): Variant;
var
GotIndex,GotSorted:integer;
begin
{$IFDEF JSONDOC_THREADSAFE}
EnterCriticalSection(FLock);
try
{$ENDIF}
if (Self<>nil) and GetKeyIndex(Key,GotIndex,GotSorted) then
begin
FElements[GotIndex].LoadIndex:=FLoadIndex;
Result:=FElements[GotIndex].Value;
end
else
Result:=Null;
{$IFDEF JSONDOC_THREADSAFE}
finally
LeaveCriticalSection(FLock);
end;
{$ENDIF}
end;
procedure TJSONDocument.Set_Item(const Key: WideString; const Value: Variant);
var
i,GotIndex,GotSorted:integer;
const
GrowStep=$20;//not too much, not too little (?)
begin
{$IFDEF JSONDOC_THREADSAFE}
EnterCriticalSection(FLock);
try
{$ENDIF}
//if ((VarType(Value) and varArray)<>0) and (VarArrayDimCount(v)>1) then
// raise EJSONException.Create(
// 'VarArray: multi-dimensional arrays not supported');
if not GetKeyIndex(Key,GotIndex,GotSorted) then
begin
if FElementIndex=FElementSize then
begin
inc(FElementSize,GrowStep);
SetLength(FElements,FElementSize);
end;
for i:=FElementIndex-1 downto GotSorted do
FElements[i+1].SortIndex:=FElements[i].SortIndex;
GotIndex:=FElementIndex;
inc(FElementIndex);
FElements[GotSorted].SortIndex:=GotIndex;
FElements[GotIndex].Key:=Key;
end;
FElements[GotIndex].Value:=Value;
FElements[GotIndex].LoadIndex:=FLoadIndex;
//FDirty:=true;
{$IFDEF JSONDOC_THREADSAFE}
finally
LeaveCriticalSection(FLock);
end;
{$ENDIF}
end;
function TJSONDocument.Parse(const JSONData: WideString): IJSONDocument;
var
i,l:integer;
function SkipWhiteSpace:WideChar;
begin
while (i<=l) and (jsonData[i]<=' ') do inc(i);
if i<=l then Result:=jsonData[i] else Result:=#0;
end;
function ExVicinity(di:integer):WideString;
const
VicinityExtent=8;
begin
if di<=VicinityExtent then
Result:=#13#10'(#'+IntToStr(di)+')"'+Copy(jsonData,1,di-1)+
' >>> '+jsonData[di]+' <<< '+Copy(jsonData,di+1,VicinityExtent)+'"'
else
Result:=#13#10'(#'+IntToStr(di)+')"...'+
Copy(jsonData,di-VicinityExtent,VicinityExtent)+
' >>> '+jsonData[di]+' <<< '+Copy(jsonData,di+1,VicinityExtent)+'"';
end;
procedure Expect(c:WideChar;const msg:string);
begin
while (i<=l) and (jsonData[i]<=' ') do inc(i);
if (i>l) or (jsonData[i]<>c) then
raise EJSONDecodeException.Create(msg+ExVicinity(i));
inc(i);
end;
procedure GetStringIndexes(var i1,i2:integer);
begin
i1:=i;
while (i<=l) and (jsonData[i]<>'"') do
begin
if jsonData[i]='\' then inc(i);//just skip all to skip any '"'
inc(i);
end;
i2:=i;
inc(i);
end;
function GetStringValue(i1,i2:integer):WideString;
var
ii,di,u,v,w:integer;
begin
//assert jsonData[i1-1]='"'
//assert jsonData[i2]='"';
SetLength(Result,i2-i1);
ii:=1;
di:=i1;
while di<i2 do
begin
//assert ii<=Length(Result);
if jsonData[di]='\' then
begin
inc(di);
case AnsiChar(jsonData[di]) of
'"','\','/':Result[ii]:=jsonData[di];
'b':Result[ii]:=#8;
't':Result[ii]:=#9;
'n':Result[ii]:=#10;
'f':Result[ii]:=#12;
'r':Result[ii]:=#13;
'u':
begin
w:=0;
for u:=0 to 3 do
begin
inc(di);
v:=word(jsonData[di]);
case v of
$30..$39:w:=(w shl 4) or (v and $F);
$41..$5A,$61..$7A:w:=(w shl 4) or ((v and $1F)+9);
else raise EJSONDecodeException.Create(
'JSON Invalid espace sequence'+ExVicinity(di));
end;
end;
Result[ii]:=WideChar(w);
end;
else raise EJSONDecodeException.Create(
'JSON Unknown escape sequence'+ExVicinity(di));
end;
end
else
Result[ii]:=jsonData[di];
inc(di);
inc(ii);
end;
SetLength(Result,ii-1);
end;
const
stackGrowStep=$20;//not too much, not too little (?)
arrGrowStep=$20;
var
IsArray:boolean;
k1,k2,v1,v2,a1,ai,al:integer;
d:IJSONDocument;
a:array of Variant;
at,vt:TVarType;
procedure SetValue(const v:Variant);
begin
//assert 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[GetStringValue(k1,k2)]:=v
end;
var
firstItem,b:boolean;
stack:array of record
k1,k2:integer;
d:IJSONDocument;
end;
stackIndex,stackSize:integer;
ods:char;
key:WideString;
d1:IJSONDocument;
dr:IJSONDocWithReUse;
da:IJSONDocArray;
aa:TJSONArray;
da0,da1:integer;
v:Variant;
v64:int64;
procedure CheckValue;
begin
//assert da<>nil
if stackIndex=da0 then
raise EJSONDecodeException.Create('IJSONDocArray: non-document element in array');
end;
begin
{$IFDEF JSONDOC_THREADSAFE}
EnterCriticalSection(FLock);
try
{$ENDIF}
//Clear;? let caller decide.
i:=1;
l:=Length(jsonData);
//object starts
Expect('{','JSON doesn''t define an object, "{" expected.');
stackSize:=0;
stackIndex:=0;
ai:=0;
a1:=0;
al:=0;
da:=nil;
da0:=0;
da1:=0;
IsArray:=false;
firstItem:=true;
{$if CompilerVersion >= 24}
ods:=FormatSettings.DecimalSeparator;
{$else}
ods:=DecimalSeparator;
{$ifend}
try
{$if CompilerVersion >= 24}
FormatSettings.DecimalSeparator:='.';
{$else}
DecimalSeparator:='.';
{$ifend}
d:=Self;
//main loop over key/values and nested objects/arrays
while (i<=l) and (stackIndex<>-1) do
begin
if firstItem then firstItem:=false else
Expect(',','JSON element not delimited by comma');
if not(IsArray) and (SkipWhiteSpace<>'}') then
begin
//key string
{$IFDEF JSONDOC_JSON_STRICT}
Expect('"','JSON key string not enclosed in double quotes');
GetStringIndexes(k1,k2);
{$ELSE}
if SkipWhiteSpace='"' then
begin
inc(i);
GetStringIndexes(k1,k2);
end
else
begin
k1:=i;
while (i<=l) and (jsonData[i]>' ') and
(jsonData[i]<>':') and (jsonData[i]<>'"') do inc(i);
k2:=i;
end;
{$ENDIF}
Expect(':','JSON key, value not separated by colon');
end;
//value
case AnsiChar(SkipWhiteSpace) of
'{','['://object or array
begin
b:=IsArray;
if jsonData[i]='{' then
begin
//an object starts
if da=nil then
if IsArray then
begin
if ai=al then
begin
inc(al,arrGrowStep);//not too much, not too little (?)
SetLength(a,al);
end;
v:=JSON;
a[ai]:=v;
//detect same type elements array
if at=varEmpty then at:=varUnknown else
if at<>varUnknown then at:=varVariant;
inc(ai);
end
else
begin
key:=GetStringValue(k1,k2);
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
else
if da0=stackIndex then da1:=i;
IsArray:=false;
end
else
begin
//an array starts
if da=nil then
if d.QueryInterface(IID_IJSONDocWithReUse,dr)=S_OK then
begin
key:=GetStringValue(k1,k2);
v:=dr.ReUse(key);
dr:=nil;
if (TVarData(v).VType in [varDispatch,varUnknown]) and
(IUnknown(v).QueryInterface(IID_IJSONDocArray,da)=S_OK) then
begin
da0:=stackIndex+1;
da1:=0;//see first '{' above
end;
end;
IsArray:=true;
end;
inc(i);
//push onto stack
if stackIndex=stackSize then
begin
inc(stackSize,stackGrowStep);
SetLength(stack,stackSize);
end;
if b then //if WasArray then
begin
stack[stackIndex].k1:=a1;
stack[stackIndex].k2:=at;
stack[stackIndex].d:=nil;
end
else
begin
stack[stackIndex].k1:=k1;
stack[stackIndex].k2:=k2;
stack[stackIndex].d:=d;
end;
inc(stackIndex);
firstItem:=true;
if da=nil then
if IsArray then
begin
a1:=ai;
at:=varEmpty;//used to detect same type elements array
end
else
d:=IUnknown(v) as IJSONDocument;
end;
'}',']':;//empty object or array, drop into close array below
'"'://string
begin
inc(i);
GetStringIndexes(v1,v2);
if da=nil then
SetValue(GetStringValue(v1,v2))
else
CheckValue;
end;
'0'..'9','-'://number
begin
b:=jsonData[i]='-';
v1:=i;
if b then inc(i);
if da=nil then
begin
v64:=0;
while (i<=l) and (AnsiChar(jsonData[i]) in ['0'..'9']) do
begin
v64:=v64*10+(word(jsonData[i]) and $F);//TODO: detect overflow
inc(i);
end;
if AnsiChar(jsonData[i]) in ['.','e','E'] then
begin
//float
inc(i);
while (i<=l) and (AnsiChar(jsonData[i]) in
['0'..'9','-','+','e','E']) do inc(i);
//try except EConvertError?
SetValue(StrToFloat(Copy(jsonData,v1,i-v1)));
end
else
begin
//integer