forked from do-/steludio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
superobject.pas
4266 lines (3934 loc) · 112 KB
/
superobject.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
(*
* Super Object Toolkit
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <[email protected]>
*
* This unit is inspired from the json c lib:
* Michael Clark <[email protected]>
* http://oss.metaparadigm.com/json-c/
*
* CHANGES:
* v1.0
* + renamed class
* + interfaced object
* + added a new data type: the method
* + parser can now evaluate properties and call methods
* - removed obselet rpc class
* - removed "find" method, now you can use "parse" method instead
* v0.6
* + refactoring
* v0.5
* + new find method to get or set value using a path syntax
* ex: obj.s['obj.prop[1]'] := 'string value';
* obj.a['@obj.array'].b[n] := true; // @ -> create property if necessary
* v0.4
* + bug corrected: AVL tree badly balanced.
* v0.3
* + New validator partially based on the Kwalify syntax.
* + extended syntax to parse unquoted fields.
* + Freepascal compatibility win32/64 Linux32/64.
* + JavaToDelphiDateTime and DelphiToJavaDateTime improved for UTC.
* + new TJsonObject.Compare function.
* v0.2
* + Hashed string list replaced with a faster AVL tree
* + JsonInt data type can be changed to int64
* + JavaToDelphiDateTime and DelphiToJavaDateTime helper fonctions
* + from json-c v0.7
* + Add escaping of backslash to json output
* + Add escaping of foward slash on tokenizing and output
* + Changes to internal tokenizer from using recursion to
* using a depth state structure to allow incremental parsing
* v0.1
* + first release
*)
unit superobject;
{$IFDEF FPC}
{$MODE OBJFPC}{$H+}
{$ENDIF}
interface
uses Classes;
{$DEFINE SUPER_LARGE_INT}
{$DEFINE SUPER_EXTENDED_SYNTAX}
{$DEFINE SUPER_METHOD}
type
{$IFNDEF FPC}
PtrInt = longint;
PtrUInt = Longword;
{$ENDIF}
{$IFDEF SUPER_LARGE_INT}
SuperInt = Int64;
{$ELSE}
SuperInt = Integer;
{$ENDIF}
const
SUPER_ARRAY_LIST_DEFAULT_SIZE = 32;
SUPER_TOKENER_MAX_DEPTH = 32;
SUPER_AVL_MAX_DEPTH = sizeof(longint) * 8;
SUPER_AVL_MASK_HIGH_BIT = not ((not longword(0)) shr 1);
type
// forward declarations
TSuperObject = class;
ISuperObject = interface;
TSuperArray = class;
(* AVL Tree
* This is a "special" autobalanced AVL tree
* It use a hash value for fast compare
*)
TSuperAvlBitArray = set of 0..SUPER_AVL_MAX_DEPTH - 1;
TSuperAvlSearchType = (stEQual, stLess, stGreater);
TSuperAvlSearchTypes = set of TSuperAvlSearchType;
TSuperAvlIterator = class;
TSuperAvlEntry = class
private
FGt, FLt: TSuperAvlEntry;
FBf: integer;
FHash: Cardinal;
FName: PChar;
FPtr: Pointer;
function GetValue: ISuperObject;
procedure SetValue(const val: ISuperObject);
public
class function Hash(k: PChar): Cardinal; virtual;
constructor Create(AName: PChar; Obj: Pointer); virtual;
destructor Destroy; override;
property Name: PChar read FName;
property Ptr: Pointer read FPtr;
property Value: ISuperObject read GetValue write SetValue;
end;
TSuperAvlTree = class
private
FRoot: TSuperAvlEntry;
FCount: Integer;
function balance(bal: TSuperAvlEntry): TSuperAvlEntry;
protected
procedure doDeleteEntry(Entry: TSuperAvlEntry; all: boolean); virtual;
function CompareNodeNode(node1, node2: TSuperAvlEntry): integer; virtual;
function CompareKeyNode(k: PChar; h: TSuperAvlEntry): integer; virtual;
function Insert(h: TSuperAvlEntry): TSuperAvlEntry; virtual;
function Search(k: PChar; st: TSuperAvlSearchTypes = [stEqual]): TSuperAvlEntry; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function IsEmpty: boolean;
procedure Clear(all: boolean = false); virtual;
procedure Delete(k: PChar);
function GetEnumerator: TSuperAvlIterator;
property count: Integer read FCount;
end;
TSuperTableString = class(TSuperAvlTree)
protected
procedure doDeleteEntry(Entry: TSuperAvlEntry; all: boolean); override;
public
function Put(k: PChar; Obj: ISuperObject): ISuperObject;
function Get(k: PChar): ISuperObject;
function GetValues: ISuperObject;
function GetNames: ISuperObject;
end;
TSuperAvlIterator = class
private
FTree: TSuperAvlTree;
FBranch: TSuperAvlBitArray;
FDepth: longint;
FPath: array[0..SUPER_AVL_MAX_DEPTH - 2] of TSuperAvlEntry;
public
constructor Create(tree: TSuperAvlTree); virtual;
procedure Search(k: PChar; st: TSuperAvlSearchTypes = [stEQual]);
procedure First;
procedure Last;
function GetIter: TSuperAvlEntry;
procedure Next;
procedure Prior;
// delphi enumerator
function MoveNext: boolean;
property Current: TSuperAvlEntry read GetIter;
end;
TSuperObjectArray = array[0..(high(PtrInt) div sizeof(TSuperObject))-1] of ISuperObject;
PSuperObjectArray = ^TSuperObjectArray;
{$IFDEF SUPER_METHOD}
TSuperMethod = procedure(This, Params: ISuperObject; var Result: ISuperObject);
{$ENDIF}
TSuperArray = class
private
FArray: PSuperObjectArray;
FLength: Integer;
FSize: Integer;
function Expand(max: Integer): Integer;
protected
function GetO(const index: integer): ISuperObject;
procedure PutO(const index: integer; Value: ISuperObject);
function GetB(const index: integer): Boolean;
procedure PutB(const index: integer; Value: Boolean);
function GetI(const index: integer): SuperInt;
procedure PutI(const index: integer; Value: SuperInt);
function GetD(const index: integer): Double;
procedure PutD(const index: integer; Value: Double);
function GetS(const index: integer): string;
procedure PutS(const index: integer; const Value: string);
{$IFDEF SUPER_METHOD}
function GetM(const index: integer): TSuperMethod;
procedure PutM(const index: integer; Value: TSuperMethod);
{$ENDIF}
function GetA(const index: integer): TSuperArray;
public
constructor Create; virtual;
destructor Destroy; override;
function Add(Data: ISuperObject): Integer;
procedure Clear(all: boolean = false);
property Length: Integer read FLength;
property O[const index: integer]: ISuperObject read GetO write PutO; default;
property B[const index: integer]: boolean read GetB write PutB;
property I[const index: integer]: SuperInt read GetI write PutI;
property D[const index: integer]: Double read GetD write PutD;
property S[const index: integer]: string read GetS write PutS;
{$IFDEF SUPER_METHOD}
property M[const index: integer]: TSuperMethod read GetM write PutM;
{$ENDIF}
property A[const index: integer]: TSuperArray read GetA;
end;
TSuperWriter = class
protected
// abstact methods to overide
function Append(buf: PChar; Size: Integer): Integer; overload; virtual; abstract;
function Append(buf: PChar): Integer; overload; virtual; abstract;
procedure Reset; virtual; abstract;
public
function Write(obj: ISuperObject; format: boolean; level: integer): Integer; virtual;
end;
TSuperWriterString = class(TSuperWriter)
private
FBuf: PChar;
FBPos: integer;
FSize: integer;
protected
function Append(buf: PChar; Size: Integer): Integer; overload; override;
function Append(buf: PChar): Integer; overload; override;
procedure Reset; override;
public
constructor Create; virtual;
destructor Destroy; override;
property Data: PChar read FBuf;
property Size: Integer read FSize;
property Position: integer read FBPos;
end;
TSuperWriterStream = class(TSuperWriter)
private
FStream: TStream;
protected
function Append(buf: PChar; Size: Integer): Integer; override;
function Append(buf: PChar): Integer; override;
procedure Reset; override;
public
constructor Create(AStream: TStream); reintroduce; virtual;
end;
TSuperWriterFake = class(TSuperWriter)
private
FSize: Integer;
protected
function Append(buf: PChar; Size: Integer): Integer; override;
function Append(buf: PChar): Integer; override;
procedure Reset; override;
public
constructor Create; reintroduce; virtual;
property size: integer read FSize;
end;
TSuperWriterSock = class(TSuperWriter)
private
FSocket: longint;
FSize: Integer;
protected
function Append(buf: PChar; Size: Integer): Integer; override;
function Append(buf: PChar): Integer; override;
procedure Reset; override;
public
constructor Create(ASocket: longint); reintroduce; virtual;
property Socket: longint read FSocket;
property Size: Integer read FSize;
end;
TSuperTokenizerError = (
teSuccess,
teContinue,
teDepth,
teParseEof,
teParseUnexpected,
teParseNull,
teParseBoolean,
teParseNumber,
teParseArray,
teParseObjectKeyName,
teParseObjectKeySep,
teParseObjectValueSep,
teParseString,
teParseComment,
teEvalObject,
teEvalArray,
teEvalMethod,
teEvalInt
);
TSuperTokenerState = (
tsEatws,
tsStart,
tsFinish,
tsNull,
tsCommentStart,
tsComment,
tsCommentEol,
tsCommentEnd,
tsString,
tsStringEscape,
{$IFDEF SUPER_EXTENDED_SYNTAX}
tsIdentifier,
{$ENDIF}
tsEscapeUnicode,
tsBoolean,
tsNumber,
tsArray,
tsArrayAdd,
tsArraySep,
tsObjectFieldStart,
tsObjectField,
{$IFDEF SUPER_EXTENDED_SYNTAX}
tsObjectUnquotedField,
{$ENDIF}
tsObjectFieldEnd,
tsObjectValue,
tsObjectValueAdd,
tsObjectSep,
tsEvalProperty,
tsEvalArray,
tsEvalMethod,
tsParamValue,
tsParamPut
);
PSuperTokenerSrec = ^TSuperTokenerSrec;
TSuperTokenerSrec = record
state, saved_state: TSuperTokenerState;
obj: ISuperObject;
current: ISuperObject;
field_name: PChar;
parent: ISuperObject;
gparent: ISuperObject;
end;
TSuperTokenizer = class
public
str: PChar;
pb: TSuperWriterString;
depth, is_double, st_pos, char_offset: Integer;
err: TSuperTokenizerError;
ucs_char: Cardinal;
quote_char: char;
stack: array[0..SUPER_TOKENER_MAX_DEPTH-1] of TSuperTokenerSrec;
public
constructor Create; virtual;
destructor Destroy; override;
procedure ResetLevel(adepth: integer);
procedure Reset;
end;
// supported object types
TSuperType = (
stNull,
stBoolean,
stDouble,
stInt,
stObject,
stArray,
stString
{$IFDEF SUPER_METHOD}
,stMethod
{$ENDIF}
);
TSuperValidateError = (
veRuleMalformated,
veFieldIsRequired,
veInvalidDataType,
veFieldNotFound,
veUnexpectedField,
veDuplicateEntry,
veValueNotInEnum,
veInvalidLength,
veInvalidRange
);
TSuperFindOption = (
foCreatePath,
foPutValue
{$IFDEF SUPER_METHOD}
,foCallMethod
{$ENDIF}
);
TSuperFindOptions = set of TSuperFindOption;
TSuperCompareResult = (cpLess, cpEqu, cpGreat, cpError);
TSuperOnValidateError = procedure(sender: Pointer; error: TSuperValidateError; const objpath: string);
ISuperObject = interface
['{4B86A9E3-E094-4E5A-954A-69048B7B6327}']
function GetDataType: TSuperType;
function GetProcessing: boolean;
procedure SetProcessing(value: boolean);
function GetO(const path: string): ISuperObject;
procedure PutO(const path: string; Value: ISuperObject);
function GetB(const path: string): Boolean;
procedure PutB(const path: string; Value: Boolean);
function GetI(const path: string): SuperInt;
procedure PutI(const path: string; Value: SuperInt);
function GetD(const path: string): Double;
procedure PutD(const path: string; Value: Double);
function GetS(const path: string): string;
procedure PutS(const path: string; const Value: string);
{$IFDEF SUPER_METHOD}
function GetM(const path: string): TSuperMethod;
procedure PutM(const path: string; Value: TSuperMethod);
{$ENDIF}
function GetA(const path: string): TSuperArray;
// Writers
function SaveTo(stream: TStream; format: boolean = false): integer; overload;
function SaveTo(const FileName: string; format: boolean = false): integer; overload;
function SaveTo(socket: longint; format: boolean = false): integer; overload;
function CalcSize(format: boolean = false): integer;
// convert
function AsBoolean: Boolean;
function AsInteger: SuperInt;
function AsDouble: Double;
function AsString: PChar;
function AsArray: TSuperArray;
function AsObject: TSuperTableString;
{$IFDEF SUPER_METHOD}
function AsMethod: TSuperMethod;
{$ENDIF}
function AsJSon(format: boolean = false): PChar;
procedure Clear(all: boolean = false);
property O[const path: string]: ISuperObject read GetO write PutO; default;
property B[const path: string]: boolean read GetB write PutB;
property I[const path: string]: SuperInt read GetI write PutI;
property D[const path: string]: Double read GetD write PutD;
property S[const path: string]: string read GetS write PutS;
{$IFDEF SUPER_METHOD}
property M[const path: string]: TSuperMethod read GetM write PutM;
{$ENDIF}
property A[const path: string]: TSuperArray read GetA;
{$IFDEF SUPER_METHOD}
function call(const path: string; param: ISuperObject = nil): ISuperObject; overload;
function call(const path, param: string): ISuperObject; overload;
{$ENDIF}
// clone a node
function Clone: ISuperObject;
// merges tow objects of same type, if reference is true then nodes are not cloned
procedure Merge(obj: ISuperObject; reference: boolean = false); overload;
procedure Merge(const str: string); overload;
// validate methods
function Validate(const rules: string; const defs: string = ''; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
function Validate(rules: ISuperObject; defs: ISuperObject = nil; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
// compare
function Compare(obj: ISuperObject): TSuperCompareResult; overload;
function Compare(const str: string): TSuperCompareResult; overload;
// the data type
function IsType(AType: TSuperType): boolean;
property DataType: TSuperType read GetDataType;
property Processing: boolean read GetProcessing write SetProcessing;
function GetDataPtr: Pointer;
procedure SetDataPtr(const Value: Pointer);
property DataPtr: Pointer read GetDataPtr write SetDataPtr;
end;
TSuperObject = class(TObject, ISuperObject)
private
FRefCount: Integer;
FProcessing: boolean;
FDataType: TSuperType;
Fpb: TSuperWriterString;
FDataPtr: Pointer;
FO: record
case TSuperType of
stBoolean: (c_boolean: boolean);
stDouble: (c_double: double);
stInt: (c_int: SuperInt);
stObject: (c_object: TSuperTableString);
stArray: (c_array: TSuperArray);
stString: (c_string: PChar);
{$IFDEF SUPER_METHOD}
stMethod: (c_method: TSuperMethod);
{$ENDIF}
end;
function GetDataType: TSuperType;
function GetDataPtr: Pointer;
procedure SetDataPtr(const Value: Pointer);
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
function _AddRef: Integer; virtual; stdcall;
function _Release: Integer; virtual; stdcall;
function GetO(const path: string): ISuperObject;
procedure PutO(const path: string; Value: ISuperObject);
function GetB(const path: string): Boolean;
procedure PutB(const path: string; Value: Boolean);
function GetI(const path: string): SuperInt;
procedure PutI(const path: string; Value: SuperInt);
function GetD(const path: string): Double;
procedure PutD(const path: string; Value: Double);
function GetS(const path: string): string;
procedure PutS(const path: string; const Value: string);
{$IFDEF SUPER_METHOD}
function GetM(const path: string): TSuperMethod;
procedure PutM(const path: string; Value: TSuperMethod);
{$ENDIF}
function GetA(const path: string): TSuperArray;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
function GetProcessing: boolean;
procedure SetProcessing(value: boolean);
// Writers
function SaveTo(stream: TStream; format: boolean = false): integer; overload;
function SaveTo(const FileName: string; format: boolean = false): integer; overload;
function SaveTo(socket: longint; format: boolean = false): integer; overload;
function CalcSize(format: boolean = false): integer;
function AsJSon(format: boolean = false): PChar;
// parser ... owned!
class function Parse(s: PChar; partial: boolean = true; this: ISuperObject = nil; options: TSuperFindOptions = [];
put: ISuperObject = nil; dt: TSuperType = stNull): ISuperObject;
class function ParseEx(tok: TSuperTokenizer; str: PChar; len: integer; this: ISuperObject = nil;
options: TSuperFindOptions = []; put: ISuperObject = nil; dt: TSuperType = stNull): ISuperObject;
// constructors / destructor
constructor Create(jt: TSuperType = stObject); overload; virtual;
constructor Create(b: boolean); overload; virtual;
constructor Create(i: SuperInt); overload; virtual;
constructor Create(d: double); overload; virtual;
constructor Create(p: PChar); overload; virtual;
constructor Create(const s: string); overload; virtual;
{$IFDEF SUPER_METHOD}
constructor Create(m: TSuperMethod); overload; virtual;
{$ENDIF}
destructor Destroy; override;
// convert
function AsBoolean: Boolean;
function AsInteger: SuperInt;
function AsDouble: Double;
function AsString: PChar;
function AsArray: TSuperArray;
function AsObject: TSuperTableString;
{$IFDEF SUPER_METHOD}
function AsMethod: TSuperMethod;
{$ENDIF}
procedure Clear(all: boolean = false); virtual;
property O[const path: string]: ISuperObject read GetO write PutO; default;
property B[const path: string]: boolean read GetB write PutB;
property I[const path: string]: SuperInt read GetI write PutI;
property D[const path: string]: Double read GetD write PutD;
property S[const path: string]: string read GetS write PutS;
{$IFDEF SUPER_METHOD}
property M[const path: string]: TSuperMethod read GetM write PutM;
{$ENDIF}
property A[const path: string]: TSuperArray read GetA;
{$IFDEF SUPER_METHOD}
function call(const path: string; param: ISuperObject = nil): ISuperObject; overload; virtual;
function call(const path, param: string): ISuperObject; overload; virtual;
{$ENDIF}
// clone a node
function Clone: ISuperObject;
// merges tow objects of same type, if reference is true then nodes are not cloned
procedure Merge(obj: ISuperObject; reference: boolean = false); overload;
procedure Merge(const str: string); overload;
// validate methods
function Validate(const rules: string; const defs: string = ''; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
function Validate(rules: ISuperObject; defs: ISuperObject = nil; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
// compare
function Compare(obj: ISuperObject): TSuperCompareResult; overload;
function Compare(const str: string): TSuperCompareResult; overload;
// the data type
function IsType(AType: TSuperType): boolean;
property DataType: TSuperType read GetDataType;
// a data pointer to link to something ele, a treeview for example
property DataPtr: Pointer read GetDataPtr write SetDataPtr;
property Processing: boolean read GetProcessing;
end;
TSuperObjectIter = record
key: PChar;
val: ISuperObject;
Ite: TSuperAvlIterator;
end;
function ObjectIsError(obj: TSuperObject): boolean;
function ObjectIsType(obj: ISuperObject; typ: TSuperType): boolean;
function ObjectGetType(obj: ISuperObject): TSuperType;
function ObjectFindFirst(obj: ISuperObject; var F: TSuperObjectIter): boolean;
function ObjectFindNext(var F: TSuperObjectIter): boolean;
procedure ObjectFindClose(var F: TSuperObjectIter);
function SO(const s: string = '{}'): ISuperObject;
function JavaToDelphiDateTime(const dt: int64): TDateTime;
function DelphiToJavaDateTime(const dt: TDateTime): int64;
implementation
uses sysutils,
{$IFDEF UNIX}
baseunix, unix
{$ELSE}
Windows
{$ENDIF}
{$IFDEF FPC}
,sockets
{$ELSE}
,WinSock
{$ENDIF};
{$IFDEF DEBUG}
var
debugcount: integer = 0;
{$ENDIF}
const
super_number_chars = '0123456789.+-e';
super_number_chars_set = ['0'..'9','.','+','-','e'];
super_hex_chars = '0123456789abcdef';
super_hex_chars_set = ['0'..'9','a'..'f'];
{$IFDEF UNIX}
{$linklib c}
function sprintf(buffer, format: PChar; const args: array of const): longint; cdecl; external;
{$ENDIF}
{$ifdef MSWINDOWS}
function sprintf(buffer, format: PChar): longint; varargs; cdecl; external 'msvcrt.dll';
{$endif}
{$IFDEF UNIX}
function GetTimeBias: integer;
var
TimeVal: TTimeVal;
TimeZone: TTimeZone;
begin
fpGetTimeOfDay(@TimeVal, @TimeZone);
Result := TimeZone.tz_minuteswest;
end;
{$ELSE}
function GetTimeBias: integer;
var
tzi : TTimeZoneInformation;
begin
if GetTimeZoneInformation (tzi) = TIME_ZONE_ID_DAYLIGHT then
Result := tzi.Bias + tzi.DaylightBias else
Result := tzi.Bias;
end;
{$ENDIF}
function JavaToDelphiDateTime(const dt: int64): TDateTime;
begin
Result := 25569 + ((dt - (GetTimeBias * 60000)) / 86400000);
end;
function DelphiToJavaDateTime(const dt: TDateTime): int64;
begin
Result := Round((dt - 25569) * 86400000) + (GetTimeBias * 60000);
end;
function FloatToStr(d: Double): string;
var
buffer: array[0..255] of char;
p1, p2: PChar;
begin
{$IFDEF UNIX}
sprintf(buffer, '%lf', [d]);
{$ELSE}
sprintf(buffer, '%lf', d);
{$ENDIF}
p1 := @buffer[0];
p2 := nil;
while true do
begin
case p1^ of
'.', '1'..'9': p2 := p1;
'0':;
else
Break
end;
inc(p1);
end;
if p2 <> nil then p2[1] := #0;
Result := buffer;
end;
function strdup(s: PChar): PChar;
var
l: Integer;
begin
if s <> nil then
begin
l := StrLen(s);
GetMem(Result, l+1);
move(s^, Result^, l);
Result[l] := #0;
end else
Result := nil;
end;
function SO(const s: string): ISuperObject;
begin
Result := TSuperObject.Parse(PChar(s));
end;
function ObjectIsError(obj: TSuperObject): boolean;
begin
Result := PtrUInt(obj) > PtrUInt(-4000);
end;
function ObjectIsType(obj: ISuperObject; typ: TSuperType): boolean;
begin
if obj <> nil then
Result := typ = obj.DataType else
Result := typ = stNull;
end;
function ObjectGetType(obj: ISuperObject): TSuperType;
begin
if obj <> nil then
Result := obj.DataType else
Result := stNull;
end;
function ObjectFindFirst(obj: ISuperObject; var F: TSuperObjectIter): boolean;
var
i: TSuperAvlEntry;
begin
if ObjectIsType(obj, stObject) then
begin
F.Ite := TSuperAvlIterator.Create(obj.AsObject);
F.Ite.First;
i := F.Ite.GetIter;
if i <> nil then
begin
f.key := i.Name;
f.val := i.Value;
Result := true;
end else
Result := False;
end else
Result := False;
end;
function ObjectFindNext(var F: TSuperObjectIter): boolean;
var
i: TSuperAvlEntry;
begin
F.Ite.Next;
i := F.Ite.GetIter;
if i <> nil then
begin
f.key := i.FName;
f.val := i.Value;
Result := true;
end else
Result := False;
end;
procedure ObjectFindClose(var F: TSuperObjectIter);
begin
F.Ite.Free;
F.val := nil;
end;
{ TSuperObject }
constructor TSuperObject.Create(jt: TSuperType);
begin
inherited Create;
{$IFDEF DEBUG}
InterlockedIncrement(debugcount);
{$ENDIF}
FProcessing := false;
FDataPtr := nil;
FDataType := jt;
case FDataType of
stObject: FO.c_object := TSuperTableString.Create;
stArray: FO.c_array := TSuperArray.Create;
else
FO.c_object := nil;
end;
Fpb := nil;
end;
constructor TSuperObject.Create(b: boolean);
begin
Create(stBoolean);
FO.c_boolean := b;
end;
constructor TSuperObject.Create(i: SuperInt);
begin
Create(stInt);
FO.c_int := i;
end;
constructor TSuperObject.Create(d: double);
begin
Create(stDouble);
FO.c_double := d;
end;
constructor TSuperObject.Create(p: PChar);
begin
Create(stString);
FO.c_string := strdup(p);
end;
destructor TSuperObject.Destroy;
begin
{$IFDEF DEBUG}
InterlockedDecrement(debugcount);
{$ENDIF}
case FDataType of
stObject: FO.c_object.Free;
stString: FreeMem(FO.c_string);
stArray: FO.c_array.Free;
end;
if Fpb <> nil then Fpb.Free;
inherited;
end;
function TSuperObject.IsType(AType: TSuperType): boolean;
begin
Result := AType = FDataType;
end;
function TSuperObject.AsBoolean: boolean;
begin
case FDataType of
stBoolean: Result := FO.c_boolean;
stInt: Result := (FO.c_int <> 0);
stDouble: Result := (FO.c_double <> 0);
stString: Result := (strlen(FO.c_string) <> 0);
else
Result := True;
end;
end;
function TSuperObject.AsInteger: SuperInt;
var
code: integer;
cint: SuperInt;
begin
case FDataType of
stInt: Result := FO.c_int;
stDouble: Result := round(FO.c_double);
stBoolean: Result := ord(FO.c_boolean);
stString:
begin
Val(FO.c_string, cint, code);
if code = 0 then
Result := cint else
Result := 0;
end;
else
Result := 0;
end;
end;
function TSuperObject.AsDouble: Double;
var
code: integer;
cdouble: double;
begin
case FDataType of
stDouble: Result := FO.c_double;
stInt: Result := FO.c_int;
stBoolean: Result := ord(FO.c_boolean);
stString:
begin
Val(FO.c_string, cdouble, code);
if code = 0 then
Result := cdouble else
Result := 0.0;
end;
else
Result := 0.0;
end;
end;
function TSuperObject.AsString: PChar;
begin
if FDataType = stString then
Result := FO.c_string else
Result := AsJSon(false);
end;
procedure TSuperObject.AfterConstruction;
begin
InterlockedDecrement(FRefCount);
end;
procedure TSuperObject.BeforeDestruction;
begin
if RefCount <> 0 then
raise Exception.Create('Invalid pointer');
end;
function TSuperObject.AsArray: TSuperArray;
begin
if FDataType = stArray then
Result := FO.c_array else
Result := nil;
end;
function TSuperObject.AsObject: TSuperTableString;
begin
if FDataType = stObject then
Result := FO.c_object else
Result := nil;
end;
function TSuperObject.AsJSon(format: boolean): PChar;
begin
if(Fpb = nil) then
Fpb := TSuperWriterString.Create else
Fpb.Reset;
if(Fpb.Write(self, format, 0) < 0) then
begin
Result := '';
Exit;
end;
if Fpb.FBPos > 0 then
Result := Fpb.FBuf else
Result := '';
end;
class function TSuperObject.Parse(s: PChar; partial: boolean; this: ISuperObject;
options: TSuperFindOptions; put: ISuperObject; dt: TSuperType): ISuperObject;
var
tok: TSuperTokenizer;
obj: ISuperObject;
begin
tok := TSuperTokenizer.Create;
obj := ParseEx(tok, s, -1, this, options, put, dt);
if(tok.err <> teSuccess) or (not partial and (s[tok.char_offset] <> #0)) then
Result := nil else
Result := obj;
tok.Free;
end;
class function TSuperObject.ParseEx(tok: TSuperTokenizer; str: PChar; len: integer;
this: ISuperObject; options: TSuperFindOptions; put: ISuperObject; dt: TSuperType): ISuperObject;
function hexdigit(x: char): byte;
begin
if x <= '9' then
Result := byte(x) - byte('0') else
Result := (byte(x) and 7) + 9;
end;
function min(v1, v2: integer): integer; begin if v1 < v2 then result := v1 else result := v2 end;
var
obj: ISuperObject;
c: char;
utf_out: array[0..2] of byte;
{$IFDEF SUPER_METHOD}
sm: TSuperMethod;
{$ENDIF}
numi: SuperInt;
numd: double;
code: integer;
TokRec: PSuperTokenerSrec;
{$IFDEF SUPER_EXTENDED_SYNTAX}
evalstack: integer;
{$ENDIF}
const
spaces = [' ',#8,#10,#13,#9];
alphanum = ['-','_','a'..'z','A'..'Z','0'..'9'];