-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathjsonDoc.pas
More file actions
4501 lines (4185 loc) · 110 KB
/
jsonDoc.pas
File metadata and controls
4501 lines (4185 loc) · 110 KB
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-2026 Stijn Sanders
Made available under terms described in file "LICENSE"
https://github.com/stijnsanders/jsonDoc
v1.3.0
}
unit jsonDoc;
{$WARN SYMBOL_PLATFORM OFF}
{$D-}
{$L-}
{$Y-}
{
Options:
Define here or in the project settings
JSONDOC_JSON_STRICT
to disallow missing quotes around key names
JSONDOC_JSON_LOOSE
to allow missing colons and comma's
JSONDOC_JSON_PASCAL_STRINGS
to allow pascal-style strings
JSONDOC_P2
to combine JSONDOC_JSON_LOOSE and JSONDOC_JSON_PASCAL_STRINGS
JSONDOC_STOREINDENTING
to make AsString 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
JSONDOC_DEFAULT_USE_IJSONDOCARRAY
to set JSON_UseIJSONDocArray to true by default
JSONDOC_NO_LOAD_AFTER_ERROR
to suppress loading keys after parse error
}
interface
uses SysUtils;
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_IJSONEnumerableSorted
: TGUID = '{4A534F4E-0001-0008-C000-000000000008}';
IID_IJSONDocArrayEnumerator
: TGUID = '{4A534F4E-0001-0009-C000-000000000009}';
IID_IJSONMemBank
: TGUID = '{4A534F4E-0001-000A-C000-00000000000A}';
IID_IJSONMemBankLoadable
: TGUID = '{4A534F4E-0001-000B-C000-00000000000B}';
type
{
IJSONDocument interface
the base JSON document interface that provides access to a set of
key-value pairs.
use AsString and Parse to convert JSON to and from string values.
use AsVarArray 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;
procedure Parse(const JSONData: WideString); stdcall;
function ToString: WideString; stdcall;
function ToVarArray: Variant; stdcall;
procedure Clear; stdcall;
procedure Delete(const Key: WideString); stdcall;
function v0(const Key: WideString): pointer; stdcall;
property Item[const Key: WideString]: Variant
read Get_Item write Set_Item; default;
property AsString: WideString read ToString write Parse;
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 ItemsCount: integer; stdcall;
function ToString: WideString; stdcall;
function v0(Index: integer): pointer; stdcall;
property Item[Idx: integer]: Variant read Get_Item write Set_Item; default;
property Count: integer read ItemsCount;
property AsString: WideString read ToString;
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;
function GetJSON(Index: integer): WideString; stdcall;
procedure Parse(const JSONData: WideString); stdcall;
end;
{
IJSONEnumerableSorted interface
used to get a IJSONEnumerable instance for a document, that uses the
document's internal keys sort order
see also: JSONEnum function
}
IJSONEnumerableSorted = interface(IUnknown)
['{4A534F4E-0001-0008-C000-000000000008}']
function NewEnumerator: IJSONEnumerator; stdcall;
end;
{
IJSONDocArrayEnumerator
extends IJSONDocument with enumerator functions, used by the JSONEnum
overload for IJSONDocArray instances
}
IJSONDocArrayEnumerator = interface(IJSONDocument)
['{4A534F4E-0001-0009-C000-000000000009}']
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
function Get_DocIndex: integer; stdcall;
property DocIndex: integer read Get_DocIndex;
end;
{
IJSONMemBank
interface used internally between jsonDoc objects to share memory
}
IJSONMemBank = interface(IUnknown)
['{4A534F4E-0001-000A-C000-00000000000A}']
function Bank:TObject;
end;
{
IJSONMemBankLoadable
interface used internally between jsonDoc objects to share memory
}
IJSONMemBankLoadable = interface(IUnknown)
['{4A534F4E-0001-000B-C000-00000000000B}']
procedure ClearBank(MemBank: IJSONMemBank); stdcall;
procedure LoadBank(Bank: IUnknown; Index: integer); stdcall;
procedure Build(Builder: pointer; TabIndex: integer); 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;
{
JSON function: JSON prepare and parse
combine the document builder with a parse call
}
function JSON(const x: array of Variant; const d: WideString): IJSONDocument;
overload; //inline;
{
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;
function JSONEnum(const x: IJSONDocArray): IJSONDocArrayEnumerator; overload; //inline;
{
JSONEnumSorted function
get a new enumerator to enumeratare the key-value pairs in the document,
using the document's internal keys sort order
}
function JSONEnumSorted(const x: IJSONDocument): IJSONEnumerator; overload; //inline;
function JSONEnumSorted(const x: Variant): IJSONEnumerator; overload;
{
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;
function JSONDocArray(const x: Variant): IJSONDocArray; overload;
{
isJSON, isJSONArray, isJSONDocArray
check whether a variant value holds an instance of IJSONDocument,
IJSONArray, IJSONDocArray
}
function isJSON(const v: Variant; var d: IJSONDocument): boolean; //inline;
function isJSONArray(const v: Variant; var a: IJSONArray): boolean; //inline;
function isJSONDocArray(const v: Variant; var a: IJSONDocArray): boolean; //inline;
{
newJSON, newJSONDocArray
assigns new instances and returns a reference for concise syntax
}
function newJSON(var d: IJSONDocument): IJSONDocument;
function newJSONDocArray(var a: IJSONDocArray): IJSONDocArray;
{
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;
{
JSON_UseIJSONDocArray
switch JSON.Parse so it will create IJSONDOCArray instances to hold arrays of
documents instead of VarArrayCreate, when a sequence of "[" and "{" is
detected, default false
see also TJSONDocument.UseIJSONDocArray property
}
var
JSON_UseIJSONDocArray: boolean;
{
JSONa function: JSON document factory with UseIJSONDocArray enabled
create a new blank document, and sets UseIJSONDocArray for cals to Parse,
creates an IJSONDocArray instance when a sequence of "[" and "{" is detected.
}
function JSONa: IJSONDocument;
type
{
EJSONException class types
exception types thrown from TJSONDocument's Parse and ToString
}
EJSONException=class(Exception);
EJSONDecodeException=class(EJSONException);
EJSONEncodeException=class(EJSONException);
implementation
uses Variants, Windows, Math;
{
KeyValueNode
internal structure to key-value pairs using key hashes
}
const
KeyValueNodeHashBits = 8;//bits
KeyValueNodeHashMask = (1 shl KeyValueNodeHashBits)-1;//$F
KeyValueItemMaxChain = 8;
type
PPKeyValueNode = ^PKeyValueNode;
PKeyValueNode = ^TKeyValueNode;
TKeyValueNode = array[0..KeyValueNodeHashMask] of pointer;//of PKeyValueNode;
//strange! 'old' Delphi has NativeUInt=0..1; ??!!
{$IF not(Declared(NativeUInt)) or (SizeOf(cardinal)=SizeOf(pointer))}
NativeUInt = cardinal;
{$IFEND}
PKeyValueItem = ^TKeyValueItem;
TKeyValueItem = record
Hash: NativeUInt;
Key: WideString;
More, Next: PKeyValueItem;
LoadIndex: cardinal;
NodeIndex: integer;
Value: Variant;
end;
{
TJSONImplBaseObj
common base object JSON implementation objects inherit
don't use directly
}
{$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}
{
TJSONBuilder
used internally as a string builder
}
TJSONBuilder = object//record
Data: WideString;
DataIndex, DataSize: cardinal;
procedure Clear;
function Reserve(l: cardinal): cardinal;
procedure Append(const x: WideString);
{$IFDEF JSONDOC_STOREINDENTING}
procedure Write(const x; l: Cardinal);
{$ENDIF}
procedure VarToStr(const v: Variant);
procedure EncodeStr(const x: WideString);
function Output: WideString;
end;
PJSONBuilder = ^TJSONBuilder;
{
TJSONMemBank
used internally to allow jsonDoc objects to share memory
}
TJSONMemNode = record
KeyIndex, KeyLength, ValueIndex, ValueLength, Next, Child, F1, F2: integer;
end;
PJSONMemNode = ^TJSONMemNode;
TJSONMemBank = class(TJSONImplBaseObj, IJSONMemBank)
private
json: TJSONBuilder;
FNodeIndex, FNodeSize: integer;
FNodes: array of TJSONMemNode;
protected
function Bank: TObject;
function ExVicinity(di: cardinal): WideString;
function Key(n: integer): WideString;
function GetStringValue(vi, vl: integer): WideString;
function StartArray: integer;
function Add(BaseIndex: integer; const Data: WideString;
Doc: IJSONDocument): integer;
public
procedure AfterConstruction; override;
procedure Parse(var DocIndex: integer; DataIndex: integer;
const Data: WideString = '');
end;
{
TJSONDocument class
the default IJSONDocument implementation
see also: JSON function
}
TJSONDocument = class(TJSONImplBaseObj, IJSONDocument, IJSONMemBankLoadable,
IJSONEnumerable, IJSONEnumerableSorted)
private
FMemBank: IJSONMemBank;
FRoot:PKeyValueNode;
FFirst,FLast:PKeyValueItem;
FLoadIndex: cardinal;
{$IFNDEF JSONDOC_THREADSAFE}
FGotItem:PKeyValueItem;
{$ENDIF}
FUseIJSONArray, FUseIJSONDocArray: boolean;
function LookUpItem(const Key:WideString):PKeyValueItem;
function StoreItem(const Key:WideString):PKeyValueItem;
function v00(Item: PKeyValueItem; FailWhenMissing: boolean): PVariant;
function v1(NodeIndex: integer): Variant;
protected
function Get_Item(const Key: WideString): Variant; stdcall;
procedure Set_Item(const Key: WideString; const Value: Variant); stdcall;
function v0(const Key: Widestring): pointer; stdcall;
procedure ClearBank(MemBank: IJSONMemBank); stdcall;
procedure LoadBank(Bank: IUnknown; Index: integer); stdcall;
procedure Build(Builder: pointer; TabIndex: integer); stdcall;
public
procedure AfterConstruction; override;
destructor Destroy; override;
procedure Parse(const JSONData: WideString); 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 AsString: WideString read JSONToString write Parse;
property UseIJSONArray:boolean read FUseIJSONArray write FUseIJSONArray;
property UseIJSONDocArray:boolean read FUseIJSONDocArray write FUseIJSONDocArray;
function NewEnumeratorSorted: IJSONEnumerator; stdcall;
function IJSONEnumerableSorted.NewEnumerator = NewEnumeratorSorted;
end;
{
TJSONEnumerator class
the default IJSONEnumerator implementation
see also: JSONEnum function
}
TJSONEnumerator = class(TJSONImplBaseObj, IJSONEnumerator)
private
FData:TJSONDocument;
FFirst:boolean;
FItem:PKeyValueItem;
protected
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
public
constructor Create(Data: TJSONDocument);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
property Key: Widestring read Get_Key;
property Value: Variant read Get_Value write Set_Value;
end;
{
TJSONEnumeratorSorted class
a IJSONEnumerator implementation that uses first sorts the keys
see also: JSONEnumSorted function
}
TJSONEnumeratorSorted = class(TJSONImplBaseObj, IJSONEnumerator)
private
FData:TJSONDocument;
FItems:array of PKeyValueItem;
FIndex:integer;
protected
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
public
constructor Create(Data: TJSONDocument);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
property Key: Widestring read Get_Key;
property Value: Variant read Get_Value write Set_Value;
end;
{
TJSONDocArrayEnumerator class
}
TJSONDocArrayEnumerator = class(TJSONDocument, IJSONDocArrayEnumerator)
private
FDocArray: IJSONDocArray;
FIndex: integer;
protected
function IJSONDocArrayEnumerator.Get_Item=Get_Item;
procedure IJSONDocArrayEnumerator.Set_Item=Set_Item;
procedure IJSONDocArrayEnumerator.Parse=Parse;
function IJSONDocArrayEnumerator.ToString=JSONToString;
function IJSONDocArrayEnumerator.ToVarArray=ToVarArray;
procedure IJSONDocArrayEnumerator.Clear=Clear;
procedure IJSONDocArrayEnumerator.Delete=Delete;
function IJSONDocArrayEnumerator.v0=v0;
function Get_DocIndex: integer; stdcall;
public
constructor Create(const Data: IJSONDocArray);
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
property DocIndex: integer read Get_DocIndex;
end;
{
TJSONArray class
Default ILightArray implementation
}
TJSONArray = class(TJSONImplBaseObj, IJSONArray, IJSONEnumerable)
private
FData:array of Variant;
protected
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 v0(Index: integer): pointer; stdcall;
function NewEnumerator: IJSONEnumerator; stdcall;
public
constructor Create(Size: integer);
property Item[Idx: integer]: Variant read Get_Item write Set_Item; default;
property AsString: WideString read JSONToString;
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;
protected
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
public
constructor Create(const Data:IJSONArray);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
property Key: Widestring read Get_Key;
property Value: Variant read Get_Value write Set_Value;
end;
{
TJSONDocArray class
the default IJSONDocArray implementation
see also: JSONDocArray function
}
TJSONDocArray = class(TJSONImplBaseObj, IJSONArray, IJSONDocArray,
IJSONMemBankLoadable)
private
FMemBank:IJSONMemBank;
FBaseIndex:integer;
{$IFNDEF JSONDOC_THREADSAFE}
FCurrentIndex,FCurrentNode:integer;
{$ENDIF}
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 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;
function GetJSON(Index: integer): WideString; stdcall;
procedure Parse(const JSONData: WideString); stdcall;
//IJSONMemBankLoadable
procedure ClearBank(MemBank: IJSONMemBank); stdcall;
procedure LoadBank(Bank: IUnknown; Index: integer); stdcall;
procedure Build(Builder: pointer; TabIndex: integer); stdcall;
public
constructor Create;
destructor Destroy; override;
property AsString: WideString read JSONToString;
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;
function Get_Key: WideString; stdcall;
function Get_Value: Variant; stdcall;
procedure Set_Value(const Value: Variant); stdcall;
function v0: pointer; stdcall;
public
constructor Create(const Data:PVariant);
destructor Destroy; override;
function EOF: boolean; stdcall;
function Next: boolean; stdcall;
property Key: Widestring read Get_Key;
property Value: Variant read Get_Value write Set_Value;
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 ItemsCount: 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;
property AsString: WideString read JSONToString;
end;
procedure VarMove(var Dest, Src: Variant);
begin
//Dest:=Src;VarClear(Src);
Move(Src,Dest,SizeOf(TVarData));
ZeroMemory(@Src,SizeOf(TVarData));
end;
{
kvsHash
key hash function used for lookup
}
function kvsHash(const Key: WideString): NativeUInt;
const
seed = $11BB9955;
var
i,l:NativeUInt;
begin
Result:=seed;
l:=Length(Key);
for i:=1 to l do
Result:=(Result shl 1) + (word(Key[i]) * $0901);
inc(Result,l);
end;
{
key-value-node functions
}
function NewNode(var nn:PKeyValueNode):PKeyValueNode;
const
ll=SizeOf(TKeyValueNode);
begin
New(nn);//GetMem(nn,ll);
FillChar(nn^,ll,0);
Result:=nn;
end;
function NewItem(Hash:NativeUInt;const Key:Widestring;
var pp:PKeyValueItem):pointer;
const
ll=SizeOf(TKeyValueItem);
begin
New(pp);//GetMem(pp,ll);
FillChar(pp^,ll,0);
Result:=pointer(NativeUInt(pp) or 1);
//assert Hash=kvsHash(Key)
pp.Hash:=Hash;
pp.Key:=Key;
end;
function IsItem(p:pointer;var pp:PKeyValueItem):boolean; //inline;
begin
Result:=(NativeUInt(p) and 1)<>0;
if Result then pp:=PKeyValueItem(NativeUInt(p) xor 1);
end;
function AsItem(p:PKeyValueItem):pointer; //inline;
begin
Result:=pointer(NativeUInt(p) or 1);
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}
{ TJSONBuilder }
const
NodeGrowStep=1 shl 8;
JSONBuilderGrowStep=1 shl 16;
w2=SizeOf(WideChar);//2
procedure TJSONBuilder.Clear;
begin
Data:='';
DataIndex:=0;
DataSize:=0;
end;
function TJSONBuilder.Reserve(l: cardinal): cardinal;
begin
Result:=DataIndex+l;
if Result>DataSize then
begin
if (Result and (JSONBuilderGrowStep-1))=0 then
DataSize:=Result
else
DataSize:=(Result and not(JSONBuilderGrowStep-1))+JSONBuilderGrowStep;
SetLength(Data,DataSize);
end;
end;
procedure TJSONBuilder.Append(const x: WideString);
var
l,d:cardinal;
begin
l:=Length(x);
d:=Reserve(l);
Move(x[1],Data[DataIndex+1],l*w2);
DataIndex:=d;
end;
function TJSONBuilder.Output: WideString;
begin
//SetLength(Data,DataIndex);DataSize:=DataIndex;Result:=Data;
SetLength(Result,DataIndex);
Move(Data[1],Result[1],DataIndex*w2);
end;
{ TJSONMemBank }
procedure TJSONMemBank.AfterConstruction;
begin
inherited;
FNodeIndex:=0;
FNodeSize:=0;
end;
const
jfk_Mask = $F0000;
jfkNoEsc = $00000;
jfkWithEsc = $10000;
jfkArrayIndex = $20000;
jfkPascalString = $30000;
jfkLoose = $40000;
jfd_Mask = $FF;
jfdObject = 1;
jfdArray = 2;
jfdNull = 3;
jfdBoolTrue = 4;
jfdBoolFalse = 5;
jfdRawJSON = 7;
jfdStringNoEsc = 8;
jfdStringWithEsc = 9;
jfdStringPascal = 10;
jfdInt8 = 20;
jfdInt16 = 21;
jfdInt32 = 22;
jfdInt64 = 23;
jfdFloat = 11;
function TJSONMemBank.Bank: TObject;
begin
Result:=Self;
end;
{$IFDEF JSONDOC_P2}
{$DEFINE JSONDOC_JSON_LOOSE}
{$DEFINE JSONDOC_JSON_PASCAL_STRINGS}
{$ENDIF}
type
TxToken=(xtInvalid,xtWhitespace,xtAOpen,xtAClose,xtBOpen,xtBClose,
xtDoubleQuotes,xtColon,xtComma,xtAlpha,xtNum,xtBackslash,
xtSymbol,xtMinus,xtSemiColon,xtEquals,xtSingleQuote,xtHash,xtDollar);
const
XTokenMap:array[0..$7F] of TxToken=(
//$00
xtInvalid,xtInvalid,xtInvalid,xtInvalid,
xtInvalid,xtInvalid,xtInvalid,xtInvalid,
xtInvalid,xtWhitespace,xtWhitespace,xtWhitespace,
xtWhitespace,xtWhitespace,xtInvalid,xtInvalid,
//$10
xtInvalid,xtInvalid,xtInvalid,xtInvalid,
xtInvalid,xtInvalid,xtInvalid,xtInvalid,
xtInvalid,xtInvalid,xtInvalid,xtInvalid,
xtInvalid,xtInvalid,xtInvalid,xtInvalid,
//$20
xtWhitespace,xtSymbol,xtDoubleQuotes,xtHash,
xtDollar,xtSymbol,xtSymbol,xtSingleQuote,
xtSymbol,xtSymbol,xtSymbol,xtSymbol,
xtComma,xtMinus,xtSymbol,xtSymbol,
//$30
xtNum,xtNum,xtNum,xtNum,
xtNum,xtNum,xtNum,xtNum,
xtNum,xtNum,xtColon,xtSemiColon,
xtSymbol,xtEquals,xtSymbol,xtSymbol,
//$40
xtSymbol,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
//$50
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtBOpen,
xtBackslash,xtBClose,xtSymbol,xtSymbol,
//$60
xtSymbol,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
//$70
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAlpha,
xtAlpha,xtAlpha,xtAlpha,xtAOpen,
xtSymbol,xtAClose,xtSymbol,xtInvalid);
procedure TJSONMemBank.Parse(var DocIndex: integer; DataIndex: integer;
const Data: WideString);
var
i,l:integer;
function Node(ki,kl,vi,vl,f1:integer):integer;
var
m:PJSONMemNode;
begin
if FNodeIndex=FNodeSize then
begin
inc(FNodeSize,NodeGrowStep);
SetLength(FNodes,FNodeSize);
end;
Result:=FNodeIndex;
m:=@FNodes[FNodeIndex];
inc(FNodeIndex);
m.KeyIndex:=ki;
m.KeyLength:=kl;
m.ValueIndex:=vi;
m.ValueLength:=vl;
m.Next:=0;
m.Child:=0;
m.F1:=f1;
m.F2:=0;
end;
function SkipWhiteSpace:TxToken;
var
w:WideChar;
begin
while (i<l) and (json.Data[i]<=' ') do inc(i);
if i<l then
begin
w:=json.Data[i];
if word(w)<$0080 then
Result:=xTokenMap[word(w) and $007F]
else
Result:=xtInvalid;
end
else
Result:=xtInvalid;
end;
procedure Expect(c:WideChar;const msg:string);
begin
while (i<l) and (json.Data[i]<=' ') do inc(i);
if (i<l) and (json.Data[i]=c) then
inc(i)
else
{$IFDEF JSONDOC_JSON_LOOSE}
;//silent