Debian Codegraph @

src/scene/load/pasgltf/CastlePasJSON.pas

raw
1 (******************************************************************************
2 * PasJSON *
3 ******************************************************************************
4 * Version 2020-03-04-02-20 *
5 ******************************************************************************
6 * zlib license *
7 *============================================================================*
8 * *
9 * Copyright (C) 2016-2020, Benjamin Rosseaux ([email protected]) *
10 * *
11 * This software is provided 'as-is', without any express or implied *
12 * warranty. In no event will the authors be held liable for any damages *
13 * arising from the use of this software. *
14 * *
15 * Permission is granted to anyone to use this software for any purpose, *
16 * including commercial applications, and to alter it and redistribute it *
17 * freely, subject to the following restrictions: *
18 * *
19 * 1. The origin of this software must not be misrepresented; you must not *
20 * claim that you wrote the original software. If you use this software *
21 * in a product, an acknowledgement in the product documentation would be *
22 * appreciated but is not required. *
23 * 2. Altered source versions must be plainly marked as such, and must not be *
24 * misrepresented as being the original software. *
25 * 3. This notice may not be removed or altered from any source distribution. *
26 * *
27 ******************************************************************************
28 * General guidelines for code contributors *
29 *============================================================================*
30 * *
31 * 1. Make sure you are legally allowed to make a contribution under the zlib *
32 * license. *
33 * 2. The zlib license header goes at the top of each source file, with *
34 * appropriate copyright notice. *
35 * 3. After a pull request, check the status of your pull request on *
36 * http://github.com/BeRo1985/pasjson *
37 * 4. Write code which's compatible with newer modern Delphi versions and *
38 * FreePascal >= 3.0.0 *
39 * 5. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
40 * but if needed, make it out-ifdef-able. *
41 * 6. No use of third-party libraries/units as possible, but if needed, make *
42 * it out-ifdef-able. *
43 * 7. Try to use const when possible. *
44 * 8. Make sure to comment out writeln, used while debugging. *
45 * 9. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
46 * x86-64, ARM, ARM64, etc.). *
47 * *
48 ******************************************************************************)
49 unit CastlePasJSON;
50 {$ifdef fpc}
51 {$mode delphi}
52 {$ifdef cpui386}
53 {$define cpu386}
54 {$endif}
55 {$ifdef cpu386}
56 {$asmmode intel}
57 {$endif}
58 {$ifdef cpuamd64}
59 {$asmmode intel}
60 {$endif}
61 {$ifdef FPC_LITTLE_ENDIAN}
62 {$define LITTLE_ENDIAN}
63 {$else}
64 {$ifdef FPC_BIG_ENDIAN}
65 {$define BIG_ENDIAN}
66 {$endif}
67 {$endif}
68 {-$pic off}
69 {$ifdef fpc_has_internal_sar}
70 {$define HasSAR}
71 {$endif}
72 {$ifdef FPC_HAS_TYPE_EXTENDED}
73 {$define HAS_TYPE_EXTENDED}
74 {$else}
75 {$undef HAS_TYPE_EXTENDED}
76 {$endif}
77 {$ifdef FPC_HAS_TYPE_DOUBLE}
78 {$define HAS_TYPE_DOUBLE}
79 {$else}
80 {$undef HAS_TYPE_DOUBLE}
81 {$endif}
82 {$ifdef FPC_HAS_TYPE_SINGLE}
83 {$define HAS_TYPE_SINGLE}
84 {$else}
85 {$undef HAS_TYPE_SINGLE}
86 {$endif}
87 {$define CAN_INLINE}
88 {$define HAS_ADVANCED_RECORDS}
89 {$else}
90 {$warn IMPLICIT_STRING_CAST off} // CGE added
91 {$realcompatibility off}
92 {$localsymbols on}
93 {$define LITTLE_ENDIAN}
94 {$ifndef cpu64}
95 {$define cpu32}
96 {$endif}
97 {$define HAS_TYPE_EXTENDED}
98 {$define HAS_TYPE_DOUBLE}
99 {$define HAS_TYPE_SINGLE}
100 {$undef CAN_INLINE}
101 {$undef HAS_ADVANCED_RECORDS}
102 {$ifndef BCB}
103 {$ifdef ver120}
104 {$define Delphi4or5}
105 {$endif}
106 {$ifdef ver130}
107 {$define Delphi4or5}
108 {$endif}
109 {$ifdef ver140}
110 {$define Delphi6}
111 {$endif}
112 {$ifdef ver150}
113 {$define Delphi7}
114 {$endif}
115 {$ifdef ver170}
116 {$define Delphi2005}
117 {$endif}
118 {$else}
119 {$ifdef ver120}
120 {$define Delphi4or5}
121 {$define BCB4}
122 {$endif}
123 {$ifdef ver130}
124 {$define Delphi4or5}
125 {$endif}
126 {$endif}
127 {$ifdef conditionalexpressions}
128 {$if CompilerVersion>=24.0}
129 {$legacyifend on}
130 {$ifend}
131 {$if CompilerVersion>=14.0}
132 {$if CompilerVersion=14.0}
133 {$define Delphi6}
134 {$ifend}
135 {$define Delphi6AndUp}
136 {$ifend}
137 {$if CompilerVersion>=15.0}
138 {$if CompilerVersion=15.0}
139 {$define Delphi7}
140 {$ifend}
141 {$define Delphi7AndUp}
142 {$ifend}
143 {$if CompilerVersion>=17.0}
144 {$if CompilerVersion=17.0}
145 {$define Delphi2005}
146 {$ifend}
147 {$define Delphi2005AndUp}
148 {$ifend}
149 {$if CompilerVersion>=18.0}
150 {$if CompilerVersion=18.0}
151 {$define BDS2006}
152 {$define Delphi2006}
153 {$ifend}
154 {$define Delphi2006AndUp}
155 {$define CAN_INLINE}
156 {$define HAS_ADVANCED_RECORDS}
157 {$ifend}
158 {$if CompilerVersion>=18.5}
159 {$if CompilerVersion=18.5}
160 {$define Delphi2007}
161 {$ifend}
162 {$define Delphi2007AndUp}
163 {$ifend}
164 {$if CompilerVersion=19.0}
165 {$define Delphi2007Net}
166 {$ifend}
167 {$if CompilerVersion>=20.0}
168 {$if CompilerVersion=20.0}
169 {$define Delphi2009}
170 {$ifend}
171 {$define Delphi2009AndUp}
172 {$ifend}
173 {$if CompilerVersion>=21.0}
174 {$if CompilerVersion=21.0}
175 {$define Delphi2010}
176 {$ifend}
177 {$define Delphi2010AndUp}
178 {$ifend}
179 {$if CompilerVersion>=22.0}
180 {$if CompilerVersion=22.0}
181 {$define DelphiXE}
182 {$ifend}
183 {$define DelphiXEAndUp}
184 {$ifend}
185 {$if CompilerVersion>=23.0}
186 {$if CompilerVersion=23.0}
187 {$define DelphiXE2}
188 {$ifend}
189 {$define DelphiXE2AndUp}
190 {$ifend}
191 {$if CompilerVersion>=24.0}
192 {$legacyifend on}
193 {$if CompilerVersion=24.0}
194 {$define DelphiXE3}
195 {$ifend}
196 {$define DelphiXE3AndUp}
197 {$ifend}
198 {$if CompilerVersion>=25.0}
199 {$if CompilerVersion=25.0}
200 {$define DelphiXE4}
201 {$ifend}
202 {$define DelphiXE4AndUp}
203 {$ifend}
204 {$if CompilerVersion>=26.0}
205 {$if CompilerVersion=26.0}
206 {$define DelphiXE5}
207 {$ifend}
208 {$define DelphiXE5AndUp}
209 {$ifend}
210 {$if CompilerVersion>=27.0}
211 {$if CompilerVersion=27.0}
212 {$define DelphiXE6}
213 {$ifend}
214 {$define DelphiXE6AndUp}
215 {$ifend}
216 {$if CompilerVersion>=28.0}
217 {$if CompilerVersion=28.0}
218 {$define DelphiXE7}
219 {$ifend}
220 {$define DelphiXE7AndUp}
221 {$ifend}
222 {$if CompilerVersion>=29.0}
223 {$if CompilerVersion=29.0}
224 {$define DelphiXE8}
225 {$ifend}
226 {$define DelphiXE8AndUp}
227 {$ifend}
228 {$if CompilerVersion>=30.0}
229 {$if CompilerVersion=30.0}
230 {$define Delphi10Seattle}
231 {$ifend}
232 {$define Delphi10SeattleAndUp}
233 {$ifend}
234 {$if CompilerVersion>=31.0}
235 {$if CompilerVersion=31.0}
236 {$define Delphi10Berlin}
237 {$ifend}
238 {$define Delphi10BerlinAndUp}
239 {$ifend}
240 {$endif}
241 {$ifndef Delphi4or5}
242 {$ifndef BCB}
243 {$define Delphi6AndUp}
244 {$endif}
245 {$ifndef Delphi6}
246 {$define BCB6OrDelphi7AndUp}
247 {$ifndef BCB}
248 {$define Delphi7AndUp}
249 {$endif}
250 {$ifndef BCB}
251 {$ifndef Delphi7}
252 {$ifndef Delphi2005}
253 {$define BDS2006AndUp}
254 {$endif}
255 {$endif}
256 {$endif}
257 {$endif}
258 {$endif}
259 {$ifdef Delphi6AndUp}
260 {$warn symbol_platform off}
261 {$warn symbol_deprecated off}
262 {$endif}
263 {$endif}
264 {$if defined(Win32) or defined(Win64)}
265 {$define Windows}
266 {$ifend}
267 {$rangechecks off}
268 {$extendedsyntax on}
269 {$writeableconst on}
270 {$hints off}
271 {$booleval off}
272 {$typedaddress off}
273 {$stackframes off}
274 {$varstringchecks on}
275 {$typeinfo on}
276 {$overflowchecks off}
277 {$longstrings on}
278 {$openstrings on}
279 {$ifndef HAS_TYPE_SINGLE}
280 {$error No single floating point precision}
281 {$endif}
282 {$ifndef HAS_TYPE_DOUBLE}
283 {$error No double floating point precision}
284 {$endif}
285 {$scopedenums on}
286 {$ifndef fpc}
287 {$ifdef conditionalexpressions}
288 {$if CompilerVersion>=24.0}
289 {$legacyifend on}
290 {$ifend}
291 {$endif}
292 {$endif}
293
294 interface
295
296 uses SysUtils,
297 Classes,
298 Math;
299
300 type PPPasJSONInt8=^PPasJSONInt8;
301 PPasJSONInt8=^TPasJSONInt8;
302 TPasJSONInt8={$ifdef fpc}Int8{$else}shortint{$endif};
303
304 PPPasJSONUInt8=^PPasJSONUInt8;
305 PPasJSONUInt8=^TPasJSONUInt8;
306 TPasJSONUInt8={$ifdef fpc}UInt8{$else}byte{$endif};
307
308 PPPasJSONUInt8Array=^PPasJSONUInt8Array;
309 PPasJSONUInt8Array=^TPasJSONUInt8Array;
310 TPasJSONUInt8Array=array[0..65535] of TPasJSONUInt8;
311
312 PPPasJSONInt16=^PPasJSONInt16;
313 PPasJSONInt16=^TPasJSONInt16;
314 TPasJSONInt16={$ifdef fpc}Int16{$else}smallint{$endif};
315
316 PPPasJSONUInt16=^PPasJSONUInt16;
317 PPasJSONUInt16=^TPasJSONUInt16;
318 TPasJSONUInt16={$ifdef fpc}UInt16{$else}word{$endif};
319
320 PPPasJSONInt32=^PPasJSONInt32;
321 PPasJSONInt32=^TPasJSONInt32;
322 TPasJSONInt32={$ifdef fpc}Int32{$else}Integer{$endif};
323
324 PPPasJSONUInt32=^PPasJSONUInt32;
325 PPasJSONUInt32=^TPasJSONUInt32;
326 TPasJSONUInt32={$ifdef fpc}UInt32{$else}Cardinal{$endif};
327
328 PPPasJSONInt64=^PPasJSONInt64;
329 PPasJSONInt64=^TPasJSONInt64;
330 TPasJSONInt64=Int64;
331
332 PPPasJSONUInt64=^PPasJSONUInt64;
333 PPasJSONUInt64=^TPasJSONUInt64;
334 TPasJSONUInt64=UInt64;
335
336 PPPasJSONChar=^PAnsiChar;
337 PPasJSONChar=PAnsiChar;
338 TPasJSONChar=AnsiChar;
339
340 PPPasJSONRawByteChar=^PAnsiChar;
341 PPasJSONRawByteChar=PAnsiChar;
342 TPasJSONRawByteChar=AnsiChar;
343
344 PPPasJSONUTF16Char=^PWideChar;
345 PPasJSONUTF16Char=PWideChar;
346 TPasJSONUTF16Char=WideChar;
347
348 PPPasJSONPointer=^PPasJSONPointer;
349 PPasJSONPointer=^TPasJSONPointer;
350 TPasJSONPointer=Pointer;
351
352 PPPasJSONPointers=^PPasJSONPointers;
353 PPasJSONPointers=^TPasJSONPointers;
354 TPasJSONPointers=array[0..65535] of TPasJSONPointer;
355
356 PPPasJSONVoid=^PPasJSONVoid;
357 PPasJSONVoid=TPasJSONPointer;
358
359 PPPasJSONFloat=^PPasJSONFloat;
360 PPasJSONFloat=^TPasJSONFloat;
361 TPasJSONFloat=Single;
362
363 TPasJSONFloats=array of TPasJSONFloat;
364
365 PPPasJSONDouble=^PPasJSONDouble;
366 PPasJSONDouble=^TPasJSONDouble;
367 TPasJSONDouble=Double;
368
369 PPPasJSONPtrUInt=^PPasJSONPtrUInt;
370 PPPasJSONPtrInt=^PPasJSONPtrInt;
371 PPasJSONPtrUInt=^TPasJSONPtrUInt;
372 PPasJSONPtrInt=^TPasJSONPtrInt;
373 {$ifdef fpc}
374 TPasJSONPtrUInt=PtrUInt;
375 TPasJSONPtrInt=PtrInt;
376 {$undef OldDelphi}
377 {$else}
378 {$ifdef conditionalexpressions}
379 {$if CompilerVersion>=23.0}
380 {$undef OldDelphi}
381 TPasJSONPtrUInt=NativeUInt;
382 TPasJSONPtrInt=NativeInt;
383 {$else}
384 {$define OldDelphi}
385 {$ifend}
386 {$else}
387 {$define OldDelphi}
388 {$endif}
389 {$endif}
390 {$ifdef OldDelphi}
391 {$ifdef cpu64}
392 TPasJSONPtrUInt=uint64;
393 TPasJSONPtrInt=int64;
394 {$else}
395 TPasJSONPtrUInt=Cardinal;
396 TPasJSONPtrInt=Integer;
397 {$endif}
398 {$endif}
399
400 PPPasJSONSizeUInt=^PPasJSONSizeUInt;
401 PPasJSONSizeUInt=^TPasJSONSizeUInt;
402 TPasJSONSizeUInt=TPasJSONPtrUInt;
403
404 PPPasJSONSizeInt=^PPasJSONSizeInt;
405 PPasJSONSizeInt=^TPasJSONSizeInt;
406 TPasJSONSizeInt=TPasJSONPtrInt;
407
408 PPPasJSONNativeUInt=^PPasJSONNativeUInt;
409 PPasJSONNativeUInt=^TPasJSONNativeUInt;
410 TPasJSONNativeUInt=TPasJSONPtrUInt;
411
412 PPPasJSONNativeInt=^PPasJSONNativeInt;
413 PPasJSONNativeInt=^TPasJSONNativeInt;
414 TPasJSONNativeInt=TPasJSONPtrInt;
415
416 PPPasJSONSize=^PPasJSONSizeUInt;
417 PPasJSONSize=^TPasJSONSizeUInt;
418 TPasJSONSize=TPasJSONPtrUInt;
419
420 PPPasJSONPtrDiff=^PPasJSONPtrDiff;
421 PPasJSONPtrDiff=^TPasJSONPtrDiff;
422 TPasJSONPtrDiff=TPasJSONPtrInt;
423
424 PPPasJSONRawByteString=^PPasJSONRawByteString;
425 PPasJSONRawByteString=^TPasJSONRawByteString;
426 TPasJSONRawByteString={$if declared(RawByteString)}RawByteString{$else}AnsiString{$ifend};
427
428 PPPasJSONUTF8String=^PPasJSONUTF8String;
429 PPasJSONUTF8String=^TPasJSONUTF8String;
430 TPasJSONUTF8String={$if declared(UTF8String)}UTF8String{$else}AnsiString{$ifend};
431
432 PPPasJSONUTF16String=^PPasJSONUTF16String;
433 PPasJSONUTF16String=^TPasJSONUTF16String;
434 TPasJSONUTF16String={$if declared(UnicodeString)}UnicodeString{$else}WideString{$ifend};
435
436 EPasJSONSyntaxError=class(Exception)
437 private
438 fPosition:TPasJSONSizeInt;
439 public
440 constructor Create(const aMessage:string;const aPosition:TPasJSONSizeInt); reintroduce;
441 published
442 property Position:TPasJSONSizeInt read fPosition write fPosition;
443 end;
444
445 EPasJSONMergeError=class(Exception);
446
447 TPasJSONMergeFlag=
448 (
449 ForceObjectPropertyValueDestinationType
450 );
451
452 TPasJSONMergeFlags=set of TPasJSONMergeFlag;
453
454 TPasJSONItem=class
455 public
456 constructor Create;
457 destructor Destroy; override;
458 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); virtual;
459 end;
460
461 TPasJSONItems=array of TPasJSONItem;
462
463 TPasJSONItemNull=class(TPasJSONItem)
464 public
465 constructor Create;
466 destructor Destroy; override;
467 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); override;
468 end;
469
470 TPasJSONItemBoolean=class(TPasJSONItem)
471 private
472 fValue:boolean;
473 public
474 constructor Create(const AValue:boolean);
475 destructor Destroy; override;
476 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); override;
477 published
478 property Value:boolean read fValue write fValue;
479 end;
480
481 TPasJSONItemNumber=class(TPasJSONItem)
482 private
483 fValue:TPasJSONDouble;
484 public
485 constructor Create(const AValue:TPasJSONDouble);
486 destructor Destroy; override;
487 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); override;
488 published
489 property Value:TPasJSONDouble read fValue write fValue;
490 end;
491
492 TPasJSONItemString=class(TPasJSONItem)
493 private
494 fValue:TPasJSONUTF8String;
495 public
496 constructor Create(const AValue:TPasJSONUTF8String);
497 destructor Destroy; override;
498 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); override;
499 published
500 property Value:TPasJSONUTF8String read fValue write fValue;
501 end;
502
503 TPasJSONItemObjectProperty=class
504 private
505 fKey:TPasJSONUTF8String;
506 fValue:TPasJSONItem;
507 public
508 constructor Create; reintroduce;
509 destructor Destroy; override;
510 published
511 property Key:TPasJSONUTF8String read fKey write fKey;
512 property Value:TPasJSONItem read fValue write fValue;
513 end;
514
515 TPasJSONItemObjectProperties=array of TPasJSONItemObjectProperty;
516
517 TPasJSONItemObject=class(TPasJSONItem)
518 public
519 type PPasJSONItemObjectEnumerator=^TPasJSONItemObjectEnumerator;
520 TPasJSONItemObjectEnumerator=record
521 private
522 fOwner:TPasJSONItemObject;
523 fIndex:TPasJSONSizeInt;
524 function GetCurrent:TPasJSONItemObjectProperty; inline;
525 public
526 constructor Create(const aOwner:TPasJSONItemObject);
527 function MoveNext:boolean; inline;
528 property Current:TPasJSONItemObjectProperty read GetCurrent;
529 end;
530 private
531 fProperties:TPasJSONItemObjectProperties;
532 fCount:TPasJSONSizeInt;
533 function GetKeyIndex(const aKey:TPasJSONUTF8String):TPasJSONInt32;
534 function GetKey(const aIndex:TPasJSONSizeInt):TPasJSONUTF8String;
535 procedure SetKey(const aIndex:TPasJSONSizeInt;const aKey:TPasJSONUTF8String);
536 function GetValue(const aIndex:TPasJSONSizeInt):TPasJSONItem;
537 procedure SetValue(const aIndex:TPasJSONSizeInt;const aItem:TPasJSONItem);
538 function GetProperty(const aKey:TPasJSONUTF8String):TPasJSONItem;
539 procedure SetProperty(const aKey:TPasJSONUTF8String;const aItem:TPasJSONItem);
540 public
541 constructor Create;
542 destructor Destroy; override;
543 function GetEnumerator:TPasJSONItemObjectEnumerator; inline;
544 procedure Clear;
545 procedure Add(const aKey:TPasJSONUTF8String;const aValue:TPasJSONItem);
546 procedure Delete(const aIndex:TPasJSONSizeInt); overload;
547 procedure Delete(const aKey:TPasJSONUTF8String); overload;
548 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); override;
549 property Count:TPasJSONSizeInt read fCount;
550 property Indices[const Key:TPasJSONUTF8String]:TPasJSONInt32 read GetKeyIndex;
551 property Keys[const Index:TPasJSONSizeInt]:TPasJSONUTF8String read GetKey write SetKey;
552 property Values[const Index:TPasJSONSizeInt]:TPasJSONItem read GetValue write SetValue;
553 property Properties[const Key:TPasJSONUTF8String]:TPasJSONItem read GetProperty write SetProperty; default;
554 end;
555
556 TPasJSONItemArray=class(TPasJSONItem)
557 public
558 type PPasJSONItemArrayEnumerator=^TPasJSONItemArrayEnumerator;
559 TPasJSONItemArrayEnumerator=record
560 private
561 fOwner:TPasJSONItemArray;
562 fIndex:TPasJSONSizeInt;
563 function GetCurrent:TPasJSONItem; inline;
564 public
565 constructor Create(const aOwner:TPasJSONItemArray);
566 function MoveNext:boolean; inline;
567 property Current:TPasJSONItem read GetCurrent;
568 end;
569 private
570 fItems:TPasJSONItems;
571 fCount:TPasJSONInt32;
572 function GetValue(const Index:TPasJSONInt32):TPasJSONItem;
573 procedure SetValue(const Index:TPasJSONInt32;const Item:TPasJSONItem);
574 public
575 constructor Create;
576 destructor Destroy; override;
577 function GetEnumerator:TPasJSONItemArrayEnumerator; inline;
578 procedure Clear;
579 procedure Add(const aValue:TPasJSONItem);
580 procedure Delete(const aIndex:TPasJSONSizeInt);
581 procedure Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]); override;
582 property Count:TPasJSONInt32 read fCount;
583 property Items[const Index:TPasJSONInt32]:TPasJSONItem read GetValue write SetValue; default;
584 end;
585
586 PPasJSONModeFlag=^TPasJSONModeFlag;
587 TPasJSONModeFlag=
588 (
589 UnquotedKeys,
590 Comments,
591 ImplicitRootObject,
592 OptionalCommas,
593 EqualsForColon,
594 MultilineStrings,
595 HexadecimalNumbers
596 );
597
598 PPasJSONModeFlags=^TPasJSONModeFlag;
599 TPasJSONModeFlags=set of TPasJSONModeFlag;
600
601 PPasJSONEncoding=^TPasJSONEncoding;
602 TPasJSONEncoding=
603 (
604 AutomaticDetection,
605 Latin1,
606 UTF8,
607 UTF16LE,
608 UTF16BE,
609 UTF32LE,
610 UTF32BE
611 );
612
613 TPasJSON=class
614 public
615 // Simplified JSON notation as in http://bitsquid.blogspot.de/2009/10/simplified-json-notation.html
616 const SimplifiedJSONModeFlags:TPasJSONModeFlags=[TPasJSONModeFlag.UnquotedKeys,
617 TPasJSONModeFlag.Comments,
618 TPasJSONModeFlag.ImplicitRootObject,
619 TPasJSONModeFlag.OptionalCommas,
620 TPasJSONModeFlag.EqualsForColon,
621 TPasJSONModeFlag.MultilineStrings];
622 public
623 class function StringQuote(const aString:TPasJSONUTF8String):TPasJSONRawByteString; static;
624 class function Parse(const aSource:TPasJSONRawByteString;const aModeFlags:TPasJSONModeFlags=[TPasJSONModeFlag.Comments];const aEncoding:TPasJSONEncoding=TPasJSONEncoding.AutomaticDetection):TPasJSONItem; overload; static;
625 class function Parse(const aStream:TStream;const aModeFlags:TPasJSONModeFlags=[TPasJSONModeFlag.Comments];const aEncoding:TPasJSONEncoding=TPasJSONEncoding.AutomaticDetection):TPasJSONItem; overload; static;
626 class function Stringify(const aJSONItem:TPasJSONItem;const aFormatting:boolean=false;const aModeFlags:TPasJSONModeFlags=[];const aLevel:TPasJSONInt32=0):TPasJSONRawByteString; static;
627 class procedure StringifyToStream(const aStream:TStream;const aJSONItem:TPasJSONItem;const aFormatting:boolean=false;const aModeFlags:TPasJSONModeFlags=[];const aLevel:TPasJSONInt32=0); static;
628 class function GetNumber(const aItem:TPasJSONItem;const aDefault:TPasJSONDouble=0.0):TPasJSONDouble; static;
629 class function GetInt64(const aItem:TPasJSONItem;const aDefault:TPasJSONInt64=0):TPasJSONInt64; static;
630 class function GetString(const aItem:TPasJSONItem;const aDefault:TPasJSONUTF8String=''):TPasJSONUTF8String; static;
631 class function GetBoolean(const aItem:TPasJSONItem;const aDefault:boolean=false):boolean; static;
632 class function LoadBinaryFromStream(const aStream:TStream):TPasJSONItem; static;
633 class procedure SaveBinaryToStream(const aStream:TStream;const aJSONItem:TPasJSONItem); static;
634 end;
635
636 implementation
637
638 uses CastlePasDblStrUtils;
639
640 //0 1 2 3 4 5 6 7 8 9 a b c d e f
641 const{UTF8CharSteps:array[AnsiChar] of byte=(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0
642 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 1
643 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 2
644 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 3
645 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 4
646 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 5
647 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 6
648 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 7
649 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 8
650 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 9
651 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // a
652 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // b
653 1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c
654 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // d
655 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // e
656 4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1); // f
657 //0 1 2 3 4 5 6 7 8 9 a b c d e f }
658
659 UTF8DFACharClasses:array[AnsiChar] of byte=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
660 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
661 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
662 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
663 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
664 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
665 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
666 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
667 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
668 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
669 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
670 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
671 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
672 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
673 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3,
674 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8);
675
676 UTF8DFATransitions:array[byte] of byte=(0,16,32,48,80,128,112,16,16,16,64,96,16,16,16,16,
677 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
678 16,0,16,16,16,16,16,0,16,0,16,16,16,16,16,16,
679 16,32,16,16,16,16,16,32,16,32,16,16,16,16,16,16,
680 16,16,16,16,16,16,16,32,16,16,16,16,16,16,16,16,
681 16,32,16,16,16,16,16,16,16,32,16,16,16,16,16,16,
682 16,16,16,16,16,16,16,48,16,48,16,16,16,16,16,16,
683 16,48,16,16,16,16,16,48,16,48,16,16,16,16,16,16,
684 16,48,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
685 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
686 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
687 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
688 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
689 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
690 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
691 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16);
692
693 suDONOTKNOW=-1;
694 suNOUTF8=0;
695 suPOSSIBLEUTF8=1;
696 suISUTF8=2;
697
698 ucACCEPT=0;
699 ucERROR=16;
700
701 function GetNextUTF8Char(const aString:PPasJSONRawByteChar;const aStringLength:TPasJSONInt32;var aCodeUnit:TPasJSONInt32):TPasJSONUInt32;
702 var StartCodeUnit,Value,CharClass,State:TPasJSONUInt32;
703 begin
704 result:=0;
705 if (aCodeUnit>0) and (aCodeUnit<=aStringLength) then begin
706 dec(aCodeUnit);
707 StartCodeUnit:=aCodeUnit;
708 State:=ucACCEPT;
709 while aCodeUnit<aStringLength do begin
710 Value:=byte(AnsiChar(aString[aCodeUnit]));
711 inc(aCodeUnit);
712 CharClass:=UTF8DFACharClasses[AnsiChar(Value)];
713 if State=ucACCEPT then begin
714 result:=Value and ($ff shr CharClass);
715 end else begin
716 result:=(result shl 6) or (Value and $3f);
717 end;
718 State:=UTF8DFATransitions[State+CharClass];
719 if State<=ucERROR then begin
720 break;
721 end;
722 end;
723 if State<>ucACCEPT then begin
724 result:=byte(AnsiChar(aString[StartCodeUnit]));
725 aCodeUnit:=StartCodeUnit+1;
726 end;
727 inc(aCodeUnit);
728 end;
729 end;
730
731 function ConvertUTF16ToUTF8(const aUTF16String:TPasJSONUTF16String):TPasJSONUTF8String;
732 begin
733 { Castle Game Engine:
734 We removed PasJSON algorithm for UTF-16 -> UTF-8 conversion.
735 Instead just let the compiler do automatic conversion UTF-16 -> UTF-8.
736 This works reliably and
737
738 - Fixes reading Chinese characters in texture in
739 https://github.com/castle-engine/castle-engine/issues/355
740
741 - Fixes Unicode test in glTF-Sample-Models on
742 https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/Unicode%E2%9D%A4%E2%99%BBTest
743 }
744
745 {$warnings off}
746 result:=aUTF16String;
747 {$warnings on}
748 end;
749
750 constructor EPasJSONSyntaxError.Create(const aMessage:string;const aPosition:TPasJSONSizeInt);
751 begin
752 inherited Create(aMessage);
753 fPosition:=aPosition;
754 end;
755
756 constructor TPasJSONItem.Create;
757 begin
758 inherited Create;
759 end;
760
761 destructor TPasJSONItem.Destroy;
762 begin
763 inherited Destroy;
764 end;
765
766 procedure TPasJSONItem.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
767 begin
768 if not (assigned(aWith) and (aWith is TPasJSONItem)) then begin
769 raise EPasJSONMergeError.Create('Incompatible data type');
770 end;
771 end;
772
773 constructor TPasJSONItemNull.Create;
774 begin
775 inherited Create;
776 end;
777
778 destructor TPasJSONItemNull.Destroy;
779 begin
780 inherited Destroy;
781 end;
782
783 procedure TPasJSONItemNull.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
784 begin
785 if not (assigned(aWith) and (aWith is TPasJSONItemNull)) then begin
786 raise EPasJSONMergeError.Create('Incompatible data type');
787 end;
788 end;
789
790 constructor TPasJSONItemBoolean.Create(const AValue:boolean);
791 begin
792 inherited Create;
793 fValue:=AValue;
794 end;
795
796 destructor TPasJSONItemBoolean.Destroy;
797 begin
798 inherited Destroy;
799 end;
800
801 procedure TPasJSONItemBoolean.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
802 begin
803 if not (assigned(aWith) and (aWith is TPasJSONItemBoolean)) then begin
804 raise EPasJSONMergeError.Create('Incompatible data type');
805 end;
806 fValue:=TPasJSONItemBoolean(aWith).Value;
807 end;
808
809 constructor TPasJSONItemNumber.Create(const AValue:TPasJSONDouble);
810 begin
811 inherited Create;
812 fValue:=AValue;
813 end;
814
815 destructor TPasJSONItemNumber.Destroy;
816 begin
817 inherited Destroy;
818 end;
819
820 procedure TPasJSONItemNumber.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
821 begin
822 if not (assigned(aWith) and (aWith is TPasJSONItemNumber)) then begin
823 raise EPasJSONMergeError.Create('Incompatible data type');
824 end;
825 fValue:=TPasJSONItemNumber(aWith).Value;
826 end;
827
828 constructor TPasJSONItemString.Create(const AValue:TPasJSONUTF8String);
829 begin
830 inherited Create;
831 fValue:=AValue;
832 end;
833
834 destructor TPasJSONItemString.Destroy;
835 begin
836 fValue:='';
837 inherited Destroy;
838 end;
839
840 procedure TPasJSONItemString.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
841 begin
842 if not (assigned(aWith) and (aWith is TPasJSONItemString)) then begin
843 raise EPasJSONMergeError.Create('Incompatible data type');
844 end;
845 fValue:=TPasJSONItemString(aWith).Value;
846 end;
847
848 constructor TPasJSONItemObjectProperty.Create;
849 begin
850 inherited Create;
851 fKey:='';
852 fValue:=nil;
853 end;
854
855 destructor TPasJSONItemObjectProperty.Destroy;
856 begin
857 fKey:='';
858 FreeAndNil(fValue);
859 inherited Destroy;
860 end;
861
862 constructor TPasJSONItemObject.TPasJSONItemObjectEnumerator.Create(const aOwner:TPasJSONItemObject);
863 begin
864 fOwner:=aOwner;
865 fIndex:=-1;
866 end;
867
868 function TPasJSONItemObject.TPasJSONItemObjectEnumerator.MoveNext:boolean;
869 begin
870 inc(fIndex);
871 result:=(fIndex>=0) and (fIndex<fOwner.fCount);
872 end;
873
874 function TPasJSONItemObject.TPasJSONItemObjectEnumerator.GetCurrent:TPasJSONItemObjectProperty;
875 begin
876 result:=fOwner.fProperties[fIndex];
877 end;
878
879 constructor TPasJSONItemObject.Create;
880 begin
881 inherited Create;
882 fProperties:=nil;
883 fCount:=0;
884 end;
885
886 destructor TPasJSONItemObject.Destroy;
887 var Index:TPasJSONInt32;
888 begin
889 for Index:=0 to fCount-1 do begin
890 FreeAndNil(fProperties[Index]);
891 end;
892 SetLength(fProperties,0);
893 inherited Destroy;
894 end;
895
896 function TPasJSONItemObject.GetKeyIndex(const aKey:TPasJSONUTF8String):TPasJSONInt32;
897 var Index:TPasJSONInt32;
898 begin
899 for Index:=0 to fCount-1 do begin
900 if fProperties[Index].Key=aKey then begin
901 result:=Index;
902 exit;
903 end;
904 end;
905 result:=-1;
906 end;
907
908 function TPasJSONItemObject.GetKey(const aIndex:TPasJSONSizeInt):TPasJSONUTF8String;
909 begin
910 if (aIndex>=0) and (aIndex<fCount) then begin
911 result:=fProperties[aIndex].Key;
912 end else begin
913 result:='';
914 end;
915 end;
916
917 procedure TPasJSONItemObject.SetKey(const aIndex:TPasJSONSizeInt;const aKey:TPasJSONUTF8String);
918 begin
919 if (aIndex>=0) and (aIndex<fCount) then begin
920 fProperties[aIndex].Key:=aKey;
921 end;
922 end;
923
924 function TPasJSONItemObject.GetValue(const aIndex:TPasJSONSizeInt):TPasJSONItem;
925 begin
926 if (aIndex>=0) and (aIndex<fCount) then begin
927 result:=fProperties[aIndex].Value;
928 end else begin
929 result:=nil;
930 end;
931 end;
932
933 procedure TPasJSONItemObject.SetValue(const aIndex:TPasJSONSizeInt;const aItem:TPasJSONItem);
934 begin
935 if (aIndex>=0) and (aIndex<fCount) then begin
936 fProperties[aIndex].Value:=aItem;
937 end;
938 end;
939
940 function TPasJSONItemObject.GetProperty(const aKey:TPasJSONUTF8String):TPasJSONItem;
941 begin
942 result:=GetValue(GetKeyIndex(aKey));
943 end;
944
945 procedure TPasJSONItemObject.SetProperty(const aKey:TPasJSONUTF8String;const aItem:TPasJSONItem);
946 begin
947 SetValue(GetKeyIndex(aKey),aItem);
948 end;
949
950 function TPasJSONItemObject.GetEnumerator:TPasJSONItemObject.TPasJSONItemObjectEnumerator;
951 begin
952 result:=TPasJSONItemObject.TPasJSONItemObjectEnumerator.Create(self);
953 end;
954
955 procedure TPasJSONItemObject.Clear;
956 var Index:TPasJSONInt32;
957 begin
958 for Index:=0 to fCount-1 do begin
959 FreeAndNil(fProperties[Index]);
960 end;
961 SetLength(fProperties,0);
962 fCount:=0;
963 end;
964
965 procedure TPasJSONItemObject.Add(const aKey:TPasJSONUTF8String;const aValue:TPasJSONItem);
966 var Index:TPasJSONSizeInt;
967 ObjectProperty:TPasJSONItemObjectProperty;
968 begin
969 Index:=fCount;
970 inc(fCount);
971 if fCount>=length(fProperties) then begin
972 SetLength(fProperties,fCount*2);
973 end;
974 ObjectProperty:=TPasJSONItemObjectProperty.Create;
975 fProperties[Index]:=ObjectProperty;
976 ObjectProperty.Key:=aKey;
977 ObjectProperty.Value:=aValue;
978 end;
979
980 procedure TPasJSONItemObject.Delete(const aIndex:TPasJSONSizeInt);
981 begin
982 if (aIndex>=0) and (aIndex<fCount) then begin
983 FreeAndNil(fProperties[aIndex]);
984 dec(fCount);
985 Move(fProperties[aIndex+1],fProperties[aIndex],fCount*SizeOf(TPasJSONItemObjectProperty));
986 end;
987 end;
988
989 procedure TPasJSONItemObject.Delete(const aKey:TPasJSONUTF8String);
990 begin
991 Delete(GetKeyIndex(aKey));
992 end;
993
994 procedure TPasJSONItemObject.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
995 var Index,KeyIndex:TPasJSONSizeint;
996 SrcProperty,OurProperty:TPasJSONItemObjectProperty;
997 NewItem:TPasJSONItem;
998 begin
999 if not (assigned(aWith) and (aWith is TPasJSONItemObject)) then begin
1000 raise EPasJSONMergeError.Create('Incompatible data type');
1001 end;
1002 for Index:=0 to TPasJSONItemObject(aWith).Count-1 do begin
1003 SrcProperty:=TPasJSONItemObject(aWith).fProperties[Index];
1004 if assigned(SrcProperty.Value) then begin
1005 KeyIndex:=GetKeyIndex(SrcProperty.Key);
1006 if KeyIndex>=0 then begin
1007 OurProperty:=fProperties[KeyIndex];
1008 if (TPasJSONMergeFlag.ForceObjectPropertyValueDestinationType in aFlags) and
1009 ((not assigned(OurProperty.Value)) or
1010 (assigned(OurProperty.Value) and
1011 (OurProperty.Value.ClassType<>SrcProperty.Value.ClassType))) then begin
1012 if assigned(OurProperty.Value) then begin
1013 OurProperty.Value.Free;
1014 end;
1015 OurProperty.Value:=TPasJSONItem(SrcProperty.Value.ClassType.Create);
1016 end;
1017 if assigned(OurProperty.Value) and (OurProperty.Value.ClassType=SrcProperty.Value.ClassType) then begin
1018 OurProperty.Value.Merge(SrcProperty.Value,aFlags);
1019 end;
1020 end else begin
1021 NewItem:=nil;
1022 try
1023 NewItem:=TPasJSONItem(SrcProperty.Value.ClassType.Create);
1024 NewItem.Merge(SrcProperty.Value,aFlags);
1025 Add(SrcProperty.Key,NewItem);
1026 except
1027 NewItem.Free;
1028 raise;
1029 end;
1030 end;
1031 end;
1032 end;
1033 end;
1034
1035 constructor TPasJSONItemArray.TPasJSONItemArrayEnumerator.Create(const aOwner:TPasJSONItemArray);
1036 begin
1037 fOwner:=aOwner;
1038 fIndex:=-1;
1039 end;
1040
1041 function TPasJSONItemArray.TPasJSONItemArrayEnumerator.MoveNext:boolean;
1042 begin
1043 inc(fIndex);
1044 result:=(fIndex>=0) and (fIndex<fOwner.fCount);
1045 end;
1046
1047 function TPasJSONItemArray.TPasJSONItemArrayEnumerator.GetCurrent:TPasJSONItem;
1048 begin
1049 result:=fOwner.fItems[fIndex];
1050 end;
1051
1052 constructor TPasJSONItemArray.Create;
1053 begin
1054 inherited Create;
1055 fItems:=nil;
1056 fCount:=0;
1057 end;
1058
1059 destructor TPasJSONItemArray.Destroy;
1060 var Index:TPasJSONInt32;
1061 begin
1062 for Index:=0 to fCount-1 do begin
1063 FreeAndNil(fItems[Index]);
1064 end;
1065 SetLength(fItems,0);
1066 inherited Destroy;
1067 end;
1068
1069 function TPasJSONItemArray.GetValue(const Index:TPasJSONInt32):TPasJSONItem;
1070 begin
1071 if (Index>=0) and (Index<fCount) then begin
1072 result:=fItems[Index];
1073 end else begin
1074 result:=nil;
1075 end;
1076 end;
1077
1078 procedure TPasJSONItemArray.SetValue(const Index:TPasJSONInt32;const Item:TPasJSONItem);
1079 begin
1080 if (Index>=0) and (Index<fCount) then begin
1081 fItems[Index]:=Item;
1082 end;
1083 end;
1084
1085 function TPasJSONItemArray.GetEnumerator:TPasJSONItemArray.TPasJSONItemArrayEnumerator;
1086 begin
1087 result:=TPasJSONItemArray.TPasJSONItemArrayEnumerator.Create(self);
1088 end;
1089
1090 procedure TPasJSONItemArray.Clear;
1091 var Index:TPasJSONInt32;
1092 begin
1093 for Index:=0 to fCount-1 do begin
1094 FreeAndNil(fItems[Index]);
1095 end;
1096 SetLength(fItems,0);
1097 fCount:=0;
1098 end;
1099
1100 procedure TPasJSONItemArray.Add(const aValue:TPasJSONItem);
1101 var Index:TPasJSONSizeInt;
1102 begin
1103 Index:=fCount;
1104 inc(fCount);
1105 if fCount>=length(fItems) then begin
1106 SetLength(fItems,fCount*2);
1107 end;
1108 fItems[Index]:=aValue;
1109 end;
1110
1111 procedure TPasJSONItemArray.Delete(const aIndex:TPasJSONSizeInt);
1112 begin
1113 if (aIndex>=0) and (aIndex<fCount) then begin
1114 FreeAndNil(fItems[aIndex]);
1115 dec(fCount);
1116 Move(fItems[aIndex+1],fItems[aIndex],fCount*SizeOf(TPasJSONItem));
1117 end;
1118 end;
1119
1120 procedure TPasJSONItemArray.Merge(const aWith:TPasJSONItem;const aFlags:TPasJSONMergeFlags=[]);
1121 var Index:TPasJSONSizeInt;
1122 Item,NewItem:TPasJSONItem;
1123 begin
1124 if not (assigned(aWith) and (aWith is TPasJSONItemArray)) then begin
1125 raise EPasJSONMergeError.Create('Incompatible data type');
1126 end;
1127 for Index:=0 to TPasJSONItemArray(aWith).Count-1 do begin
1128 Item:=TPasJSONItemArray(aWith).Items[Index];
1129 if assigned(Item) then begin
1130 NewItem:=TPasJSONItem(Item.ClassType.Create);
1131 Add(NewItem);
1132 NewItem.Merge(Item,aFlags);
1133 end;
1134 end;
1135 end;
1136
1137 const HexChars:array[boolean,0..15] of ansichar=(('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'),
1138 ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'));
1139
1140 class function TPasJSON.StringQuote(const aString:TPasJSONUTF8String):TPasJSONRawByteString;
1141 var i,l:TPasJSONInt32;
1142 c,t:TPasJSONUInt32;
1143 begin
1144 result:='"';
1145 i:=1;
1146 l:=length(aString);
1147 while i<=l do begin
1148 case aString[i] of
1149 '"','\':begin
1150 result:=result+'\'+AnsiChar(aString[i]);
1151 inc(i);
1152 end;
1153 #$08:begin
1154 result:=result+'\b';
1155 inc(i);
1156 end;
1157 #$09:begin
1158 result:=result+'\t';
1159 inc(i);
1160 end;
1161 #$0a:begin
1162 result:=result+'\n';
1163 inc(i);
1164 end;
1165 #$0b:begin
1166 result:=result+'\v';
1167 inc(i);
1168 end;
1169 #$0c:begin
1170 result:=result+'\f';
1171 inc(i);
1172 end;
1173 #$0d:begin
1174 result:=result+'\r';
1175 inc(i);
1176 end;
1177 #$00..#$07,#$0e..#$1f,#$7e..#$7f:begin
1178 c:=byte(AnsiChar(aString[i]));
1179 result:=result+'\u00'+HexChars[false,(c shr 4) and $f]+HexChars[false,c and $f];
1180 inc(i);
1181 end;
1182 #$80..#$ff:begin
1183 c:=GetNextUTF8Char(PAnsiChar(@aString[1]),l,i);
1184 case c of
1185 $0000..$d7ff,$f000..$fffc:begin
1186 result:=result+'\u'+HexChars[false,(c shr 12) and $f]+HexChars[false,(c shr 8) and $f]+HexChars[false,(c shr 4) and $f]+HexChars[false,c and $f];
1187 end;
1188 $100000..$10ffff:begin
1189 dec(c,$100000);
1190 t:=(c shr 10) or $d800;
1191 result:=result+'\u'+HexChars[false,(t shr 12) and $f]+HexChars[false,(t shr 8) and $f]+HexChars[false,(t shr 4) and $f]+HexChars[false,t and $f];
1192 t:=(c and $3ff) or $dc00;
1193 result:=result+'\u'+HexChars[false,(t shr 12) and $f]+HexChars[false,(t shr 8) and $f]+HexChars[false,(t shr 4) and $f]+HexChars[false,t and $f];
1194 end;
1195 else {-$d800..$dfff,$fffd..$ffff,$110000..$ffffffff:}begin
1196 result:=result+'\ufffd';
1197 end;
1198 end;
1199 end;
1200 else begin
1201 result:=result+AnsiChar(aString[i]);
1202 inc(i);
1203 end;
1204 end;
1205 end;
1206 result:=result+'"';
1207 end;
1208
1209 class function TPasJSON.Parse(const aSource:TPasJSONRawByteString;const aModeFlags:TPasJSONModeFlags=[TPasJSONModeFlag.Comments];const aEncoding:TPasJSONEncoding=TPasJSONEncoding.AutomaticDetection):TPasJSONItem;
1210 var Position:TPasJSONInt32;
1211 CurrentChar:TPasJSONUInt32;
1212 CharEOF:boolean;
1213 Encoding:TPasJSONEncoding;
1214 procedure NextChar;
1215 const UTF16Shifts:array[TPasJSONEncoding.UTF16LE..TPasJSONEncoding.UTF16BE,0..1] of TPasJSONInt32=((0,8),(8,0));
1216 var Temp:TPasJSONUInt32;
1217 begin
1218 if Position<=length(aSource) then begin
1219 case Encoding of
1220 TPasJSONEncoding.UTF8:begin
1221 CurrentChar:=GetNextUTF8Char(PAnsiChar(@aSource[1]),Length(aSource),Position);
1222 end;
1223 TPasJSONEncoding.UTF16LE,TPasJSONEncoding.UTF16BE:begin
1224 if (Position+1)<=length(aSource) then begin
1225 CurrentChar:=(TPasJSONUInt32(byte(AnsiChar(aSource[Position]))) shl UTF16Shifts[Encoding,0]) or (TPasJSONUInt32(byte(AnsiChar(aSource[Position+1]))) shl UTF16Shifts[Encoding,1]);
1226 inc(Position,2);
1227 if ((CurrentChar>=$d800) and (CurrentChar<=$dbff)) and ((Position+1)<=length(aSource)) then begin
1228 Temp:=(TPasJSONUInt32(byte(AnsiChar(aSource[Position]))) shl UTF16Shifts[Encoding,0]) or (TPasJSONUInt32(byte(AnsiChar(aSource[Position+1]))) shl UTF16Shifts[Encoding,1]);
1229 if (Temp>=$dc00) and (Temp<=$dfff) then begin
1230 CurrentChar:=(TPasJSONUInt32(TPasJSONUInt32(CurrentChar and $3ff) shl 10) or TPasJSONUInt32(Temp and $3ff))+$10000;
1231 inc(Position,2);
1232 end else begin
1233 CurrentChar:=$fffd;
1234 end;
1235 end else if not ((CurrentChar<=$d7ff) or (CurrentChar>=$e000)) then begin
1236 CurrentChar:=$fffd;
1237 end;
1238 end else begin
1239 inc(Position);
1240 CurrentChar:=0;
1241 CharEOF:=true;
1242 end;
1243 end;
1244 TPasJSONEncoding.UTF32LE:begin
1245 if (Position+3)<=length(aSource) then begin
1246 CurrentChar:=(TPasJSONUInt32(byte(AnsiChar(aSource[Position]))) shl 0) or
1247 (TPasJSONUInt32(byte(AnsiChar(aSource[Position+1]))) shl 8) or
1248 (TPasJSONUInt32(byte(AnsiChar(aSource[Position+2]))) shl 16) or
1249 (TPasJSONUInt32(byte(AnsiChar(aSource[Position+3]))) shl 24);
1250 inc(Position,4);
1251 end else begin
1252 inc(Position);
1253 CurrentChar:=0;
1254 CharEOF:=true;
1255 end;
1256 end;
1257 TPasJSONEncoding.UTF32BE:begin
1258 if (Position+3)<=length(aSource) then begin
1259 CurrentChar:=(TPasJSONUInt32(byte(AnsiChar(aSource[Position]))) shl 24) or
1260 (TPasJSONUInt32(byte(AnsiChar(aSource[Position+1]))) shl 16) or
1261 (TPasJSONUInt32(byte(AnsiChar(aSource[Position+2]))) shl 8) or
1262 (TPasJSONUInt32(byte(AnsiChar(aSource[Position+3]))) shl 0);
1263 inc(Position,4);
1264 end else begin
1265 inc(Position);
1266 CurrentChar:=0;
1267 CharEOF:=true;
1268 end;
1269 end;
1270 else begin
1271 CurrentChar:=byte(AnsiChar(aSource[Position]));
1272 inc(Position);
1273 end;
1274 end;
1275 end else begin
1276 CurrentChar:=0;
1277 CharEOF:=true;
1278 end;
1279 end;
1280 procedure JSONError;
1281 begin
1282 raise EPasJSONSyntaxError.Create('Parser error at byte position '+IntToStr(Position),Position);
1283 end;
1284 procedure SkipWhite;
1285 var LastChar:TPasJSONUInt32;
1286 begin
1287 while not CharEOF do begin
1288 case CurrentChar of
1289 $0009,$000a,$000d,$0020:begin
1290 NextChar;
1291 end;
1292 ord('/'):begin
1293 if TPasJSONModeFlag.Comments in aModeFlags then begin
1294 NextChar;
1295 case CurrentChar of
1296 ord('/'):begin
1297 NextChar;
1298 while not (CharEOF or ((CurrentChar=$000a) or (CurrentChar=$000d))) do begin
1299 NextChar;
1300 end;
1301 end;
1302 ord('*'):begin
1303 NextChar;
1304 LastChar:=0;
1305 while not (CharEOF or ((LastChar=ord('*')) and (CurrentChar=ord('/')))) do begin
1306 LastChar:=CurrentChar;
1307 NextChar;
1308 end;
1309 if CurrentChar=ord('/') then begin
1310 NextChar;
1311 end;
1312 end;
1313 else begin
1314 JSONError;
1315 end;
1316 end;
1317 end else begin
1318 JSONError;
1319 end;
1320 end;
1321 else begin
1322 break;
1323 end;
1324 end;
1325 end;
1326 end;
1327 function IsChar(c:TPasJSONUTF16Char):boolean;
1328 begin
1329 result:=(not CharEOF) and (CurrentChar=UInt16(c));
1330 end;
1331 procedure ExpectChar(c:TPasJSONUTF16Char);
1332 begin
1333 if IsChar(c) then begin
1334 NextChar;
1335 end else begin
1336 JSONError;
1337 end;
1338 end;
1339 function ParseValue(const ImplicitRootObject:boolean):TPasJSONItem;
1340 function ParseString:TPasJSONItem;
1341 var w:TPasJSONUTF16String; // <= because of easy correct handling of UTF16 surrogates (see ECMAScript and JSON specs)
1342 wl:TPasJSONInt32;
1343 wc:TPasJSONUInt32;
1344 procedure AddChar(c:TPasJSONUInt32);
1345 var cl:TPasJSONInt32;
1346 begin
1347 if (c>=$100000) and (c<=$10ffff) then begin
1348 cl:=2;
1349 end else begin
1350 cl:=1;
1351 end;
1352 if (wl+cl)>length(w) then begin
1353 SetLength(w,(wl+cl) shl 1);
1354 end;
1355 if c<=$d7ff then begin
1356 inc(wl);
1357 w[wl]:=TPasJSONUTF16Char(UInt16(c));
1358 end else if c<=$dfff then begin
1359 inc(wl);
1360 w[wl]:=TPasJSONUTF16Char(UInt16($fffd));
1361 end else if c<=$fffd then begin
1362 inc(wl);
1363 w[wl]:=TPasJSONUTF16Char(UInt16(c));
1364 end else if c<=$ffff then begin
1365 inc(wl);
1366 w[wl]:=TPasJSONUTF16Char(UInt16($fffd));
1367 end else if c<=$10ffff then begin
1368 dec(c,$10000);
1369 inc(wl);
1370 w[wl]:=TPasJSONUTF16Char(UInt16((c shr 10) or $d800));
1371 inc(wl);
1372 w[wl]:=TPasJSONUTF16Char(UInt16((c and $3ff) or $dc00));
1373 end else begin
1374 inc(wl);
1375 w[wl]:=TPasJSONUTF16Char(UInt16($fffd));
1376 end;
1377 end;
1378 begin
1379 result:=nil;
1380 w:='';
1381 try
1382 try
1383 SetLength(w,512);
1384 wl:=0;
1385 if IsChar('"') then begin
1386 NextChar;
1387 while not (CharEOF or IsChar('"')) do begin
1388 case CurrentChar of
1389 $0000..$001f:begin
1390 if TPasJSONModeFlag.MultiLineStrings in aModeFlags then begin
1391 AddChar(CurrentChar);
1392 NextChar;
1393 end else begin
1394 JSONError;
1395 end;
1396 end;
1397 ord('\'):begin
1398 NextChar;
1399 case CurrentChar of
1400 ord('"'),ord('\'),ord('/'):begin
1401 AddChar(CurrentChar);
1402 NextChar;
1403 end;
1404 ord('b'):begin
1405 AddChar($0008);
1406 NextChar;
1407 end;
1408 ord('f'):begin
1409 AddChar($000c);
1410 NextChar;
1411 end;
1412 ord('n'):begin
1413 AddChar($000a);
1414 NextChar;
1415 end;
1416 ord('r'):begin
1417 AddChar($000d);
1418 NextChar;
1419 end;
1420 ord('t'):begin
1421 AddChar($0009);
1422 NextChar;
1423 end;
1424 ord('u'):begin
1425 NextChar;
1426 if (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or ((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))) and not CharEOF then begin
1427 if (CurrentChar>=ord('0')) and (CurrentChar<=ord('9')) then begin
1428 wc:=UInt16(CurrentChar)-ord('0');
1429 end else if (CurrentChar>=ord('a')) and (CurrentChar<=ord('f')) then begin
1430 wc:=(UInt16(CurrentChar)-ord('a'))+$a;
1431 end else if (CurrentChar>=ord('A')) and (CurrentChar<=ord('F')) then begin
1432 wc:=(UInt16(CurrentChar)-ord('A'))+$a;
1433 end else begin
1434 wc:=0;
1435 end;
1436 wc:=wc shl 4;
1437 NextChar;
1438 if (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or ((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))) and not CharEOF then begin
1439 if (CurrentChar>=ord('0')) and (CurrentChar<=ord('9')) then begin
1440 wc:=wc or UInt16(UInt16(CurrentChar)-ord('0'));
1441 end else if (CurrentChar>=ord('a')) and (CurrentChar<=ord('f')) then begin
1442 wc:=wc or UInt16((UInt16(CurrentChar)-ord('a'))+$a);
1443 end else if (CurrentChar>=ord('A')) and (CurrentChar<=ord('F')) then begin
1444 wc:=wc or UInt16((UInt16(CurrentChar)-ord('A'))+$a);
1445 end;
1446 wc:=wc shl 4;
1447 NextChar;
1448 if (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or ((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))) and not CharEOF then begin
1449 if (CurrentChar>=ord('0')) and (CurrentChar<=ord('9')) then begin
1450 wc:=wc or UInt16(UInt16(CurrentChar)-ord('0'));
1451 end else if (CurrentChar>=ord('a')) and (CurrentChar<=ord('f')) then begin
1452 wc:=wc or UInt16((UInt16(CurrentChar)-ord('a'))+$a);
1453 end else if (CurrentChar>=ord('A')) and (CurrentChar<=ord('F')) then begin
1454 wc:=wc or UInt16((UInt16(CurrentChar)-ord('A'))+$a);
1455 end;
1456 wc:=wc shl 4;
1457 NextChar;
1458 if (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or ((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))) and not CharEOF then begin
1459 if (CurrentChar>=ord('0')) and (CurrentChar<=ord('9')) then begin
1460 wc:=wc or UInt16(UInt16(CurrentChar)-ord('0'));
1461 end else if (CurrentChar>=ord('a')) and (CurrentChar<=ord('f')) then begin
1462 wc:=wc or UInt16((UInt16(CurrentChar)-ord('a'))+$a);
1463 end else if (CurrentChar>=ord('A')) and (CurrentChar<=ord('F')) then begin
1464 wc:=wc or UInt16((UInt16(CurrentChar)-ord('A'))+$a);
1465 end;
1466 AddChar(wc);
1467 NextChar;
1468 end else begin
1469 JSONError;
1470 end;
1471 end else begin
1472 JSONError;
1473 end;
1474 end else begin
1475 JSONError;
1476 end;
1477 end else begin
1478 JSONError;
1479 end;
1480 end;
1481 else begin
1482 JSONError;
1483 end;
1484 end;
1485 end;
1486 else begin
1487 AddChar(CurrentChar);
1488 NextChar;
1489 end;
1490 end;
1491 end;
1492 ExpectChar('"');
1493 SetLength(w,wl);
1494 result:=TPasJSONItemString.Create(ConvertUTF16ToUTF8(w));
1495 end else begin
1496 JSONError;
1497 end;
1498 SkipWhite;
1499 except
1500 FreeAndNil(result);
1501 raise;
1502 end;
1503 finally
1504 w:='';
1505 end;
1506 end;
1507 function ParseNumber:TPasJSONItem;
1508 var s:TPasJSONRawByteString;
1509 OK:TPasDblStrUtilsBoolean;
1510 Value:TPasJSONDouble;
1511 IsHexadecimal:boolean;
1512 begin
1513 result:=nil;
1514 s:='';
1515 try
1516 try
1517 if CharEOF then begin
1518 JSONError;
1519 end;
1520 case CurrentChar of
1521 ord('-'),ord('0')..ord('9'):begin
1522 if IsChar('-') then begin
1523 s:=s+ansichar(byte(CurrentChar));
1524 NextChar;
1525 if CharEOF or not ((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) then begin
1526 JSONError;
1527 end;
1528 end;
1529 IsHexadecimal:=false;
1530 if (not CharEOF) and (CurrentChar=ord('0')) then begin
1531 s:=s+ansichar(byte(CurrentChar));
1532 NextChar;
1533 if (TPasJSONModeFlag.HexadecimalNumbers in aModeFlags) and
1534 ((not CharEOF) and (CurrentChar in [ord('x'),ord('X')])) then begin
1535 s:=s+ansichar(byte(CurrentChar));
1536 NextChar;
1537 while (not CharEOF) and
1538 (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or
1539 ((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or
1540 ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))) do begin
1541 s:=s+ansichar(byte(CurrentChar));
1542 NextChar;
1543 end;
1544 IsHexadecimal:=true;
1545 end else begin
1546 if (not CharEOF) and ((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) then begin
1547 JSONError;
1548 end;
1549 end;
1550 end else begin
1551 while (not CharEOF) and ((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) do begin
1552 s:=s+ansichar(byte(CurrentChar));
1553 NextChar;
1554 end;
1555 end;
1556 if IsChar('.') then begin
1557 s:=s+ansichar(byte(CurrentChar));
1558 NextChar;
1559 if CharEOF or not (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or
1560 (IsHexadecimal and
1561 (((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or
1562 ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))))) then begin
1563 JSONError;
1564 end;
1565 while (not CharEOF) and (((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) or
1566 (IsHexadecimal and
1567 (((CurrentChar>=ord('a')) and (CurrentChar<=ord('f'))) or
1568 ((CurrentChar>=ord('A')) and (CurrentChar<=ord('F')))))) do begin
1569 s:=s+ansichar(byte(CurrentChar));
1570 NextChar;
1571 end;
1572 end;
1573 if (not CharEOF) and ((CurrentChar=ord('e')) or (CurrentChar=ord('E'))) then begin
1574 s:=s+ansichar(byte(CurrentChar));
1575 NextChar;
1576 if (not CharEOF) and ((CurrentChar=ord('-')) or (CurrentChar=ord('+'))) then begin
1577 s:=s+ansichar(byte(CurrentChar));
1578 NextChar;
1579 end;
1580 if CharEOF or not ((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) then begin
1581 JSONError;
1582 end;
1583 while (not CharEOF) and ((CurrentChar>=ord('0')) and (CurrentChar<=ord('9'))) do begin
1584 s:=s+ansichar(byte(CurrentChar));
1585 NextChar;
1586 end;
1587 end;
1588 end else begin
1589 JSONError;
1590 end;
1591 end;
1592 if length(s)>0 then begin
1593 OK:=false;
1594 Value:=ConvertStringToDouble(s,rmNearest,@OK);
1595 if not OK then begin
1596 JSONError;
1597 end;
1598 result:=TPasJSONItemNumber.Create(Value);
1599 end;
1600 except
1601 FreeAndNil(result);
1602 raise;
1603 end;
1604 finally
1605 s:='';
1606 end;
1607 end;
1608 procedure ParseObjectProperty(DestinationObject:TPasJSONItemObject);
1609 var Key:TPasJSONUTF8String;
1610 Value:TPasJSONItem;
1611 begin
1612 result:=nil;
1613 try
1614 if (TPasJSONModeFlag.UnquotedKeys in aModeFlags) and
1615 (not CharEOF) and
1616 ((CurrentChar=UInt16(TPasJSONUTF16Char('_'))) or
1617 ((CurrentChar>=UInt16(TPasJSONUTF16Char('a'))) and (CurrentChar<=UInt16(TPasJSONUTF16Char('z')))) or
1618 ((CurrentChar>=UInt16(TPasJSONUTF16Char('A'))) and (CurrentChar<=UInt16(TPasJSONUTF16Char('Z')))) or
1619 ((CurrentChar>=UInt16(TPasJSONUTF16Char('0'))) and (CurrentChar<=UInt16(TPasJSONUTF16Char('9'))))) then begin
1620 Key:=TPasJSONUTF8String(AnsiChar(byte(CurrentChar)));
1621 NextChar;
1622 while ((CurrentChar=UInt16(TPasJSONUTF16Char('_'))) or
1623 ((CurrentChar>=UInt16(TPasJSONUTF16Char('a'))) and (CurrentChar<=UInt16(TPasJSONUTF16Char('z')))) or
1624 ((CurrentChar>=UInt16(TPasJSONUTF16Char('A'))) and (CurrentChar<=UInt16(TPasJSONUTF16Char('Z')))) or
1625 ((CurrentChar>=UInt16(TPasJSONUTF16Char('0'))) and (CurrentChar<=UInt16(TPasJSONUTF16Char('9'))))) do begin
1626 Key:=Key+TPasJSONUTF8String(AnsiChar(byte(CurrentChar)));
1627 NextChar;
1628 end;
1629 SkipWhite;
1630 end else begin
1631 Value:=ParseString;
1632 if assigned(Value) and (Value is TPasJSONItemString) then begin
1633 Key:=TPasJSONItemString(Value).Value;
1634 FreeAndNil(Value);
1635 end else begin
1636 FreeAndNil(Value);
1637 JSONError;
1638 Key:='';
1639 end;
1640 end;
1641 SkipWhite;
1642 if TPasJSONModeFlag.EqualsForColon in aModeFlags then begin
1643 ExpectChar('=');
1644 end else begin
1645 ExpectChar(':');
1646 end;
1647 SkipWhite;
1648 Value:=ParseValue(false);
1649 DestinationObject.Add(Key,Value);
1650 except
1651 FreeAndNil(result);
1652 raise;
1653 end;
1654 end;
1655 function ParseObject(const ImplicitRootObject:boolean):TPasJSONItem;
1656 begin
1657 result:=TPasJSONItemObject.Create;
1658 try
1659 if not ImplicitRootObject then begin
1660 ExpectChar('{');
1661 end;
1662 SkipWhite;
1663 while not (CharEOF or ((not ImplicitRootObject) and IsChar('}'))) do begin
1664 ParseObjectProperty(TPasJSONItemObject(result));
1665 SkipWhite;
1666 if IsChar(',') then begin
1667 NextChar;
1668 SkipWhite;
1669 if (not (CharEOF or ImplicitRootObject)) and IsChar('}') then begin
1670 JSONError;
1671 end;
1672 end else if not (TPasJSONModeFlag.OptionalCommas in aModeFlags) then begin
1673 break;
1674 end;
1675 end;
1676 if not ImplicitRootObject then begin
1677 ExpectChar('}');
1678 end;
1679 except
1680 FreeAndNil(result);
1681 raise;
1682 end;
1683 end;
1684 function ParseArray:TPasJSONItem;
1685 begin
1686 result:=TPasJSONItemArray.Create;
1687 try
1688 ExpectChar('[');
1689 SkipWhite;
1690 while not (CharEOF or IsChar(']')) do begin
1691 TPasJSONItemArray(result).Add(ParseValue(false));
1692 SkipWhite;
1693 if IsChar(',') then begin
1694 NextChar;
1695 SkipWhite;
1696 if (not CharEOF) and IsChar(']') then begin
1697 JSONError;
1698 end;
1699 end else if not (TPasJSONModeFlag.OptionalCommas in aModeFlags) then begin
1700 break;
1701 end;
1702 end;
1703 ExpectChar(']');
1704 except
1705 FreeAndNil(result);
1706 raise;
1707 end;
1708 end;
1709 procedure ExpectKeyword(const Keyword:TPasJSONUTF8String);
1710 var i:TPasJSONInt32;
1711 begin
1712 for i:=1 to length(Keyword) do begin
1713 ExpectChar(TPasJSONUTF16Char(Keyword[i]));
1714 end;
1715 end;
1716 begin
1717 result:=nil;
1718 try
1719 SkipWhite;
1720 if CharEOF then begin
1721 JSONError;
1722 end;
1723 if ImplicitRootObject then begin
1724 result:=ParseObject(true);
1725 end else begin
1726 case CurrentChar of
1727 ord('{'):begin
1728 result:=ParseObject(false);
1729 end;
1730 ord('['):begin
1731 result:=ParseArray;
1732 end;
1733 ord('"'):begin
1734 result:=ParseString;
1735 end;
1736 ord('-'),ord('0')..ord('9'):begin
1737 result:=ParseNumber;
1738 end;
1739 ord('t'):begin
1740 ExpectKeyword('true');
1741 result:=TPasJSONItemBoolean.Create(true);
1742 end;
1743 ord('f'):begin
1744 ExpectKeyword('false');
1745 result:=TPasJSONItemBoolean.Create(false);
1746 end;
1747 ord('n'):begin
1748 ExpectKeyword('null');
1749 result:=TPasJSONItemNull.Create;
1750 end;
1751 else begin
1752 JSONError;
1753 end;
1754 end;
1755 end;
1756 except
1757 FreeAndNil(result);
1758 raise;
1759 end;
1760 end;
1761 begin
1762 result:=nil;
1763 try
1764 CharEOF:=false;
1765 if aEncoding=TPasJSONEncoding.AutomaticDetection then begin
1766 if (length(aSource)>=3) and ((byte(ansichar(aSource[1]))=$ef) and (byte(ansichar(aSource[2]))=$bb) and (byte(ansichar(aSource[3]))=$bf)) then begin
1767 Position:=4;
1768 Encoding:=TPasJSONEncoding.UTF8;
1769 end else if (length(aSource)>=4) and ((byte(ansichar(aSource[1]))=$ff) and (byte(ansichar(aSource[2]))=$fe) and (byte(ansichar(aSource[3]))=$00) and (byte(ansichar(aSource[4]))=$00)) then begin
1770 Position:=5;
1771 Encoding:=TPasJSONEncoding.UTF32LE;
1772 end else if (length(aSource)>=4) and ((byte(ansichar(aSource[1]))=$00) and (byte(ansichar(aSource[2]))=$00) and (byte(ansichar(aSource[3]))=$fe) and (byte(ansichar(aSource[4]))=$ff)) then begin
1773 Position:=5;
1774 Encoding:=TPasJSONEncoding.UTF32BE;
1775 end else if (length(aSource)>=2) and ((byte(ansichar(aSource[1]))=$ff) and (byte(ansichar(aSource[2]))=$fe)) then begin
1776 Position:=3;
1777 Encoding:=TPasJSONEncoding.UTF16LE;
1778 end else if (length(aSource)>=2) and ((byte(ansichar(aSource[1]))=$fe) and (byte(ansichar(aSource[2]))=$ff)) then begin
1779 Position:=3;
1780 Encoding:=TPasJSONEncoding.UTF16BE;
1781 end else begin
1782 Position:=1;
1783 Encoding:=TPasJSONEncoding.Latin1;
1784 end;
1785 end else begin
1786 Position:=1;
1787 Encoding:=aEncoding;
1788 end;
1789 NextChar;
1790 result:=ParseValue(TPasJSONModeFlag.ImplicitRootObject in aModeFlags);
1791 SkipWhite;
1792 if not CharEOF then begin
1793 JSONError;
1794 end;
1795 except
1796 FreeAndNil(result);
1797 raise;
1798 end;
1799 end;
1800
1801 class function TPasJSON.Parse(const aStream:TStream;const aModeFlags:TPasJSONModeFlags=[TPasJSONModeFlag.Comments];const aEncoding:TPasJSONEncoding=TPasJSONEncoding.AutomaticDetection):TPasJSONItem;
1802 var StringValue:TPasJSONRawByteString;
1803 begin
1804 StringValue:='';
1805 try
1806 SetLength(StringValue,aStream.Size);
1807 if length(StringValue)>0 then begin
1808 if aStream.Seek(0,soBeginning)<>0 then begin
1809 raise EInOutError.Create('Stream seek error');
1810 end;
1811 aStream.ReadBuffer(StringValue[1],aStream.Size);
1812 end;
1813 result:=TPasJSON.Parse(StringValue,aModeFlags,aEncoding);
1814 finally
1815 StringValue:='';
1816 end;
1817 end;
1818
1819 class function TPasJSON.Stringify(const aJSONItem:TPasJSONItem;const aFormatting:boolean=false;const aModeFlags:TPasJSONModeFlags=[];const aLevel:TPasJSONInt32=0):TPasJSONRawByteString;
1820 function IsIdentifier(const pKey:TPasJSONUTF8String):boolean;
1821 var Index:TPasJSONInt32;
1822 begin
1823 result:=length(pKey)>0;
1824 for Index:=1 to length(pKey) do begin
1825 case UInt16(TPasJSONUTF16Char(pKey[Index])) of
1826 UInt16(TPasJSONUTF16Char('_')),
1827 UInt16(TPasJSONUTF16Char('a'))..UInt16(TPasJSONUTF16Char('z')),
1828 UInt16(TPasJSONUTF16Char('A'))..UInt16(TPasJSONUTF16Char('Z')),
1829 UInt16(TPasJSONUTF16Char('0'))..UInt16(TPasJSONUTF16Char('9')):begin
1830 end;
1831 else begin
1832 result:=false;
1833 break;
1834 end;
1835 end;
1836 end;
1837 end;
1838 var Index,Count,Ident,LevelOffset:TPasJSONInt32;
1839 IntegerValue:Int64;
1840 Key:TPasJSONUTF8String;
1841 begin
1842 if assigned(aJSONItem) then begin
1843 if aJSONItem is TPasJSONItemNull then begin
1844 result:='null';
1845 end else if aJSONItem is TPasJSONItemBoolean then begin
1846 if TPasJSONItemBoolean(aJSONItem).Value then begin
1847 result:='true';
1848 end else begin
1849 result:='false';
1850 end;
1851 end else if aJSONItem is TPasJSONItemNumber then begin
1852 if IsInfinite(TPasJSONItemNumber(aJSONItem).Value) then begin
1853 if (TPasJSONUInt64(Pointer(@TPasJSONItemNumber(aJSONItem).Value)^) shr 63)<>0 then begin
1854 result:=TPasJSON.StringQuote('-Infinity');
1855 end else begin
1856 result:=TPasJSON.StringQuote('Infinity');
1857 end;
1858 end else if IsNaN(TPasJSONItemNumber(aJSONItem).Value) then begin
1859 if (TPasJSONUInt64(Pointer(@TPasJSONItemNumber(aJSONItem).Value)^) shr 63)<>0 then begin
1860 result:=TPasJSON.StringQuote('-NaN');
1861 end else begin
1862 result:=TPasJSON.StringQuote('NaN');
1863 end;
1864 end else begin
1865 IntegerValue:=trunc(TPasJSONItemNumber(aJSONItem).Value);
1866 if TPasJSONItemNumber(aJSONItem).Value=IntegerValue then begin
1867 Str(IntegerValue,result);
1868 end else begin
1869 result:=ConvertDoubleToString(TPasJSONItemNumber(aJSONItem).Value,omStandard,0);
1870 end;
1871 end;
1872 end else if aJSONItem is TPasJSONItemString then begin
1873 result:=TPasJSON.StringQuote(TPasJSONItemString(aJSONItem).Value);
1874 end else if aJSONItem is TPasJSONItemArray then begin
1875 result:='[';
1876 if aFormatting then begin
1877 result:=result+#13#10;
1878 end;
1879 Count:=TPasJSONItemArray(aJSONItem).Count;
1880 if TPasJSONModeFlag.ImplicitRootObject in aModeFlags then begin
1881 LevelOffset:=-1;
1882 end else begin
1883 LevelOffset:=0;
1884 end;
1885 for Index:=0 to Count-1 do begin
1886 if aFormatting then begin
1887 for Ident:=0 to aLevel+LevelOffset do begin
1888 result:=result+' ';
1889 end;
1890 end;
1891 result:=result+TPasJSON.Stringify(TPasJSONItemArray(aJSONItem).Items[Index],aFormatting,aModeFlags,aLevel+1);
1892 if ((Index+1)<Count) and not (TPasJSONModeFlag.OptionalCommas in aModeFlags) then begin
1893 result:=result+',';
1894 end;
1895 if aFormatting then begin
1896 result:=result+#13#10;
1897 end;
1898 end;
1899 if aFormatting then begin
1900 for Ident:=1 to aLevel+LevelOffset do begin
1901 result:=result+' ';
1902 end;
1903 end;
1904 result:=result+']';
1905 end else if aJSONItem is TPasJSONItemObject then begin
1906 if (not (TPasJSONModeFlag.ImplicitRootObject in aModeFlags)) or (aLevel<>0) then begin
1907 result:='{';
1908 if aFormatting then begin
1909 result:=result+#13#10;
1910 end;
1911 end else begin
1912 result:='';
1913 end;
1914 if TPasJSONModeFlag.ImplicitRootObject in aModeFlags then begin
1915 LevelOffset:=-1;
1916 end else begin
1917 LevelOffset:=0;
1918 end;
1919 Count:=TPasJSONItemArray(aJSONItem).Count;
1920 for Index:=0 to Count-1 do begin
1921 if aFormatting then begin
1922 for Ident:=0 to aLevel+LevelOffset do begin
1923 result:=result+' ';
1924 end;
1925 end;
1926 Key:=TPasJSONItemObject(aJSONItem).Keys[Index];
1927 if (TPasJSONModeFlag.UnquotedKeys in aModeFlags) and IsIdentifier(Key) then begin
1928 result:=result+TPasJSONRawByteString(Key);
1929 end else begin
1930 result:=result+TPasJSON.StringQuote(Key);
1931 end;
1932 if TPasJSONModeFlag.EqualsForColon in aModeFlags then begin
1933 if aFormatting then begin
1934 result:=result+' ';
1935 end;
1936 result:=result+'=';
1937 end else begin
1938 result:=result+':';
1939 end;
1940 if aFormatting then begin
1941 result:=result+' ';
1942 end;
1943 result:=result+TPasJSON.Stringify(TPasJSONItemObject(aJSONItem).Values[Index],aFormatting,aModeFlags,aLevel+1);
1944 if ((Index+1)<Count) and not (TPasJSONModeFlag.OptionalCommas in aModeFlags) then begin
1945 result:=result+',';
1946 end;
1947 if aFormatting then begin
1948 result:=result+#13#10;
1949 end;
1950 end;
1951 if aFormatting then begin
1952 for Ident:=1 to aLevel+LevelOffset do begin
1953 result:=result+' ';
1954 end;
1955 end;
1956 if (not (TPasJSONModeFlag.ImplicitRootObject in aModeFlags)) or (aLevel<>0) then begin
1957 result:=result+'}';
1958 end;
1959 end else begin
1960 result:='null';
1961 end;
1962 end else begin
1963 result:='null';
1964 end;
1965 end;
1966
1967 class procedure TPasJSON.StringifyToStream(const aStream:TStream;const aJSONItem:TPasJSONItem;const aFormatting:boolean=false;const aModeFlags:TPasJSONModeFlags=[];const aLevel:TPasJSONInt32=0);
1968 var StringValue:TPasJSONRawByteString;
1969 begin
1970 StringValue:=Stringify(aJSONItem,aFormatting,aModeFlags,aLevel);
1971 try
1972 if length(StringValue)>0 then begin
1973 aStream.WriteBuffer(StringValue[1],length(StringValue));
1974 end;
1975 finally
1976 StringValue:='';
1977 end;
1978 end;
1979
1980 class function TPasJSON.GetNumber(const aItem:TPasJSONItem;const aDefault:TPasJSONDouble=0.0):TPasJSONDouble;
1981 var OK:TPasDblStrUtilsBoolean;
1982 begin
1983 if assigned(aItem) and (aItem is TPasJSONItemNumber) then begin
1984 result:=TPasJSONItemNumber(aItem).Value;
1985 end else if assigned(aItem) and (aItem is TPasJSONItemString) then begin
1986 OK:=false;
1987 result:=ConvertStringToDouble(TPasJSONItemString(aItem).Value,rmNearest,@OK,-1);
1988 if not OK then begin
1989 result:=aDefault;
1990 end;
1991 end else if assigned(aItem) and (aItem is TPasJSONItemBoolean) then begin
1992 result:=ord(TPasJSONItemBoolean(aItem).Value) and 1;
1993 end else begin
1994 result:=aDefault;
1995 end;
1996 end;
1997
1998 class function TPasJSON.GetInt64(const aItem:TPasJSONItem;const aDefault:TPasJSONInt64=0):TPasJSONInt64;
1999 begin
2000 if assigned(aItem) and (aItem is TPasJSONItemNumber) then begin
2001 result:=Trunc(TPasJSONItemNumber(aItem).Value);
2002 end else if assigned(aItem) and (aItem is TPasJSONItemString) then begin
2003 result:=StrToInt64Def(TPasJSONItemString(aItem).Value,aDefault);
2004 end else if assigned(aItem) and (aItem is TPasJSONItemBoolean) then begin
2005 result:=ord(TPasJSONItemBoolean(aItem).Value) and 1;
2006 end else begin
2007 result:=aDefault;
2008 end;
2009 end;
2010
2011 class function TPasJSON.GetString(const aItem:TPasJSONItem;const aDefault:TPasJSONUTF8String=''):TPasJSONUTF8String;
2012 begin
2013 if assigned(aItem) and (aItem is TPasJSONItemString) then begin
2014 result:=TPasJSONItemString(aItem).Value;
2015 end else if assigned(aItem) and (aItem is TPasJSONItemNumber) then begin
2016 result:=ConvertDoubleToString(TPasJSONItemNumber(aItem).Value,omStandard);
2017 end else if assigned(aItem) and (aItem is TPasJSONItemBoolean) then begin
2018 if TPasJSONItemBoolean(aItem).Value then begin
2019 result:='true';
2020 end else begin
2021 result:='false';
2022 end;
2023 end else begin
2024 result:=aDefault;
2025 end;
2026 end;
2027
2028 class function TPasJSON.GetBoolean(const aItem:TPasJSONItem;const aDefault:boolean=false):boolean;
2029 begin
2030 if assigned(aItem) and (aItem is TPasJSONItemBoolean) then begin
2031 result:=TPasJSONItemBoolean(aItem).Value;
2032 end else if assigned(aItem) and (aItem is TPasJSONItemNumber) then begin
2033 result:=TPasJSONItemNumber(aItem).Value<>0.0;
2034 end else if assigned(aItem) and (aItem is TPasJSONItemString) then begin
2035 result:=(LowerCase(TPasJSONItemString(aItem).Value)<>'false') and
2036 (TPasJSONItemString(aItem).Value<>'0');
2037 end else begin
2038 result:=aDefault;
2039 end;
2040 end;
2041
2042 class function TPasJSON.LoadBinaryFromStream(const aStream:TStream):TPasJSONItem;
2043 function LoadJSONItem:TPasJSONItem;
2044 var ItemType,BooleanValue:TPasJSONUInt8;
2045 Count,Counter,Len:TPasJSONInt32;
2046 TempString:TPasJSONUTF8String;
2047 DoubleValue:TPasJSONDouble;
2048 begin
2049 result:=nil;
2050 if aStream.Read(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2051 raise EInOutError.Create('Stream read error');
2052 end;
2053 case ItemType of
2054 0:begin
2055 result:=TPasJSONItemNull.Create;
2056 end;
2057 1:begin
2058 result:=TPasJSONItemArray.Create;
2059 if aStream.Read(Count,SizeOf(TPasJSONUInt32))<>SizeOf(TPasJSONInt32) then begin
2060 raise EInOutError.Create('Stream read error');
2061 end;
2062 for Counter:=0 to Count-1 do begin
2063 TPasJSONItemArray(result).Add(LoadJSONItem);
2064 end;
2065 end;
2066 2:begin
2067 TempString:='';
2068 try
2069 result:=TPasJSONItemObject.Create;
2070 if aStream.Read(Count,SizeOf(TPasJSONUInt32))<>SizeOf(TPasJSONInt32) then begin
2071 raise EInOutError.Create('Stream read error');
2072 end;
2073 for Counter:=0 to Count-1 do begin
2074 if aStream.Read(Len,SizeOf(TPasJSONUInt32))<>SizeOf(TPasJSONInt32) then begin
2075 raise EInOutError.Create('Stream read error');
2076 end;
2077 SetLength(TempString,Len);
2078 if Len>0 then begin
2079 if TPasJSONInt64(aStream.Read(TempString[1],Len*SizeOf(AnsiChar)))<>TPasJSONInt64(Len*SizeOf(AnsiChar)) then begin
2080 raise EInOutError.Create('Stream read error');
2081 end;
2082 end;
2083 TPasJSONItemObject(result).Add(TempString,LoadJSONItem);
2084 end;
2085 finally
2086 TempString:='';
2087 end;
2088 end;
2089 3:begin
2090 if aStream.Read(BooleanValue,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2091 raise EInOutError.Create('Stream read error');
2092 end;
2093 result:=TPasJSONItemBoolean.Create(BooleanValue<>0);
2094 end;
2095 4:begin
2096 if aStream.Read(DoubleValue,SizeOf(TPasJSONDouble))<>SizeOf(TPasJSONDouble) then begin
2097 raise EInOutError.Create('Stream read error');
2098 end;
2099 result:=TPasJSONItemNumber.Create(DoubleValue);
2100 end;
2101 5:begin
2102 TempString:='';
2103 try
2104 if aStream.Read(Len,SizeOf(TPasJSONInt32))<>SizeOf(TPasJSONInt32) then begin
2105 raise EInOutError.Create('Stream read error');
2106 end;
2107 SetLength(TempString,Len);
2108 if Len>0 then begin
2109 if TPasJSONInt64(aStream.Read(TempString[1],Len*SizeOf(AnsiChar)))<>TPasJSONInt64(Len*SizeOf(AnsiChar)) then begin
2110 raise EInOutError.Create('Stream read error');
2111 end;
2112 end;
2113 result:=TPasJSONItemString.Create(TempString);
2114 finally
2115 TempString:='';
2116 end;
2117 end;
2118 else begin
2119 raise EInOutError.Create('Stream read error');
2120 end;
2121 end;
2122 end;
2123 begin
2124 if assigned(aStream) and (aStream.Position<aStream.Size) then begin
2125 result:=LoadJSONItem;
2126 end else begin
2127 result:=nil;
2128 end;
2129 end;
2130
2131 class procedure TPasJSON.SaveBinaryToStream(const aStream:TStream;const aJSONItem:TPasJSONItem);
2132 procedure SaveJSONItem(const pCurrentJSONItem:TPasJSONItem);
2133 var ItemType,BooleanValue:TPasJSONUInt8;
2134 Count,Counter,Len:TPasJSONInt32;
2135 TempString:TPasJSONUTF8String;
2136 DoubleValue:TPasJSONDouble;
2137 begin
2138 if assigned(pCurrentJSONItem) then begin
2139 if pCurrentJSONItem is TPasJSONItemNull then begin
2140 ItemType:=0;
2141 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2142 raise EInOutError.Create('Stream write error');
2143 end;
2144 end else if pCurrentJSONItem is TPasJSONItemArray then begin
2145 ItemType:=1;
2146 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2147 raise EInOutError.Create('Stream write error');
2148 end;
2149 Count:=TPasJSONItemArray(pCurrentJSONItem).Count;
2150 if aStream.Write(Count,SizeOf(TPasJSONInt32))<>SizeOf(TPasJSONInt32) then begin
2151 raise EInOutError.Create('Stream write error');
2152 end;
2153 for Counter:=0 to Count-1 do begin
2154 SaveJSONItem(TPasJSONItemArray(pCurrentJSONItem).Items[Counter]);
2155 end;
2156 end else if pCurrentJSONItem is TPasJSONItemObject then begin
2157 ItemType:=2;
2158 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2159 raise EInOutError.Create('Stream write error');
2160 end;
2161 Count:=TPasJSONItemObject(pCurrentJSONItem).Count;
2162 if aStream.Write(Count,SizeOf(TPasJSONInt32))<>SizeOf(TPasJSONInt32) then begin
2163 raise EInOutError.Create('Stream write error');
2164 end;
2165 try
2166 for Counter:=0 to Count-1 do begin
2167 TempString:=TPasJSONItemObject(pCurrentJSONItem).Keys[Counter];
2168 Len:=length(TempString);
2169 if aStream.Write(Len,SizeOf(TPasJSONInt32))<>SizeOf(TPasJSONInt32) then begin
2170 raise EInOutError.Create('Stream write error');
2171 end;
2172 if Len>0 then begin
2173 if TPasJSONInt64(aStream.Write(TempString[1],Len*SizeOf(AnsiChar)))<>TPasJSONInt64(Len*SizeOf(AnsiChar)) then begin
2174 raise EInOutError.Create('Stream write error');
2175 end;
2176 end;
2177 SaveJSONItem(TPasJSONItemObject(pCurrentJSONItem).Values[Counter]);
2178 end;
2179 finally
2180 TempString:='';
2181 end;
2182 end else if pCurrentJSONItem is TPasJSONItemBoolean then begin
2183 ItemType:=3;
2184 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2185 raise EInOutError.Create('Stream write error');
2186 end;
2187 if TPasJSONItemBoolean(pCurrentJSONItem).fValue then begin
2188 BooleanValue:=$ff;
2189 end else begin
2190 BooleanValue:=$00;
2191 end;
2192 if aStream.Write(BooleanValue,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2193 raise EInOutError.Create('Stream write error');
2194 end;
2195 end else if pCurrentJSONItem is TPasJSONItemNumber then begin
2196 ItemType:=4;
2197 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2198 raise EInOutError.Create('Stream write error');
2199 end;
2200 DoubleValue:=TPasJSONItemNumber(pCurrentJSONItem).fValue;
2201 if aStream.Write(DoubleValue,SizeOf(TPasJSONDouble))<>SizeOf(TPasJSONDouble) then begin
2202 raise EInOutError.Create('Stream write error');
2203 end;
2204 end else if pCurrentJSONItem is TPasJSONItemString then begin
2205 ItemType:=5;
2206 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2207 raise EInOutError.Create('Stream write error');
2208 end;
2209 TempString:=TPasJSONItemString(pCurrentJSONItem).fValue;
2210 Len:=length(TempString);
2211 if aStream.Write(Len,SizeOf(TPasJSONInt32))<>SizeOf(TPasJSONInt32) then begin
2212 raise EInOutError.Create('Stream write error');
2213 end;
2214 if Len>0 then begin
2215 if TPasJSONInt64(aStream.Write(TempString[1],Len*SizeOf(AnsiChar)))<>TPasJSONInt64(Len*SizeOf(AnsiChar)) then begin
2216 raise EInOutError.Create('Stream write error');
2217 end;
2218 end;
2219 end else begin
2220 ItemType:=0;
2221 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2222 raise EInOutError.Create('Stream write error');
2223 end;
2224 end;
2225 end else begin
2226 ItemType:=0;
2227 if aStream.Write(ItemType,SizeOf(TPasJSONUInt8))<>SizeOf(TPasJSONUInt8) then begin
2228 raise EInOutError.Create('Stream write error');
2229 end;
2230 end;
2231 end;
2232 begin
2233 if assigned(aJSONItem) and assigned(aStream) then begin
2234 SaveJSONItem(aJSONItem);
2235 end;
2236 end;
2237
2238 initialization
2239 end.
2240