aboutsummaryrefslogtreecommitdiffstats
path: root/src/shared/json/json.cpp
blob: 321004dc62ef7683ced5f70b6aaf61be0c95ece0 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <algorithm>
#include <atomic>
#include <cmath>
#include <iostream>
#include <limits>
#include <string>
#include <utility>
#include <vector>

#include <limits.h>
#include <string.h>

#include "json.h"


//#define PARSER_DEBUG
#ifdef PARSER_DEBUG
static int indent = 0;
#define BEGIN std::cerr << std::string(4*indent++, ' ').data() << " pos=" << current
#define END --indent
#define DEBUG std::cerr << std::string(4*indent, ' ').data()
#else
#define BEGIN if (1) ; else std::cerr
#define END do {} while (0)
#define DEBUG if (1) ; else std::cerr
#endif

static const int nestingLimit = 1024;


namespace Json {
namespace Internal {

/*
  This defines a binary data structure for Json data. The data structure is optimised for fast reading
  and minimum allocations. The whole data structure can be mmap'ed and used directly.

  In most cases the binary structure is not as space efficient as a utf8 encoded text representation, but
  much faster to access.

  The size requirements are:

  String: 4 bytes header + 2*(string.length())

  Values: 4 bytes + size of data (size can be 0 for some data)
    bool: 0 bytes
    double: 8 bytes (0 if integer with less than 27bits)
    string: see above
    array: size of array
    object: size of object
  Array: 12 bytes + 4*length + size of Value data
  Object: 12 bytes + 8*length + size of Key Strings + size of Value data

  For an example such as

    {                                           // object: 12 + 5*8                   = 52
         "firstName": "John",                   // key 12, value 8                    = 20
         "lastName" : "Smith",                  // key 12, value 8                    = 20
         "age"      : 25,                       // key 8, value 0                     = 8
         "address"  :                           // key 12, object below               = 140
         {                                      // object: 12 + 4*8
             "streetAddress": "21 2nd Street",  // key 16, value 16
             "city"         : "New York",       // key 8, value 12
             "state"        : "NY",             // key 8, value 4
             "postalCode"   : "10021"           // key 12, value 8
         },                                     // object total: 128
         "phoneNumber":                         // key: 16, value array below         = 172
         [                                      // array: 12 + 2*4 + values below: 156
             {                                  // object 12 + 2*8
               "type"  : "home",                // key 8, value 8
               "number": "212 555-1234"         // key 8, value 16
             },                                 // object total: 68
             {                                  // object 12 + 2*8
               "type"  : "fax",                 // key 8, value 8
               "number": "646 555-4567"         // key 8, value 16
             }                                  // object total: 68
         ]                                      // array total: 156
    }                                           // great total:                         412 bytes

    The uncompressed text file used roughly 500 bytes, so in this case we end up using about
    the same space as the text representation.

    Other measurements have shown a slightly bigger binary size than a compact text
    representation where all possible whitespace was stripped out.
*/

class Array;
class Object;
class Value;
class Entry;

template<int pos, int width>
class qle_bitfield
{
public:
    uint32_t val;

    enum {
        mask = ((1u << width) - 1) << pos
    };

    void operator=(uint32_t t) {
        uint32_t i = val;
        i &= ~mask;
        i |= t << pos;
        val = i;
    }
    operator uint32_t() const {
        uint32_t t = val;
        t &= mask;
        t >>= pos;
        return t;
    }
    bool operator!() const { return !operator uint32_t(); }
    bool operator==(uint32_t t) { return uint32_t(*this) == t; }
    bool operator!=(uint32_t t) { return uint32_t(*this) != t; }
    bool operator<(uint32_t t) { return uint32_t(*this) < t; }
    bool operator>(uint32_t t) { return uint32_t(*this) > t; }
    bool operator<=(uint32_t t) { return uint32_t(*this) <= t; }
    bool operator>=(uint32_t t) { return uint32_t(*this) >= t; }
    void operator+=(uint32_t i) { *this = (uint32_t(*this) + i); }
    void operator-=(uint32_t i) { *this = (uint32_t(*this) - i); }
};

template<int pos, int width>
class qle_signedbitfield
{
public:
    uint32_t val;

    enum {
        mask = ((1u << width) - 1) << pos
    };

    void operator=(int t) {
        uint32_t i = val;
        i &= ~mask;
        i |= t << pos;
        val = i;
    }
    operator int() const {
        uint32_t i = val;
        i <<= 32 - width - pos;
        int t = (int) i;
        t >>= pos;
        return t;
    }

    bool operator!() const { return !operator int(); }
    bool operator==(int t) { return int(*this) == t; }
    bool operator!=(int t) { return int(*this) != t; }
    bool operator<(int t) { return int(*this) < t; }
    bool operator>(int t) { return int(*this) > t; }
    bool operator<=(int t) { return int(*this) <= t; }
    bool operator>=(int t) { return int(*this) >= t; }
    void operator+=(int i) { *this = (int(*this) + i); }
    void operator-=(int i) { *this = (int(*this) - i); }
};

typedef uint32_t offset;

// round the size up to the next 4 byte boundary
int alignedSize(int size) { return (size + 3) & ~3; }

static int qStringSize(const std::string &ba)
{
    int l = 4 + static_cast<int>(ba.length());
    return alignedSize(l);
}

// returns INT_MAX if it can't compress it into 28 bits
static int compressedNumber(double d)
{
    // this relies on details of how ieee floats are represented
    const int exponent_off = 52;
    const uint64_t fraction_mask = 0x000fffffffffffffull;
    const uint64_t exponent_mask = 0x7ff0000000000000ull;

    uint64_t val;
    memcpy (&val, &d, sizeof(double));
    int exp = (int)((val & exponent_mask) >> exponent_off) - 1023;
    if (exp < 0 || exp > 25)
        return INT_MAX;

    uint64_t non_int = val & (fraction_mask >> exp);
    if (non_int)
        return INT_MAX;

    bool neg = (val >> 63) != 0;
    val &= fraction_mask;
    val |= ((uint64_t)1 << 52);
    int res = (int)(val >> (52 - exp));
    return neg ? -res : res;
}

static void toInternal(char *addr, const char *data, int size)
{
    memcpy(addr, &size, 4);
    memcpy(addr + 4, data, size);
}

class String
{
public:
    String(const char *data) { d = (Data *)data; }

    struct Data {
        int length;
        char utf8[1];
    };

    Data *d;

    void operator=(const std::string &ba)
    {
        d->length = static_cast<int>(ba.length());
        memcpy(d->utf8, ba.data(), ba.length());
    }

    bool operator==(const std::string &ba) const {
        return toString() == ba;
    }
    bool operator!=(const std::string &str) const {
        return !operator==(str);
    }
    bool operator>=(const std::string &str) const {
        // ###
        return toString() >= str;
    }

    bool operator==(const String &str) const {
        if (d->length != str.d->length)
            return false;
        return !memcmp(d->utf8, str.d->utf8, d->length);
    }
    bool operator<(const String &other) const;
    bool operator>=(const String &other) const { return !(*this < other); }

    std::string toString() const {
        return std::string(d->utf8, d->length);
    }

};

bool String::operator<(const String &other) const
{
    int alen = d->length;
    int blen = other.d->length;
    int l = std::min(alen, blen);
    char *a = d->utf8;
    char *b = other.d->utf8;

    while (l-- && *a == *b)
        a++,b++;
    if (l==-1)
        return (alen < blen);
    return (unsigned char)(*a) < (unsigned char)(*b);
}

static void copyString(char *dest, const std::string &str)
{
    String string(dest);
    string = str;
}


/*
 Base is the base class for both Object and Array. Both classe work more or less the same way.
 The class starts with a header (defined by the struct below), then followed by data (the data for
 values in the Array case and Entry's (see below) for objects.

 After the data a table follows (tableOffset points to it) containing Value objects for Arrays, and
 offsets from the beginning of the object to Entry's in the case of Object.

 Entry's in the Object's table are lexicographically sorted by key in the table(). This allows the usage
 of a binary search over the keys in an Object.
 */
class Base
{
public:
    uint32_t size;
    union {
        uint32_t _dummy;
        qle_bitfield<0, 1> is_object;
        qle_bitfield<1, 31> length;
    };
    offset tableOffset;
    // content follows here

    bool isObject() const { return !!is_object; }
    bool isArray() const { return !isObject(); }

    offset *table() const { return (offset *) (((char *) this) + tableOffset); }

    int reserveSpace(uint32_t dataSize, int posInTable, uint32_t numItems, bool replace);
    void removeItems(int pos, int numItems);
};

class Object : public Base
{
public:
    Entry *entryAt(int i) const {
        return reinterpret_cast<Entry *>(((char *)this) + table()[i]);
    }
    int indexOf(const std::string &key, bool *exists);

    bool isValid() const;
};


class Value
{
public:
    enum {
        MaxSize = (1<<27) - 1
    };
    union {
        uint32_t _dummy;
        qle_bitfield<0, 3> type;
        qle_bitfield<3, 1> intValue;
        qle_bitfield<4, 1> _; // Ex-latin1Key
        qle_bitfield<5, 27> value;  // Used as offset in case of Entry(?)
        qle_signedbitfield<5, 27> int_value;
    };

    char *data(const Base *b) const { return ((char *)b) + value; }
    int usedStorage(const Base *b) const;

    bool toBoolean() const { return value != 0; }
    double toDouble(const Base *b) const;
    std::string toString(const Base *b) const;
    Base *base(const Base *b) const;

    bool isValid(const Base *b) const;

    static int requiredStorage(JsonValue &v, bool *compressed);
    static uint32_t valueToStore(const JsonValue &v, uint32_t offset);
    static void copyData(const JsonValue &v, char *dest, bool compressed);
};

class Array : public Base
{
public:
    Value at(int i) const { return *(Value *) (table() + i); }
    Value &operator[](int i) { return *(Value *) (table() + i); }

    bool isValid() const;
};

class Entry {
public:
    Value value;
    // key
    // value data follows key

    int size() const
    {
        int s = sizeof(Entry);
        s += sizeof(uint32_t) + (*(int *) ((const char *)this + sizeof(Entry)));
        return alignedSize(s);
    }

    int usedStorage(Base *b) const
    {
        return size() + value.usedStorage(b);
    }

    String shallowKey() const
    {
        return String((const char *)this + sizeof(Entry));
    }

    std::string key() const
    {
        return shallowKey().toString();
    }

    bool operator==(const std::string &key) const;
    bool operator!=(const std::string &key) const { return !operator==(key); }
    bool operator>=(const std::string &key) const { return shallowKey() >= key; }

    bool operator==(const Entry &other) const;
    bool operator>=(const Entry &other) const;
};

bool operator<(const std::string &key, const Entry &e)
{
    return e >= key;
}


class Header
{
public:
    uint32_t tag; // 'qbjs'
    uint32_t version; // 1
    Base *root() { return (Base *)(this + 1); }
};


double Value::toDouble(const Base *b) const
{
    // assert(type == JsonValue::Double);
    if (intValue)
        return int_value;

    double d;
    memcpy(&d, (const char *)b + value, 8);
    return d;
}

std::string Value::toString(const Base *b) const
{
    String s(data(b));
    return s.toString();
}

Base *Value::base(const Base *b) const
{
    // assert(type == JsonValue::Array || type == JsonValue::Object);
    return reinterpret_cast<Base *>(data(b));
}

class AtomicInt
{
public:
    bool ref() { return ++x != 0; }
    bool deref() { return --x != 0; }
    int load() { return x.load(std::memory_order_seq_cst); }
private:
    std::atomic<int> x { 0 };
};


class SharedString
{
public:
    AtomicInt ref;
    std::string s;
};

class Data {
public:
    enum Validation {
        Unchecked,
        Validated,
        Invalid
    };

    AtomicInt ref;
    int alloc;
    union {
        char *rawData;
        Header *header;
    };
    uint32_t compactionCounter : 31;
    uint32_t ownsData : 1;

    Data(char *raw, int a)
        : alloc(a), rawData(raw), compactionCounter(0), ownsData(true)
    {
    }
    Data(int reserved, JsonValue::Type valueType)
        : rawData(nullptr), compactionCounter(0), ownsData(true)
    {
        // assert(valueType == JsonValue::Array || valueType == JsonValue::Object);

        alloc = sizeof(Header) + sizeof(Base) + reserved + sizeof(offset);
        header = (Header *)malloc(alloc);
        header->tag = JsonDocument::BinaryFormatTag;
        header->version = 1;
        Base *b = header->root();
        b->size = sizeof(Base);
        b->is_object = (valueType == JsonValue::Object);
        b->tableOffset = sizeof(Base);
        b->length = 0;
    }
    ~Data()
    { if (ownsData) free(rawData); }

    uint32_t offsetOf(const void *ptr) const { return (uint32_t)(((char *)ptr - rawData)); }

    JsonObject toObject(Object *o) const
    {
        return JsonObject(const_cast<Data *>(this), o);
    }

    JsonArray toArray(Array *a) const
    {
        return JsonArray(const_cast<Data *>(this), a);
    }

    Data *clone(Base *b, int reserve = 0)
    {
        int size = sizeof(Header) + b->size;
        if (b == header->root() && ref.load() == 1 && alloc >= size + reserve)
            return this;

        if (reserve) {
            if (reserve < 128)
                reserve = 128;
            size = std::max(size + reserve, size *2);
        }
        char *raw = (char *)malloc(size);
        memcpy(raw + sizeof(Header), b, b->size);
        Header *h = (Header *)raw;
        h->tag = JsonDocument::BinaryFormatTag;
        h->version = 1;
        const auto d = new Data(raw, size);
        d->compactionCounter = (b == header->root()) ? compactionCounter : 0;
        return d;
    }

    void compact();
    bool valid() const;

private:
    Data(const Data &);
    void operator=(const Data &);
};


void objectToJson(const Object *o, std::string &json, int indent, bool compact = false);
void arrayToJson(const Array *a, std::string &json, int indent, bool compact = false);

class Parser
{
public:
    Parser(const char *json, int length);

    JsonDocument parse(JsonParseError *error);

    class ParsedObject
    {
    public:
        ParsedObject(Parser *p, int pos) : parser(p), objectPosition(pos) {
            offsets.reserve(64);
        }
        void insert(uint32_t offset);

        Parser *parser;
        int objectPosition;
        std::vector<uint32_t> offsets;

        Entry *entryAt(size_t i) const {
            return reinterpret_cast<Entry *>(parser->data + objectPosition + offsets[i]);
        }
    };


private:
    void eatBOM();
    bool eatSpace();
    char nextToken();

    bool parseObject();
    bool parseArray();
    bool parseMember(int baseOffset);
    bool parseString();
    bool parseEscapeSequence();
    bool parseValue(Value *val, int baseOffset);
    bool parseNumber(Value *val, int baseOffset);

    void addChar(char c) {
        const int pos = reserveSpace(1);
        data[pos] = c;
    }

    const char *head;
    const char *json;
    const char *end;

    char *data;
    int dataLength;
    int current;
    int nestingLevel;
    JsonParseError::ParseError lastError;

    int reserveSpace(int space) {
        if (current + space >= dataLength) {
            dataLength = 2*dataLength + space;
            data = (char *)realloc(data, dataLength);
        }
        int pos = current;
        current += space;
        return pos;
    }
};

} // namespace Internal

using namespace Internal;

/*!
    \class JsonValue
    \inmodule QtCore
    \ingroup json
    \ingroup shared
    \reentrant
    \since 5.0

    \brief The JsonValue class encapsulates a value in JSON.

    A value in JSON can be one of 6 basic types:

    JSON is a format to store structured data. It has 6 basic data types:

    \list
    \li bool JsonValue::Bool
    \li double JsonValue::Double
    \li string JsonValue::String
    \li array JsonValue::Array
    \li object JsonValue::Object
    \li null JsonValue::Null
    \endlist

    A value can represent any of the above data types. In addition, JsonValue has one special
    flag to represent undefined values. This can be queried with isUndefined().

    The type of the value can be queried with type() or accessors like isBool(), isString(), and so on.
    Likewise, the value can be converted to the type stored in it using the toBool(), toString() and so on.

    Values are strictly typed internally and contrary to QVariant will not attempt to do any implicit type
    conversions. This implies that converting to a type that is not stored in the value will return a default
    constructed return value.

    \section1 JsonValueRef

    JsonValueRef is a helper class for JsonArray and JsonObject.
    When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the element in the JsonArray or JsonObject
    from which you got the reference.

    The following methods return JsonValueRef:
    \list
    \li \l {JsonArray}::operator[](int i)
    \li \l {JsonObject}::operator[](const QString & key) const
    \endlist

    \sa {JSON Support in Qt}, {JSON Save Game Example}
*/

/*!
    Creates a JsonValue of type \a type.

    The default is to create a Null value.
 */
JsonValue::JsonValue(Type type)
    : ui(0), d(nullptr), t(type)
{
}

/*!
    \internal
 */
JsonValue::JsonValue(Internal::Data *data, Internal::Base *base, const Internal::Value &v)
    : d(nullptr), t((Type)(uint32_t)v.type)
{
    switch (t) {
    case Undefined:
    case Null:
        dbl = 0;
        break;
    case Bool:
        b = v.toBoolean();
        break;
    case Double:
        dbl = v.toDouble(base);
        break;
    case String: {
        stringData = new Internal::SharedString;
        stringData->s = v.toString(base);
        stringData->ref.ref();
        break;
    }
    case Array:
    case Object:
        d = data;
        this->base = v.base(base);
        break;
    }
    if (d)
        d->ref.ref();
}

/*!
    Creates a value of type Bool, with value \a b.
 */
JsonValue::JsonValue(bool b)
    : d(nullptr), t(Bool)
{
    this->b = b;
}

/*!
    Creates a value of type Double, with value \a n.
 */
JsonValue::JsonValue(double n)
    : d(nullptr), t(Double)
{
    this->dbl = n;
}

/*!
    \overload
    Creates a value of type Double, with value \a n.
 */
JsonValue::JsonValue(int n)
    : d(nullptr), t(Double)
{
    this->dbl = n;
}

/*!
    \overload
    Creates a value of type Double, with value \a n.
    NOTE: the integer limits for IEEE 754 double precision data is 2^53 (-9007199254740992 to +9007199254740992).
    If you pass in values outside this range expect a loss of precision to occur.
 */
JsonValue::JsonValue(int64_t n)
    : d(nullptr), t(Double)
{
    this->dbl = double(n);
}

/*!
    Creates a value of type String, with value \a s.
 */
JsonValue::JsonValue(const std::string &s)
    : d(nullptr), t(String)
{
    stringData = new Internal::SharedString;
    stringData->s = s;
    stringData->ref.ref();
}

JsonValue::JsonValue(const char *s)
    : d(nullptr), t(String)
{
    stringData = new Internal::SharedString;
    stringData->s = s;
    stringData->ref.ref();
}

/*!
    Creates a value of type Array, with value \a a.
 */
JsonValue::JsonValue(const JsonArray &a)
    : d(a.d), t(Array)
{
    base = a.a;
    if (d)
        d->ref.ref();
}

/*!
    Creates a value of type Object, with value \a o.
 */
JsonValue::JsonValue(const JsonObject &o)
    : d(o.d), t(Object)
{
    base = o.o;
    if (d)
        d->ref.ref();
}


/*!
    Destroys the value.
 */
JsonValue::~JsonValue()
{
    if (t == String && stringData && !stringData->ref.deref())
        free(stringData);

    if (d && !d->ref.deref())
        delete d;
}

/*!
    Creates a copy of \a other.
 */
JsonValue::JsonValue(const JsonValue &other)
    : t(other.t)
{
    d = other.d;
    ui = other.ui;
    if (d)
        d->ref.ref();

    if (t == String && stringData)
        stringData->ref.ref();
}

/*!
    Assigns the value stored in \a other to this object.
 */
JsonValue &JsonValue::operator=(const JsonValue &other)
{
    if (t == String && stringData && !stringData->ref.deref())
        free(stringData);

    t = other.t;
    dbl = other.dbl;

    if (d != other.d) {

        if (d && !d->ref.deref())
            delete d;
        d = other.d;
        if (d)
            d->ref.ref();

    }

    if (t == String && stringData)
        stringData->ref.ref();

    return *this;
}

/*!
    \fn bool JsonValue::isNull() const

    Returns \c true if the value is null.
*/

/*!
    \fn bool JsonValue::isBool() const

    Returns \c true if the value contains a boolean.

    \sa toBool()
 */

/*!
    \fn bool JsonValue::isDouble() const

    Returns \c true if the value contains a double.

    \sa toDouble()
 */

/*!
    \fn bool JsonValue::isString() const

    Returns \c true if the value contains a string.

    \sa toString()
 */

/*!
    \fn bool JsonValue::isArray() const

    Returns \c true if the value contains an array.

    \sa toArray()
 */

/*!
    \fn bool JsonValue::isObject() const

    Returns \c true if the value contains an object.

    \sa toObject()
 */

/*!
    \fn bool JsonValue::isUndefined() const

    Returns \c true if the value is undefined. This can happen in certain
    error cases as e.g. accessing a non existing key in a JsonObject.
 */


/*!
    \enum JsonValue::Type

    This enum describes the type of the JSON value.

    \value Null     A Null value
    \value Bool     A boolean value. Use toBool() to convert to a bool.
    \value Double   A double. Use toDouble() to convert to a double.
    \value String   A string. Use toString() to convert to a QString.
    \value Array    An array. Use toArray() to convert to a JsonArray.
    \value Object   An object. Use toObject() to convert to a JsonObject.
    \value Undefined The value is undefined. This is usually returned as an
                    error condition, when trying to read an out of bounds value
                    in an array or a non existent key in an object.
*/

/*!
    Returns the type of the value.

    \sa JsonValue::Type
 */


/*!
    Converts the value to a bool and returns it.

    If type() is not bool, the \a defaultValue will be returned.
 */
bool JsonValue::toBool(bool defaultValue) const
{
    if (t != Bool)
        return defaultValue;
    return b;
}

/*!
    Converts the value to an int and returns it.

    If type() is not Double or the value is not a whole number,
    the \a defaultValue will be returned.
 */
int JsonValue::toInt(int defaultValue) const
{
    if (t == Double && int(dbl) == dbl)
        return int(dbl);
    return defaultValue;
}

/*!
    Converts the value to a double and returns it.

    If type() is not Double, the \a defaultValue will be returned.
 */
double JsonValue::toDouble(double defaultValue) const
{
    if (t != Double)
        return defaultValue;
    return dbl;
}

/*!
    Converts the value to a QString and returns it.

    If type() is not String, the \a defaultValue will be returned.
 */
std::string JsonValue::toString(const std::string &defaultValue) const
{
    if (t != String)
        return defaultValue;
    return stringData->s;
}

/*!
    Converts the value to an array and returns it.

    If type() is not Array, the \a defaultValue will be returned.
 */
JsonArray JsonValue::toArray(const JsonArray &defaultValue) const
{
    if (!d || t != Array)
        return defaultValue;

    return JsonArray(d, static_cast<Internal::Array *>(base));
}

/*!
    \overload

    Converts the value to an array and returns it.

    If type() is not Array, a \l{JsonArray::}{JsonArray()} will be returned.
 */
JsonArray JsonValue::toArray() const
{
    return toArray(JsonArray());
}

/*!
    Converts the value to an object and returns it.

    If type() is not Object, the \a defaultValue will be returned.
 */
JsonObject JsonValue::toObject(const JsonObject &defaultValue) const
{
    if (!d || t != Object)
        return defaultValue;

    return JsonObject(d, static_cast<Internal::Object *>(base));
}

/*!
    \overload

    Converts the value to an object and returns it.

    If type() is not Object, the \l {JsonObject::}{JsonObject()} will be returned.
*/
JsonObject JsonValue::toObject() const
{
    return toObject(JsonObject());
}

/*!
    Returns \c true if the value is equal to \a other.
 */
bool JsonValue::operator==(const JsonValue &other) const
{
    if (t != other.t)
        return false;

    switch (t) {
    case Undefined:
    case Null:
        break;
    case Bool:
        return b == other.b;
    case Double:
        return dbl == other.dbl;
    case String:
        return toString() == other.toString();
    case Array:
        if (base == other.base)
            return true;
        if (!base)
            return !other.base->length;
        if (!other.base)
            return !base->length;
        return JsonArray(d, static_cast<Internal::Array *>(base))
                == JsonArray(other.d, static_cast<Internal::Array *>(other.base));
    case Object:
        if (base == other.base)
            return true;
        if (!base)
            return !other.base->length;
        if (!other.base)
            return !base->length;
        return JsonObject(d, static_cast<Internal::Object *>(base))
                == JsonObject(other.d, static_cast<Internal::Object *>(other.base));
    }
    return true;
}

/*!
    Returns \c true if the value is not equal to \a other.
 */
bool JsonValue::operator!=(const JsonValue &other) const
{
    return !(*this == other);
}

/*!
    \internal
 */
void JsonValue::detach()
{
    if (!d)
        return;

    Internal::Data *x = d->clone(base);
    x->ref.ref();
    if (!d->ref.deref())
        delete d;
    d = x;
    base = static_cast<Internal::Object *>(d->header->root());
}


/*!
    \class JsonValueRef
    \inmodule QtCore
    \reentrant
    \brief The JsonValueRef class is a helper class for JsonValue.

    \internal

    \ingroup json

    When you get an object of type JsonValueRef, if you can assign to it,
    the assignment will apply to the character in the string from
    which you got the reference. That is its whole purpose in life.

    You can use it exactly in the same way as a reference to a JsonValue.

    The JsonValueRef becomes invalid once modifications are made to the
    string: if you want to keep the character, copy it into a JsonValue.

    Most of the JsonValue member functions also exist in JsonValueRef.
    However, they are not explicitly documented here.
*/


JsonValueRef &JsonValueRef::operator=(const JsonValue &val)
{
    if (is_object)
        o->setValueAt(index, val);
    else
        a->replace(index, val);

    return *this;
}

JsonValueRef &JsonValueRef::operator=(const JsonValueRef &ref)
{
    if (is_object)
        o->setValueAt(index, ref);
    else
        a->replace(index, ref);

    return *this;
}

JsonArray JsonValueRef::toArray() const
{
    return toValue().toArray();
}

JsonObject JsonValueRef::toObject() const
{
    return toValue().toObject();
}

JsonValue JsonValueRef::toValue() const
{
    if (!is_object)
        return a->at(index);
    return o->valueAt(index);
}

/*!
    \class JsonArray
    \inmodule QtCore
    \ingroup json
    \ingroup shared
    \reentrant
    \since 5.0

    \brief The JsonArray class encapsulates a JSON array.

    A JSON array is a list of values. The list can be manipulated by inserting and
    removing JsonValue's from the array.

    A JsonArray can be converted to and from a QVariantList. You can query the
    number of entries with size(), insert(), and removeAt() entries from it
    and iterate over its content using the standard C++ iterator pattern.

    JsonArray is an implicitly shared class and shares the data with the document
    it has been created from as long as it is not being modified.

    You can convert the array to and from text based JSON through JsonDocument.

    \sa {JSON Support in Qt}, {JSON Save Game Example}
*/

/*!
    \typedef JsonArray::Iterator

    Qt-style synonym for JsonArray::iterator.
*/

/*!
    \typedef JsonArray::ConstIterator

    Qt-style synonym for JsonArray::const_iterator.
*/

/*!
    \typedef JsonArray::size_type

    Typedef for int. Provided for STL compatibility.
*/

/*!
    \typedef JsonArray::value_type

    Typedef for JsonValue. Provided for STL compatibility.
*/

/*!
    \typedef JsonArray::difference_type

    Typedef for int. Provided for STL compatibility.
*/

/*!
    \typedef JsonArray::pointer

    Typedef for JsonValue *. Provided for STL compatibility.
*/

/*!
    \typedef JsonArray::const_pointer

    Typedef for const JsonValue *. Provided for STL compatibility.
*/

/*!
    \typedef JsonArray::reference

    Typedef for JsonValue &. Provided for STL compatibility.
*/

/*!
    \typedef JsonArray::const_reference

    Typedef for const JsonValue &. Provided for STL compatibility.
*/

/*!
    Creates an empty array.
 */
JsonArray::JsonArray()
    : d(nullptr), a(nullptr)
{
}

JsonArray::JsonArray(std::initializer_list<JsonValue> args)
    : d(nullptr), a(nullptr)
{
    for (auto i = args.begin(); i != args.end(); ++i)
        append(*i);
}

/*!
    \fn JsonArray::JsonArray(std::initializer_list<JsonValue> args)
    \since 5.4
    Creates an array initialized from \a args initialization list.

    JsonArray can be constructed in a way similar to JSON notation,
    for example:
    \code
    JsonArray array = { 1, 2.2, QString() };
    \endcode
 */

/*!
    \internal
 */
JsonArray::JsonArray(Internal::Data *data, Internal::Array *array)
    : d(data), a(array)
{
    // assert(data);
    // assert(array);
    d->ref.ref();
}

/*!
    Deletes the array.
 */
JsonArray::~JsonArray()
{
    if (d && !d->ref.deref())
        delete d;
}

/*!
    Creates a copy of \a other.

    Since JsonArray is implicitly shared, the copy is shallow
    as long as the object doesn't get modified.
 */
JsonArray::JsonArray(const JsonArray &other)
{
    d = other.d;
    a = other.a;
    if (d)
        d->ref.ref();
}

/*!
    Assigns \a other to this array.
 */
JsonArray &JsonArray::operator=(const JsonArray &other)
{
    if (d != other.d) {
        if (d && !d->ref.deref())
            delete d;
        d = other.d;
        if (d)
            d->ref.ref();
    }
    a = other.a;

    return *this;
}

/*! \fn JsonArray &JsonArray::operator+=(const JsonValue &value)

    Appends \a value to the array, and returns a reference to the array itself.

    \since 5.3
    \sa append(), operator<<()
*/

/*! \fn JsonArray JsonArray::operator+(const JsonValue &value) const

    Returns an array that contains all the items in this array followed
    by the provided \a value.

    \since 5.3
    \sa operator+=()
*/

/*! \fn JsonArray &JsonArray::operator<<(const JsonValue &value)

    Appends \a value to the array, and returns a reference to the array itself.

    \since 5.3
    \sa operator+=(), append()
*/

/*!
    Returns the number of values stored in the array.
 */
int JsonArray::size() const
{
    if (!d)
        return 0;

    return (int)a->length;
}

/*!
    \fn JsonArray::count() const

    Same as size().

    \sa size()
*/

/*!
    Returns \c true if the object is empty. This is the same as size() == 0.

    \sa size()
 */
bool JsonArray::isEmpty() const
{
    if (!d)
        return true;

    return !a->length;
}

/*!
    Returns a JsonValue representing the value for index \a i.

    The returned JsonValue is \c Undefined, if \a i is out of bounds.

 */
JsonValue JsonArray::at(int i) const
{
    if (!a || i < 0 || i >= (int)a->length)
        return JsonValue(JsonValue::Undefined);

    return JsonValue(d, a, a->at(i));
}

/*!
    Returns the first value stored in the array.

    Same as \c at(0).

    \sa at()
 */
JsonValue JsonArray::first() const
{
    return at(0);
}

/*!
    Returns the last value stored in the array.

    Same as \c{at(size() - 1)}.

    \sa at()
 */
JsonValue JsonArray::last() const
{
    return at(a ? (a->length - 1) : 0);
}

/*!
    Inserts \a value at the beginning of the array.

    This is the same as \c{insert(0, value)} and will prepend \a value to the array.

    \sa append(), insert()
 */
void JsonArray::prepend(const JsonValue &value)
{
    insert(0, value);
}

/*!
    Inserts \a value at the end of the array.

    \sa prepend(), insert()
 */
void JsonArray::append(const JsonValue &value)
{
    insert(a ? (int)a->length : 0, value);
}

/*!
    Removes the value at index position \a i. \a i must be a valid
    index position in the array (i.e., \c{0 <= i < size()}).

    \sa insert(), replace()
 */
void JsonArray::removeAt(int i)
{
    if (!a || i < 0 || i >= (int)a->length)
        return;

    detach();
    a->removeItems(i, 1);
    ++d->compactionCounter;
    if (d->compactionCounter > 32u && d->compactionCounter >= unsigned(a->length) / 2u)
        compact();
}

/*! \fn void JsonArray::removeFirst()

    Removes the first item in the array. Calling this function is
    equivalent to calling \c{removeAt(0)}. The array must not be empty. If
    the array can be empty, call isEmpty() before calling this
    function.

    \sa removeAt(), removeLast()
*/

/*! \fn void JsonArray::removeLast()

    Removes the last item in the array. Calling this function is
    equivalent to calling \c{removeAt(size() - 1)}. The array must not be
    empty. If the array can be empty, call isEmpty() before calling
    this function.

    \sa removeAt(), removeFirst()
*/

/*!
    Removes the item at index position \a i and returns it. \a i must
    be a valid index position in the array (i.e., \c{0 <= i < size()}).

    If you don't use the return value, removeAt() is more efficient.

    \sa removeAt()
 */
JsonValue JsonArray::takeAt(int i)
{
    if (!a || i < 0 || i >= (int)a->length)
        return JsonValue(JsonValue::Undefined);

    JsonValue v(d, a, a->at(i));
    removeAt(i); // detaches
    return v;
}

/*!
    Inserts \a value at index position \a i in the array. If \a i
    is \c 0, the value is prepended to the array. If \a i is size(), the
    value is appended to the array.

    \sa append(), prepend(), replace(), removeAt()
 */
void JsonArray::insert(int i, const JsonValue &value)
{
    // assert (i >= 0 && i <= (a ? (int)a->length : 0));
    JsonValue val = value;

    bool compressed;
    int valueSize = Internal::Value::requiredStorage(val, &compressed);

    detach(valueSize + sizeof(Internal::Value));

    if (!a->length)
        a->tableOffset = sizeof(Internal::Array);

    int valueOffset = a->reserveSpace(valueSize, i, 1, false);
    if (!valueOffset)
        return;

    Internal::Value &v = (*a)[i];
    v.type = (val.t == JsonValue::Undefined ? JsonValue::Null : val.t);
    v.intValue = compressed;
    v.value = Internal::Value::valueToStore(val, valueOffset);
    if (valueSize)
        Internal::Value::copyData(val, (char *)a + valueOffset, compressed);
}

/*!
    \fn JsonArray::iterator JsonArray::insert(iterator before, const JsonValue &value)

    Inserts \a value before the position pointed to by \a before, and returns an iterator
    pointing to the newly inserted item.

    \sa erase(), insert()
*/

/*!
    \fn JsonArray::iterator JsonArray::erase(iterator it)

    Removes the item pointed to by \a it, and returns an iterator pointing to the
    next item.

    \sa removeAt()
*/

/*!
    Replaces the item at index position \a i with \a value. \a i must
    be a valid index position in the array (i.e., \c{0 <= i < size()}).

    \sa operator[](), removeAt()
 */
void JsonArray::replace(int i, const JsonValue &value)
{
    // assert (a && i >= 0 && i < (int)(a->length));
    JsonValue val = value;

    bool compressed;
    int valueSize = Internal::Value::requiredStorage(val, &compressed);

    detach(valueSize);

    if (!a->length)
        a->tableOffset = sizeof(Internal::Array);

    int valueOffset = a->reserveSpace(valueSize, i, 1, true);
    if (!valueOffset)
        return;

    Internal::Value &v = (*a)[i];
    v.type = (val.t == JsonValue::Undefined ? JsonValue::Null : val.t);
    v.intValue = compressed;
    v.value = Internal::Value::valueToStore(val, valueOffset);
    if (valueSize)
        Internal::Value::copyData(val, (char *)a + valueOffset, compressed);

    ++d->compactionCounter;
    if (d->compactionCounter > 32u && d->compactionCounter >= unsigned(a->length) / 2u)
        compact();
}

/*!
    Returns \c true if the array contains an occurrence of \a value, otherwise \c false.

    \sa count()
 */
bool JsonArray::contains(const JsonValue &value) const
{
    for (int i = 0; i < size(); i++) {
        if (at(i) == value)
            return true;
    }
    return false;
}

/*!
    Returns the value at index position \a i as a modifiable reference.
    \a i must be a valid index position in the array (i.e., \c{0 <= i <
    size()}).

    The return value is of type JsonValueRef, a helper class for JsonArray
    and JsonObject. When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the character in the JsonArray of JsonObject
    from which you got the reference.

    \sa at()
 */
JsonValueRef JsonArray::operator[](int i)
{
    // assert(a && i >= 0 && i < (int)a->length);
    return JsonValueRef(this, i);
}

/*!
    \overload

    Same as at().
 */
JsonValue JsonArray::operator[](int i) const
{
    return at(i);
}

/*!
    Returns \c true if this array is equal to \a other.
 */
bool JsonArray::operator==(const JsonArray &other) const
{
    if (a == other.a)
        return true;

    if (!a)
        return !other.a->length;
    if (!other.a)
        return !a->length;
    if (a->length != other.a->length)
        return false;

    for (int i = 0; i < (int)a->length; ++i) {
        if (JsonValue(d, a, a->at(i)) != JsonValue(other.d, other.a, other.a->at(i)))
            return false;
    }
    return true;
}

/*!
    Returns \c true if this array is not equal to \a other.
 */
bool JsonArray::operator!=(const JsonArray &other) const
{
    return !(*this == other);
}

/*! \fn JsonArray::iterator JsonArray::begin()

    Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first item in
    the array.

    \sa constBegin(), end()
*/

/*! \fn JsonArray::const_iterator JsonArray::begin() const

    \overload
*/

/*! \fn JsonArray::const_iterator JsonArray::constBegin() const

    Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first item
    in the array.

    \sa begin(), constEnd()
*/

/*! \fn JsonArray::iterator JsonArray::end()

    Returns an \l{STL-style iterators}{STL-style iterator} pointing to the imaginary item
    after the last item in the array.

    \sa begin(), constEnd()
*/

/*! \fn const_iterator JsonArray::end() const

    \overload
*/

/*! \fn JsonArray::const_iterator JsonArray::constEnd() const

    Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
    item after the last item in the array.

    \sa constBegin(), end()
*/

/*! \fn void JsonArray::push_back(const JsonValue &value)

    This function is provided for STL compatibility. It is equivalent
    to \l{JsonArray::append()}{append(value)} and will append \a value to the array.
*/

/*! \fn void JsonArray::push_front(const JsonValue &value)

    This function is provided for STL compatibility. It is equivalent
    to \l{JsonArray::prepend()}{prepend(value)} and will prepend \a value to the array.
*/

/*! \fn void JsonArray::pop_front()

    This function is provided for STL compatibility. It is equivalent
    to removeFirst(). The array must not be empty. If the array can be
    empty, call isEmpty() before calling this function.
*/

/*! \fn void JsonArray::pop_back()

    This function is provided for STL compatibility. It is equivalent
    to removeLast(). The array must not be empty. If the array can be
    empty, call isEmpty() before calling this function.
*/

/*! \fn bool JsonArray::empty() const

    This function is provided for STL compatibility. It is equivalent
    to isEmpty() and returns \c true if the array is empty.
*/

/*! \class JsonArray::iterator
    \inmodule QtCore
    \brief The JsonArray::iterator class provides an STL-style non-const iterator for JsonArray.

    JsonArray::iterator allows you to iterate over a JsonArray
    and to modify the array item associated with the
    iterator. If you want to iterate over a const JsonArray, use
    JsonArray::const_iterator instead. It is generally a good practice to
    use JsonArray::const_iterator on a non-const JsonArray as well, unless
    you need to change the JsonArray through the iterator. Const
    iterators are slightly faster and improves code readability.

    The default JsonArray::iterator constructor creates an uninitialized
    iterator. You must initialize it using a JsonArray function like
    JsonArray::begin(), JsonArray::end(), or JsonArray::insert() before you can
    start iterating.

    Most JsonArray functions accept an integer index rather than an
    iterator. For that reason, iterators are rarely useful in
    connection with JsonArray. One place where STL-style iterators do
    make sense is as arguments to \l{generic algorithms}.

    Multiple iterators can be used on the same array. However, be
    aware that any non-const function call performed on the JsonArray
    will render all existing iterators undefined.

    \sa JsonArray::const_iterator
*/

/*! \typedef JsonArray::iterator::iterator_category

  A synonym for \e {std::random_access_iterator_tag} indicating
  this iterator is a random access iterator.
*/

/*! \typedef JsonArray::iterator::difference_type

    \internal
*/

/*! \typedef JsonArray::iterator::value_type

    \internal
*/

/*! \typedef JsonArray::iterator::reference

    \internal
*/

/*! \typedef JsonArray::iterator::pointer

    \internal
*/

/*! \fn JsonArray::iterator::iterator()

    Constructs an uninitialized iterator.

    Functions like operator*() and operator++() should not be called
    on an uninitialized iterator. Use operator=() to assign a value
    to it before using it.

    \sa JsonArray::begin(), JsonArray::end()
*/

/*! \fn JsonArray::iterator::iterator(JsonArray *array, int index)
    \internal
*/

/*! \fn JsonValueRef JsonArray::iterator::operator*() const


    Returns a modifiable reference to the current item.

    You can change the value of an item by using operator*() on the
    left side of an assignment.

    The return value is of type JsonValueRef, a helper class for JsonArray
    and JsonObject. When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the character in the JsonArray of JsonObject
    from which you got the reference.
*/

/*! \fn JsonValueRef *JsonArray::iterator::operator->() const

    Returns a pointer to a modifiable reference to the current item.
*/

/*! \fn JsonValueRef JsonArray::iterator::operator[](int j) const

    Returns a modifiable reference to the item at offset \a j from the
    item pointed to by this iterator (the item at position \c{*this + j}).

    This function is provided to make JsonArray iterators behave like C++
    pointers.

    The return value is of type JsonValueRef, a helper class for JsonArray
    and JsonObject. When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the character in the JsonArray of JsonObject
    from which you got the reference.

    \sa operator+()
*/

/*!
    \fn bool JsonArray::iterator::operator==(const iterator &other) const
    \fn bool JsonArray::iterator::operator==(const const_iterator &other) const

    Returns \c true if \a other points to the same item as this
    iterator; otherwise returns \c false.

    \sa operator!=()
*/

/*!
    \fn bool JsonArray::iterator::operator!=(const iterator &other) const
    \fn bool JsonArray::iterator::operator!=(const const_iterator &other) const

    Returns \c true if \a other points to a different item than this
    iterator; otherwise returns \c false.

    \sa operator==()
*/

/*!
    \fn bool JsonArray::iterator::operator<(const iterator& other) const
    \fn bool JsonArray::iterator::operator<(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is less than
    the item pointed to by the \a other iterator.
*/

/*!
    \fn bool JsonArray::iterator::operator<=(const iterator& other) const
    \fn bool JsonArray::iterator::operator<=(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is less than
    or equal to the item pointed to by the \a other iterator.
*/

/*!
    \fn bool JsonArray::iterator::operator>(const iterator& other) const
    \fn bool JsonArray::iterator::operator>(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is greater
    than the item pointed to by the \a other iterator.
*/

/*!
    \fn bool JsonArray::iterator::operator>=(const iterator& other) const
    \fn bool JsonArray::iterator::operator>=(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is greater
    than or equal to the item pointed to by the \a other iterator.
*/

/*! \fn JsonArray::iterator &JsonArray::iterator::operator++()

    The prefix ++ operator, \c{++it}, advances the iterator to the
    next item in the array and returns an iterator to the new current
    item.

    Calling this function on JsonArray::end() leads to undefined results.

    \sa operator--()
*/

/*! \fn JsonArray::iterator JsonArray::iterator::operator++(int)

    \overload

    The postfix ++ operator, \c{it++}, advances the iterator to the
    next item in the array and returns an iterator to the previously
    current item.
*/

/*! \fn JsonArray::iterator &JsonArray::iterator::operator--()

    The prefix -- operator, \c{--it}, makes the preceding item
    current and returns an iterator to the new current item.

    Calling this function on JsonArray::begin() leads to undefined results.

    \sa operator++()
*/

/*! \fn JsonArray::iterator JsonArray::iterator::operator--(int)

    \overload

    The postfix -- operator, \c{it--}, makes the preceding item
    current and returns an iterator to the previously current item.
*/

/*! \fn JsonArray::iterator &JsonArray::iterator::operator+=(int j)

    Advances the iterator by \a j items. If \a j is negative, the
    iterator goes backward.

    \sa operator-=(), operator+()
*/

/*! \fn JsonArray::iterator &JsonArray::iterator::operator-=(int j)

    Makes the iterator go back by \a j items. If \a j is negative,
    the iterator goes forward.

    \sa operator+=(), operator-()
*/

/*! \fn JsonArray::iterator JsonArray::iterator::operator+(int j) const

    Returns an iterator to the item at \a j positions forward from
    this iterator. If \a j is negative, the iterator goes backward.

    \sa operator-(), operator+=()
*/

/*! \fn JsonArray::iterator JsonArray::iterator::operator-(int j) const

    Returns an iterator to the item at \a j positions backward from
    this iterator. If \a j is negative, the iterator goes forward.

    \sa operator+(), operator-=()
*/

/*! \fn int JsonArray::iterator::operator-(iterator other) const

    Returns the number of items between the item pointed to by \a
    other and the item pointed to by this iterator.
*/

/*! \class JsonArray::const_iterator
    \inmodule QtCore
    \brief The JsonArray::const_iterator class provides an STL-style const iterator for JsonArray.

    JsonArray::const_iterator allows you to iterate over a
    JsonArray. If you want to modify the JsonArray as
    you iterate over it, use JsonArray::iterator instead. It is generally a
    good practice to use JsonArray::const_iterator on a non-const JsonArray
    as well, unless you need to change the JsonArray through the
    iterator. Const iterators are slightly faster and improves
    code readability.

    The default JsonArray::const_iterator constructor creates an
    uninitialized iterator. You must initialize it using a JsonArray
    function like JsonArray::constBegin(), JsonArray::constEnd(), or
    JsonArray::insert() before you can start iterating.

    Most JsonArray functions accept an integer index rather than an
    iterator. For that reason, iterators are rarely useful in
    connection with JsonArray. One place where STL-style iterators do
    make sense is as arguments to \l{generic algorithms}.

    Multiple iterators can be used on the same array. However, be
    aware that any non-const function call performed on the JsonArray
    will render all existing iterators undefined.

    \sa JsonArray::iterator
*/

/*! \fn JsonArray::const_iterator::const_iterator()

    Constructs an uninitialized iterator.

    Functions like operator*() and operator++() should not be called
    on an uninitialized iterator. Use operator=() to assign a value
    to it before using it.

    \sa JsonArray::constBegin(), JsonArray::constEnd()
*/

/*! \fn JsonArray::const_iterator::const_iterator(const JsonArray *array, int index)
    \internal
*/

/*! \typedef JsonArray::const_iterator::iterator_category

  A synonym for \e {std::random_access_iterator_tag} indicating
  this iterator is a random access iterator.
*/

/*! \typedef JsonArray::const_iterator::difference_type

    \internal
*/

/*! \typedef JsonArray::const_iterator::value_type

    \internal
*/

/*! \typedef JsonArray::const_iterator::reference

    \internal
*/

/*! \typedef JsonArray::const_iterator::pointer

    \internal
*/

/*! \fn JsonArray::const_iterator::const_iterator(const const_iterator &other)

    Constructs a copy of \a other.
*/

/*! \fn JsonArray::const_iterator::const_iterator(const iterator &other)

    Constructs a copy of \a other.
*/

/*! \fn JsonValue JsonArray::const_iterator::operator*() const

    Returns the current item.
*/

/*! \fn JsonValue *JsonArray::const_iterator::operator->() const

    Returns a pointer to the current item.
*/

/*! \fn JsonValue JsonArray::const_iterator::operator[](int j) const

    Returns the item at offset \a j from the item pointed to by this iterator (the item at
    position \c{*this + j}).

    This function is provided to make JsonArray iterators behave like C++
    pointers.

    \sa operator+()
*/

/*! \fn bool JsonArray::const_iterator::operator==(const const_iterator &other) const

    Returns \c true if \a other points to the same item as this
    iterator; otherwise returns \c false.

    \sa operator!=()
*/

/*! \fn bool JsonArray::const_iterator::operator!=(const const_iterator &other) const

    Returns \c true if \a other points to a different item than this
    iterator; otherwise returns \c false.

    \sa operator==()
*/

/*!
    \fn bool JsonArray::const_iterator::operator<(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is less than
    the item pointed to by the \a other iterator.
*/

/*!
    \fn bool JsonArray::const_iterator::operator<=(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is less than
    or equal to the item pointed to by the \a other iterator.
*/

/*!
    \fn bool JsonArray::const_iterator::operator>(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is greater
    than the item pointed to by the \a other iterator.
*/

/*!
    \fn bool JsonArray::const_iterator::operator>=(const const_iterator& other) const

    Returns \c true if the item pointed to by this iterator is greater
    than or equal to the item pointed to by the \a other iterator.
*/

/*! \fn JsonArray::const_iterator &JsonArray::const_iterator::operator++()

    The prefix ++ operator, \c{++it}, advances the iterator to the
    next item in the array and returns an iterator to the new current
    item.

    Calling this function on JsonArray::end() leads to undefined results.

    \sa operator--()
*/

/*! \fn JsonArray::const_iterator JsonArray::const_iterator::operator++(int)

    \overload

    The postfix ++ operator, \c{it++}, advances the iterator to the
    next item in the array and returns an iterator to the previously
    current item.
*/

/*! \fn JsonArray::const_iterator &JsonArray::const_iterator::operator--()

    The prefix -- operator, \c{--it}, makes the preceding item
    current and returns an iterator to the new current item.

    Calling this function on JsonArray::begin() leads to undefined results.

    \sa operator++()
*/

/*! \fn JsonArray::const_iterator JsonArray::const_iterator::operator--(int)

    \overload

    The postfix -- operator, \c{it--}, makes the preceding item
    current and returns an iterator to the previously current item.
*/

/*! \fn JsonArray::const_iterator &JsonArray::const_iterator::operator+=(int j)

    Advances the iterator by \a j items. If \a j is negative, the
    iterator goes backward.

    \sa operator-=(), operator+()
*/

/*! \fn JsonArray::const_iterator &JsonArray::const_iterator::operator-=(int j)

    Makes the iterator go back by \a j items. If \a j is negative,
    the iterator goes forward.

    \sa operator+=(), operator-()
*/

/*! \fn JsonArray::const_iterator JsonArray::const_iterator::operator+(int j) const

    Returns an iterator to the item at \a j positions forward from
    this iterator. If \a j is negative, the iterator goes backward.

    \sa operator-(), operator+=()
*/

/*! \fn JsonArray::const_iterator JsonArray::const_iterator::operator-(int j) const

    Returns an iterator to the item at \a j positions backward from
    this iterator. If \a j is negative, the iterator goes forward.

    \sa operator+(), operator-=()
*/

/*! \fn int JsonArray::const_iterator::operator-(const_iterator other) const

    Returns the number of items between the item pointed to by \a
    other and the item pointed to by this iterator.
*/


/*!
    \internal
 */
void JsonArray::detach(uint32_t reserve)
{
    if (!d) {
        d = new Internal::Data(reserve, JsonValue::Array);
        a = static_cast<Internal::Array *>(d->header->root());
        d->ref.ref();
        return;
    }
    if (reserve == 0 && d->ref.load() == 1)
        return;

    Internal::Data *x = d->clone(a, reserve);
    x->ref.ref();
    if (!d->ref.deref())
        delete d;
    d = x;
    a = static_cast<Internal::Array *>(d->header->root());
}

/*!
    \internal
 */
void JsonArray::compact()
{
    if (!d || !d->compactionCounter)
        return;

    detach();
    d->compact();
    a = static_cast<Internal::Array *>(d->header->root());
}

/*!
    \class JsonObject
    \inmodule QtCore
    \ingroup json
    \ingroup shared
    \reentrant
    \since 5.0

    \brief The JsonObject class encapsulates a JSON object.

    A JSON object is a list of key value pairs, where the keys are unique strings
    and the values are represented by a JsonValue.

    A JsonObject can be converted to and from a QVariantMap. You can query the
    number of (key, value) pairs with size(), insert(), and remove() entries from it
    and iterate over its content using the standard C++ iterator pattern.

    JsonObject is an implicitly shared class, and shares the data with the document
    it has been created from as long as it is not being modified.

    You can convert the object to and from text based JSON through JsonDocument.

    \sa {JSON Support in Qt}, {JSON Save Game Example}
*/

/*!
    \typedef JsonObject::Iterator

    Qt-style synonym for JsonObject::iterator.
*/

/*!
    \typedef JsonObject::ConstIterator

    Qt-style synonym for JsonObject::const_iterator.
*/

/*!
    \typedef JsonObject::key_type

    Typedef for QString. Provided for STL compatibility.
*/

/*!
    \typedef JsonObject::mapped_type

    Typedef for JsonValue. Provided for STL compatibility.
*/

/*!
    \typedef JsonObject::size_type

    Typedef for int. Provided for STL compatibility.
*/


/*!
    Constructs an empty JSON object.

    \sa isEmpty()
 */
JsonObject::JsonObject()
    : d(nullptr), o(nullptr)
{
}

JsonObject::JsonObject(std::initializer_list<std::pair<std::string, JsonValue> > args)
    : d(nullptr), o(nullptr)
{
    for (auto i = args.begin(); i != args.end(); ++i)
        insert(i->first, i->second);
}

/*!
    \fn JsonObject::JsonObject(std::initializer_list<QPair<QString, JsonValue> > args)
    \since 5.4
    Constructs a JsonObject instance initialized from \a args initialization list.
    For example:
    \code
    JsonObject object
    {
        {"property1", 1},
        {"property2", 2}
    };
    \endcode
*/

/*!
    \internal
 */
JsonObject::JsonObject(Internal::Data *data, Internal::Object *object)
    : d(data), o(object)
{
    // assert(d);
    // assert(o);
    d->ref.ref();
}

/*!
    This method replaces part of the JsonObject(std::initializer_list<QPair<QString, JsonValue>> args) body.
    The constructor needs to be inline, but we do not want to leak implementation details
    of this class.
    \note this method is called for an uninitialized object
    \internal
 */

/*!
    Destroys the object.
 */
JsonObject::~JsonObject()
{
    if (d && !d->ref.deref())
        delete d;
}

/*!
    Creates a copy of \a other.

    Since JsonObject is implicitly shared, the copy is shallow
    as long as the object does not get modified.
 */
JsonObject::JsonObject(const JsonObject &other)
{
    d = other.d;
    o = other.o;
    if (d)
        d->ref.ref();
}

/*!
    Assigns \a other to this object.
 */
JsonObject &JsonObject::operator=(const JsonObject &other)
{
    if (d != other.d) {
        if (d && !d->ref.deref())
            delete d;
        d = other.d;
        if (d)
            d->ref.ref();
    }
    o = other.o;

    return *this;
}

/*!
    Returns a list of all keys in this object.

    The list is sorted lexographically.
 */
JsonObject::Keys JsonObject::keys() const
{
    Keys keys;
    if (!d)
        return keys;

    keys.reserve(o->length);
    for (uint32_t i = 0; i < o->length; ++i) {
        Internal::Entry *e = o->entryAt(i);
        keys.push_back(e->key().data());
    }

    return keys;
}

/*!
    Returns the number of (key, value) pairs stored in the object.
 */
int JsonObject::size() const
{
    if (!d)
        return 0;

    return o->length;
}

/*!
    Returns \c true if the object is empty. This is the same as size() == 0.

    \sa size()
 */
bool JsonObject::isEmpty() const
{
    if (!d)
        return true;

    return !o->length;
}

/*!
    Returns a JsonValue representing the value for the key \a key.

    The returned JsonValue is JsonValue::Undefined if the key does not exist.

    \sa JsonValue, JsonValue::isUndefined()
 */
JsonValue JsonObject::value(const std::string &key) const
{
    if (!d)
        return JsonValue(JsonValue::Undefined);

    bool keyExists;
    int i = o->indexOf(key, &keyExists);
    if (!keyExists)
        return JsonValue(JsonValue::Undefined);
    return JsonValue(d, o, o->entryAt(i)->value);
}

/*!
    Returns a JsonValue representing the value for the key \a key.

    This does the same as value().

    The returned JsonValue is JsonValue::Undefined if the key does not exist.

    \sa value(), JsonValue, JsonValue::isUndefined()
 */
JsonValue JsonObject::operator[](const std::string &key) const
{
    return value(key);
}

/*!
    Returns a reference to the value for \a key.

    The return value is of type JsonValueRef, a helper class for JsonArray
    and JsonObject. When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the element in the JsonArray or JsonObject
    from which you got the reference.

    \sa value()
 */
JsonValueRef JsonObject::operator[](const std::string &key)
{
    // ### somewhat inefficient, as we lookup the key twice if it doesn't yet exist
    bool keyExists = false;
    int index = o ? o->indexOf(key, &keyExists) : -1;
    if (!keyExists) {
        iterator i = insert(key, JsonValue());
        index = i.i;
    }
    return JsonValueRef(this, index);
}

/*!
    Inserts a new item with the key \a key and a value of \a value.

    If there is already an item with the key \a key, then that item's value
    is replaced with \a value.

    Returns an iterator pointing to the inserted item.

    If the value is JsonValue::Undefined, it will cause the key to get removed
    from the object. The returned iterator will then point to end().

    \sa remove(), take(), JsonObject::iterator, end()
 */
JsonObject::iterator JsonObject::insert(const std::string &key, const JsonValue &value)
{
    if (value.t == JsonValue::Undefined) {
        remove(key);
        return end();
    }
    JsonValue val = value;

    bool isIntValue;
    int valueSize = Internal::Value::requiredStorage(val, &isIntValue);

    int valueOffset = sizeof(Internal::Entry) + Internal::qStringSize(key);
    int requiredSize = valueOffset + valueSize;

    detach(requiredSize + sizeof(Internal::offset)); // offset for the new index entry

    if (!o->length)
        o->tableOffset = sizeof(Internal::Object);

    bool keyExists = false;
    int pos = o->indexOf(key, &keyExists);
    if (keyExists)
        ++d->compactionCounter;

    uint32_t off = o->reserveSpace(requiredSize, pos, 1, keyExists);
    if (!off)
        return end();

    Internal::Entry *e = o->entryAt(pos);
    e->value.type = val.t;
    e->value.intValue = isIntValue;
    e->value.value = Internal::Value::valueToStore(val, static_cast<uint32_t>((char *)e - (char *)o)
                                                   + valueOffset);
    Internal::copyString((char *)(e + 1), key);
    if (valueSize)
        Internal::Value::copyData(val, (char *)e + valueOffset, isIntValue);

    if (d->compactionCounter > 32u && d->compactionCounter >= unsigned(o->length) / 2u)
        compact();

    return iterator(this, pos);
}

/*!
    Removes \a key from the object.

    \sa insert(), take()
 */
void JsonObject::remove(const std::string &key)
{
    if (!d)
        return;

    bool keyExists;
    int index = o->indexOf(key, &keyExists);
    if (!keyExists)
        return;

    detach();
    o->removeItems(index, 1);
    ++d->compactionCounter;
    if (d->compactionCounter > 32u && d->compactionCounter >= unsigned(o->length) / 2u)
        compact();
}

/*!
    Removes \a key from the object.

    Returns a JsonValue containing the value referenced by \a key.
    If \a key was not contained in the object, the returned JsonValue
    is JsonValue::Undefined.

    \sa insert(), remove(), JsonValue
 */
JsonValue JsonObject::take(const std::string &key)
{
    if (!o)
        return JsonValue(JsonValue::Undefined);

    bool keyExists;
    int index = o->indexOf(key, &keyExists);
    if (!keyExists)
        return JsonValue(JsonValue::Undefined);

    JsonValue v(d, o, o->entryAt(index)->value);
    detach();
    o->removeItems(index, 1);
    ++d->compactionCounter;
    if (d->compactionCounter > 32u && d->compactionCounter >= unsigned(o->length) / 2u)
        compact();

    return v;
}

/*!
    Returns \c true if the object contains key \a key.

    \sa insert(), remove(), take()
 */
bool JsonObject::contains(const std::string &key) const
{
    if (!o)
        return false;

    bool keyExists;
    o->indexOf(key, &keyExists);
    return keyExists;
}

/*!
    Returns \c true if \a other is equal to this object.
 */
bool JsonObject::operator==(const JsonObject &other) const
{
    if (o == other.o)
        return true;

    if (!o)
        return !other.o->length;
    if (!other.o)
        return !o->length;
    if (o->length != other.o->length)
        return false;

    for (uint32_t i = 0; i < o->length; ++i) {
        Internal::Entry *e = o->entryAt(i);
        JsonValue v(d, o, e->value);
        if (other.value(e->key()) != v)
            return false;
    }

    return true;
}

/*!
    Returns \c true if \a other is not equal to this object.
 */
bool JsonObject::operator!=(const JsonObject &other) const
{
    return !(*this == other);
}

/*!
    Removes the (key, value) pair pointed to by the iterator \a it
    from the map, and returns an iterator to the next item in the
    map.

    \sa remove()
 */
JsonObject::iterator JsonObject::erase(JsonObject::iterator it)
{
    // assert(d && d->ref.load() == 1);
    if (it.o != this || it.i < 0 || it.i >= (int)o->length)
        return iterator(this, o->length);

    int index = it.i;

    o->removeItems(index, 1);
    ++d->compactionCounter;
    if (d->compactionCounter > 32u && d->compactionCounter >= unsigned(o->length) / 2u)
        compact();

    // iterator hasn't changed
    return it;
}

/*!
    Returns an iterator pointing to the item with key \a key in the
    map.

    If the map contains no item with key \a key, the function
    returns end().
 */
JsonObject::iterator JsonObject::find(const std::string &key)
{
    bool keyExists = false;
    int index = o ? o->indexOf(key, &keyExists) : 0;
    if (!keyExists)
        return end();
    detach();
    return iterator(this, index);
}

/*! \fn JsonObject::const_iterator JsonObject::find(const QString &key) const

    \overload
*/

/*!
    Returns a const iterator pointing to the item with key \a key in the
    map.

    If the map contains no item with key \a key, the function
    returns constEnd().
 */
JsonObject::const_iterator JsonObject::constFind(const std::string &key) const
{
    bool keyExists = false;
    int index = o ? o->indexOf(key, &keyExists) : 0;
    if (!keyExists)
        return end();
    return const_iterator(this, index);
}

/*! \fn int JsonObject::count() const

    \overload

    Same as size().
*/

/*! \fn int JsonObject::length() const

    \overload

    Same as size().
*/

/*! \fn JsonObject::iterator JsonObject::begin()

    Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first item in
    the object.

    \sa constBegin(), end()
*/

/*! \fn JsonObject::const_iterator JsonObject::begin() const

    \overload
*/

/*! \fn JsonObject::const_iterator JsonObject::constBegin() const

    Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first item
    in the object.

    \sa begin(), constEnd()
*/

/*! \fn JsonObject::iterator JsonObject::end()

    Returns an \l{STL-style iterators}{STL-style iterator} pointing to the imaginary item
    after the last item in the object.

    \sa begin(), constEnd()
*/

/*! \fn JsonObject::const_iterator JsonObject::end() const

    \overload
*/

/*! \fn JsonObject::const_iterator JsonObject::constEnd() const

    Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
    item after the last item in the object.

    \sa constBegin(), end()
*/

/*!
    \fn bool JsonObject::empty() const

    This function is provided for STL compatibility. It is equivalent
    to isEmpty(), returning \c true if the object is empty; otherwise
    returning \c false.
*/

/*! \class JsonObject::iterator
    \inmodule QtCore
    \ingroup json
    \reentrant
    \since 5.0

    \brief The JsonObject::iterator class provides an STL-style non-const iterator for JsonObject.

    JsonObject::iterator allows you to iterate over a JsonObject
    and to modify the value (but not the key) stored under
    a particular key. If you want to iterate over a const JsonObject, you
    should use JsonObject::const_iterator. It is generally good practice to
    use JsonObject::const_iterator on a non-const JsonObject as well, unless you
    need to change the JsonObject through the iterator. Const iterators are
    slightly faster, and improve code readability.

    The default JsonObject::iterator constructor creates an uninitialized
    iterator. You must initialize it using a JsonObject function like
    JsonObject::begin(), JsonObject::end(), or JsonObject::find() before you can
    start iterating.

    Multiple iterators can be used on the same object. Existing iterators will however
    become dangling once the object gets modified.

    \sa JsonObject::const_iterator, {JSON Support in Qt}, {JSON Save Game Example}
*/

/*! \typedef JsonObject::iterator::difference_type

    \internal
*/

/*! \typedef JsonObject::iterator::iterator_category

    A synonym for \e {std::bidirectional_iterator_tag} indicating
    this iterator is a bidirectional iterator.
*/

/*! \typedef JsonObject::iterator::reference

    \internal
*/

/*! \typedef JsonObject::iterator::value_type

    \internal
*/

/*! \fn JsonObject::iterator::iterator()

    Constructs an uninitialized iterator.

    Functions like key(), value(), and operator++() must not be
    called on an uninitialized iterator. Use operator=() to assign a
    value to it before using it.

    \sa JsonObject::begin(), JsonObject::end()
*/

/*! \fn JsonObject::iterator::iterator(JsonObject *obj, int index)
    \internal
*/

/*! \fn QString JsonObject::iterator::key() const

    Returns the current item's key.

    There is no direct way of changing an item's key through an
    iterator, although it can be done by calling JsonObject::erase()
    followed by JsonObject::insert().

    \sa value()
*/

/*! \fn JsonValueRef JsonObject::iterator::value() const

    Returns a modifiable reference to the current item's value.

    You can change the value of an item by using value() on
    the left side of an assignment.

    The return value is of type JsonValueRef, a helper class for JsonArray
    and JsonObject. When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the element in the JsonArray or JsonObject
    from which you got the reference.

    \sa key(), operator*()
*/

/*! \fn JsonValueRef JsonObject::iterator::operator*() const

    Returns a modifiable reference to the current item's value.

    Same as value().

    The return value is of type JsonValueRef, a helper class for JsonArray
    and JsonObject. When you get an object of type JsonValueRef, you can
    use it as if it were a reference to a JsonValue. If you assign to it,
    the assignment will apply to the element in the JsonArray or JsonObject
    from which you got the reference.

    \sa key()
*/

/*! \fn JsonValueRef *JsonObject::iterator::operator->() const

    Returns a pointer to a modifiable reference to the current item.
*/

/*!
    \fn bool JsonObject::iterator::operator==(const iterator &other) const
    \fn bool JsonObject::iterator::operator==(const const_iterator &other) const

    Returns \c true if \a other points to the same item as this
    iterator; otherwise returns \c false.

    \sa operator!=()
*/

/*!
    \fn bool JsonObject::iterator::operator!=(const iterator &other) const
    \fn bool JsonObject::iterator::operator!=(const const_iterator &other) const

    Returns \c true if \a other points to a different item than this
    iterator; otherwise returns \c false.

    \sa operator==()
*/

/*! \fn JsonObject::iterator JsonObject::iterator::operator++()

    The prefix ++ operator, \c{++i}, advances the iterator to the
    next item in the object and returns an iterator to the new current
    item.

    Calling this function on JsonObject::end() leads to undefined results.

    \sa operator--()
*/

/*! \fn JsonObject::iterator JsonObject::iterator::operator++(int)

    \overload

    The postfix ++ operator, \c{i++}, advances the iterator to the
    next item in the object and returns an iterator to the previously
    current item.
*/

/*! \fn JsonObject::iterator JsonObject::iterator::operator--()

    The prefix -- operator, \c{--i}, makes the preceding item
    current and returns an iterator pointing to the new current item.

    Calling this function on JsonObject::begin() leads to undefined
    results.

    \sa operator++()
*/

/*! \fn JsonObject::iterator JsonObject::iterator::operator--(int)

    \overload

    The postfix -- operator, \c{i--}, makes the preceding item
    current and returns an iterator pointing to the previously
    current item.
*/

/*! \fn JsonObject::iterator JsonObject::iterator::operator+(int j) const

    Returns an iterator to the item at \a j positions forward from
    this iterator. If \a j is negative, the iterator goes backward.

    \sa operator-()

*/

/*! \fn JsonObject::iterator JsonObject::iterator::operator-(int j) const

    Returns an iterator to the item at \a j positions backward from
    this iterator. If \a j is negative, the iterator goes forward.

    \sa operator+()
*/

/*! \fn JsonObject::iterator &JsonObject::iterator::operator+=(int j)

    Advances the iterator by \a j items. If \a j is negative, the
    iterator goes backward.

    \sa operator-=(), operator+()
*/

/*! \fn JsonObject::iterator &JsonObject::iterator::operator-=(int j)

    Makes the iterator go back by \a j items. If \a j is negative,
    the iterator goes forward.

    \sa operator+=(), operator-()
*/

/*!
    \class JsonObject::const_iterator
    \inmodule QtCore
    \ingroup json
    \since 5.0
    \brief The JsonObject::const_iterator class provides an STL-style const iterator for JsonObject.

    JsonObject::const_iterator allows you to iterate over a JsonObject.
    If you want to modify the JsonObject as you iterate
    over it, you must use JsonObject::iterator instead. It is generally
    good practice to use JsonObject::const_iterator on a non-const JsonObject as
    well, unless you need to change the JsonObject through the iterator.
    Const iterators are slightly faster and improve code
    readability.

    The default JsonObject::const_iterator constructor creates an
    uninitialized iterator. You must initialize it using a JsonObject
    function like JsonObject::constBegin(), JsonObject::constEnd(), or
    JsonObject::find() before you can start iterating.

    Multiple iterators can be used on the same object. Existing iterators
    will however become dangling if the object gets modified.

    \sa JsonObject::iterator, {JSON Support in Qt}, {JSON Save Game Example}
*/

/*! \typedef JsonObject::const_iterator::difference_type

    \internal
*/

/*! \typedef JsonObject::const_iterator::iterator_category

    A synonym for \e {std::bidirectional_iterator_tag} indicating
    this iterator is a bidirectional iterator.
*/

/*! \typedef JsonObject::const_iterator::reference

    \internal
*/

/*! \typedef JsonObject::const_iterator::value_type

    \internal
*/

/*! \fn JsonObject::const_iterator::const_iterator()

    Constructs an uninitialized iterator.

    Functions like key(), value(), and operator++() must not be
    called on an uninitialized iterator. Use operator=() to assign a
    value to it before using it.

    \sa JsonObject::constBegin(), JsonObject::constEnd()
*/

/*! \fn JsonObject::const_iterator::const_iterator(const JsonObject *obj, int index)
    \internal
*/

/*! \fn JsonObject::const_iterator::const_iterator(const iterator &other)

    Constructs a copy of \a other.
*/

/*! \fn QString JsonObject::const_iterator::key() const

    Returns the current item's key.

    \sa value()
*/

/*! \fn JsonValue JsonObject::const_iterator::value() const

    Returns the current item's value.

    \sa key(), operator*()
*/

/*! \fn JsonValue JsonObject::const_iterator::operator*() const

    Returns the current item's value.

    Same as value().

    \sa key()
*/

/*! \fn JsonValue *JsonObject::const_iterator::operator->() const

    Returns a pointer to the current item.
*/

/*! \fn bool JsonObject::const_iterator::operator==(const const_iterator &other) const
    \fn bool JsonObject::const_iterator::operator==(const iterator &other) const

    Returns \c true if \a other points to the same item as this
    iterator; otherwise returns \c false.

    \sa operator!=()
*/

/*! \fn bool JsonObject::const_iterator::operator!=(const const_iterator &other) const
    \fn bool JsonObject::const_iterator::operator!=(const iterator &other) const

    Returns \c true if \a other points to a different item than this
    iterator; otherwise returns \c false.

    \sa operator==()
*/

/*! \fn JsonObject::const_iterator JsonObject::const_iterator::operator++()

    The prefix ++ operator, \c{++i}, advances the iterator to the
    next item in the object and returns an iterator to the new current
    item.

    Calling this function on JsonObject::end() leads to undefined results.

    \sa operator--()
*/

/*! \fn JsonObject::const_iterator JsonObject::const_iterator::operator++(int)

    \overload

    The postfix ++ operator, \c{i++}, advances the iterator to the
    next item in the object and returns an iterator to the previously
    current item.
*/

/*! \fn JsonObject::const_iterator &JsonObject::const_iterator::operator--()

    The prefix -- operator, \c{--i}, makes the preceding item
    current and returns an iterator pointing to the new current item.

    Calling this function on JsonObject::begin() leads to undefined
    results.

    \sa operator++()
*/

/*! \fn JsonObject::const_iterator JsonObject::const_iterator::operator--(int)

    \overload

    The postfix -- operator, \c{i--}, makes the preceding item
    current and returns an iterator pointing to the previously
    current item.
*/

/*! \fn JsonObject::const_iterator JsonObject::const_iterator::operator+(int j) const

    Returns an iterator to the item at \a j positions forward from
    this iterator. If \a j is negative, the iterator goes backward.

    This operation can be slow for large \a j values.

    \sa operator-()
*/

/*! \fn JsonObject::const_iterator JsonObject::const_iterator::operator-(int j) const

    Returns an iterator to the item at \a j positions backward from
    this iterator. If \a j is negative, the iterator goes forward.

    This operation can be slow for large \a j values.

    \sa operator+()
*/

/*! \fn JsonObject::const_iterator &JsonObject::const_iterator::operator+=(int j)

    Advances the iterator by \a j items. If \a j is negative, the
    iterator goes backward.

    This operation can be slow for large \a j values.

    \sa operator-=(), operator+()
*/

/*! \fn JsonObject::const_iterator &JsonObject::const_iterator::operator-=(int j)

    Makes the iterator go back by \a j items. If \a j is negative,
    the iterator goes forward.

    This operation can be slow for large \a j values.

    \sa operator+=(), operator-()
*/


/*!
    \internal
 */
void JsonObject::detach(uint32_t reserve)
{
    if (!d) {
        d = new Internal::Data(reserve, JsonValue::Object);
        o = static_cast<Internal::Object *>(d->header->root());
        d->ref.ref();
        return;
    }
    if (reserve == 0 && d->ref.load() == 1)
        return;

    Internal::Data *x = d->clone(o, reserve);
    x->ref.ref();
    if (!d->ref.deref())
        delete d;
    d = x;
    o = static_cast<Internal::Object *>(d->header->root());
}

/*!
    \internal
 */
void JsonObject::compact()
{
    if (!d || !d->compactionCounter)
        return;

    detach();
    d->compact();
    o = static_cast<Internal::Object *>(d->header->root());
}

/*!
    \internal
 */
std::string JsonObject::keyAt(int i) const
{
    // assert(o && i >= 0 && i < (int)o->length);

    Internal::Entry *e = o->entryAt(i);
    return e->key();
}

/*!
    \internal
 */
JsonValue JsonObject::valueAt(int i) const
{
    if (!o || i < 0 || i >= (int)o->length)
        return JsonValue(JsonValue::Undefined);

    Internal::Entry *e = o->entryAt(i);
    return JsonValue(d, o, e->value);
}

/*!
    \internal
 */
void JsonObject::setValueAt(int i, const JsonValue &val)
{
    // assert(o && i >= 0 && i < (int)o->length);

    Internal::Entry *e = o->entryAt(i);
    insert(e->key(), val);
}


/*! \class JsonDocument
    \inmodule QtCore
    \ingroup json
    \ingroup shared
    \reentrant
    \since 5.0

    \brief The JsonDocument class provides a way to read and write JSON documents.

    JsonDocument is a class that wraps a complete JSON document and can read and
    write this document both from a UTF-8 encoded text based representation as well
    as Qt's own binary format.

    A JSON document can be converted from its text-based representation to a JsonDocument
    using JsonDocument::fromJson(). toJson() converts it back to text. The parser is very
    fast and efficient and converts the JSON to the binary representation used by Qt.

    Validity of the parsed document can be queried with !isNull()

    A document can be queried as to whether it contains an array or an object using isArray()
    and isObject(). The array or object contained in the document can be retrieved using
    array() or object() and then read or manipulated.

    A document can also be created from a stored binary representation using fromBinaryData() or
    fromRawData().

    \sa {JSON Support in Qt}, {JSON Save Game Example}
*/

/*!
 * Constructs an empty and invalid document.
 */
JsonDocument::JsonDocument()
    : d(nullptr)
{
}

/*!
 * Creates a JsonDocument from \a object.
 */
JsonDocument::JsonDocument(const JsonObject &object)
    : d(nullptr)
{
    setObject(object);
}

/*!
 * Constructs a JsonDocument from \a array.
 */
JsonDocument::JsonDocument(const JsonArray &array)
    : d(nullptr)
{
    setArray(array);
}

/*!
    \internal
 */
JsonDocument::JsonDocument(Internal::Data *data)
    : d(data)
{
    // assert(d);
    d->ref.ref();
}

/*!
 Deletes the document.

 Binary data set with fromRawData is not freed.
 */
JsonDocument::~JsonDocument()
{
    if (d && !d->ref.deref())
        delete d;
}

/*!
 * Creates a copy of the \a other document.
 */
JsonDocument::JsonDocument(const JsonDocument &other)
{
    d = other.d;
    if (d)
        d->ref.ref();
}

/*!
 * Assigns the \a other document to this JsonDocument.
 * Returns a reference to this object.
 */
JsonDocument &JsonDocument::operator=(const JsonDocument &other)
{
    if (d != other.d) {
        if (d && !d->ref.deref())
            delete d;
        d = other.d;
        if (d)
            d->ref.ref();
    }

    return *this;
}

/*! \enum JsonDocument::DataValidation

  This value is used to tell JsonDocument whether to validate the binary data
  when converting to a JsonDocument using fromBinaryData() or fromRawData().

  \value Validate Validate the data before using it. This is the default.
  \value BypassValidation Bypasses data validation. Only use if you received the
  data from a trusted place and know it's valid, as using of invalid data can crash
  the application.
  */

/*!
 Creates a JsonDocument that uses the first \a size bytes from
 \a data. It assumes \a data contains a binary encoded JSON document.
 The created document does not take ownership of \a data and the caller
 has to guarantee that \a data will not be deleted or modified as long as
 any JsonDocument, JsonObject or JsonArray still references the data.

 \a data has to be aligned to a 4 byte boundary.

 \a validation decides whether the data is checked for validity before being used.
 By default the data is validated. If the \a data is not valid, the method returns
 a null document.

 Returns a JsonDocument representing the data.

 \sa rawData(), fromBinaryData(), isNull(), DataValidation
 */
JsonDocument JsonDocument::fromRawData(const char *data, int size, DataValidation validation)
{
    if (std::uintptr_t(data) & 3) {
        std::cerr <<"JsonDocument::fromRawData: data has to have 4 byte alignment\n";
        return JsonDocument();
    }

    const auto d = new Internal::Data((char *)data, size);
    d->ownsData = false;

    if (validation != BypassValidation && !d->valid()) {
        delete d;
        return JsonDocument();
    }

    return JsonDocument(d);
}

/*!
  Returns the raw binary representation of the data
  \a size will contain the size of the returned data.

  This method is useful to e.g. stream the JSON document
  in it's binary form to a file.
 */
const char *JsonDocument::rawData(int *size) const
{
    if (!d) {
        *size = 0;
        return nullptr;
    }
    *size = d->alloc;
    return d->rawData;
}

/*!
 Creates a JsonDocument from \a data.

 \a validation decides whether the data is checked for validity before being used.
 By default the data is validated. If the \a data is not valid, the method returns
 a null document.

 \sa toBinaryData(), fromRawData(), isNull(), DataValidation
 */
JsonDocument JsonDocument::fromBinaryData(const std::string &data, DataValidation validation)
{
    if (data.size() < (int)(sizeof(Internal::Header) + sizeof(Internal::Base)))
        return JsonDocument();

    Internal::Header h;
    memcpy(&h, data.data(), sizeof(Internal::Header));
    Internal::Base root;
    memcpy(&root, data.data() + sizeof(Internal::Header), sizeof(Internal::Base));

    // do basic checks here, so we don't try to allocate more memory than we can.
    if (h.tag != JsonDocument::BinaryFormatTag || h.version != 1u ||
        sizeof(Internal::Header) + root.size > (uint32_t)data.size())
        return JsonDocument();

    const uint32_t size = sizeof(Internal::Header) + root.size;
    char *raw = (char *)malloc(size);
    if (!raw)
        return JsonDocument();

    memcpy(raw, data.data(), size);
    const auto d = new Internal::Data(raw, size);

    if (validation != BypassValidation && !d->valid()) {
        delete d;
        return JsonDocument();
    }

    return JsonDocument(d);
}

/*!
    \enum JsonDocument::JsonFormat

    This value defines the format of the JSON byte array produced
    when converting to a JsonDocument using toJson().

    \value Indented Defines human readable output as follows:
        \code
        {
            "Array": [
                true,
                999,
                "string"
            ],
            "Key": "Value",
            "null": null
        }
        \endcode

    \value Compact Defines a compact output as follows:
        \code
        {"Array":[true,999,"string"],"Key":"Value","null":null}
        \endcode
  */

/*!
    Converts the JsonDocument to a UTF-8 encoded JSON document in the provided \a format.

    \sa fromJson(), JsonFormat
 */
#ifndef QT_JSON_READONLY
std::string JsonDocument::toJson(JsonFormat format) const
{
    std::string json;

    if (!d)
        return json;

    if (d->header->root()->isArray())
        Internal::arrayToJson(static_cast<Internal::Array *>(d->header->root()), json, 0, (format == Compact));
    else
        Internal::objectToJson(static_cast<Internal::Object *>(d->header->root()), json, 0, (format == Compact));

    return json;
}
#endif

/*!
 Parses a UTF-8 encoded JSON document and creates a JsonDocument
 from it.

 \a json contains the json document to be parsed.

 The optional \a error variable can be used to pass in a JsonParseError data
 structure that will contain information about possible errors encountered during
 parsing.

 \sa toJson(), JsonParseError
 */
JsonDocument JsonDocument::fromJson(const std::string &json, JsonParseError *error)
{
    Internal::Parser parser(json.data(), static_cast<int>(json.length()));
    return parser.parse(error);
}

/*!
    Returns \c true if the document doesn't contain any data.
 */
bool JsonDocument::isEmpty() const
{
    if (!d)
        return true;

    return false;
}

/*!
 Returns a binary representation of the document.

 The binary representation is also the native format used internally in Qt,
 and is very efficient and fast to convert to and from.

 The binary format can be stored on disk and interchanged with other applications
 or computers. fromBinaryData() can be used to convert it back into a
 JSON document.

 \sa fromBinaryData()
 */
std::string JsonDocument::toBinaryData() const
{
    if (!d || !d->rawData)
        return std::string();

    return std::string(d->rawData, d->header->root()->size + sizeof(Internal::Header));
}

/*!
    Returns \c true if the document contains an array.

    \sa array(), isObject()
 */
bool JsonDocument::isArray() const
{
    if (!d)
        return false;

    Internal::Header *h = (Internal::Header *)d->rawData;
    return h->root()->isArray();
}

/*!
    Returns \c true if the document contains an object.

    \sa object(), isArray()
 */
bool JsonDocument::isObject() const
{
    if (!d)
        return false;

    Internal::Header *h = (Internal::Header *)d->rawData;
    return h->root()->isObject();
}

/*!
    Returns the JsonObject contained in the document.

    Returns an empty object if the document contains an
    array.

    \sa isObject(), array(), setObject()
 */
JsonObject JsonDocument::object() const
{
    if (d) {
        Internal::Base *b = d->header->root();
        if (b->isObject())
            return JsonObject(d, static_cast<Internal::Object *>(b));
    }
    return JsonObject();
}

/*!
    Returns the JsonArray contained in the document.

    Returns an empty array if the document contains an
    object.

    \sa isArray(), object(), setArray()
 */
JsonArray JsonDocument::array() const
{
    if (d) {
        Internal::Base *b = d->header->root();
        if (b->isArray())
            return JsonArray(d, static_cast<Internal::Array *>(b));
    }
    return JsonArray();
}

/*!
    Sets \a object as the main object of this document.

    \sa setArray(), object()
 */
void JsonDocument::setObject(const JsonObject &object)
{
    if (d && !d->ref.deref())
        delete d;

    d = object.d;

    if (!d) {
        d = new Internal::Data(0, JsonValue::Object);
    } else if (d->compactionCounter || object.o != d->header->root()) {
        JsonObject o(object);
        if (d->compactionCounter)
            o.compact();
        else
            o.detach();
        d = o.d;
        d->ref.ref();
        return;
    }
    d->ref.ref();
}

/*!
    Sets \a array as the main object of this document.

    \sa setObject(), array()
 */
void JsonDocument::setArray(const JsonArray &array)
{
    if (d && !d->ref.deref())
        delete d;

    d = array.d;

    if (!d) {
        d = new Internal::Data(0, JsonValue::Array);
    } else if (d->compactionCounter || array.a != d->header->root()) {
        JsonArray a(array);
        if (d->compactionCounter)
            a.compact();
        else
            a.detach();
        d = a.d;
        d->ref.ref();
        return;
    }
    d->ref.ref();
}

/*!
    Returns \c true if the \a other document is equal to this document.
 */
bool JsonDocument::operator==(const JsonDocument &other) const
{
    if (d == other.d)
        return true;

    if (!d || !other.d)
        return false;

    if (d->header->root()->isArray() != other.d->header->root()->isArray())
        return false;

    if (d->header->root()->isObject())
        return JsonObject(d, static_cast<Internal::Object *>(d->header->root()))
                == JsonObject(other.d, static_cast<Internal::Object *>(other.d->header->root()));
    else
        return JsonArray(d, static_cast<Internal::Array *>(d->header->root()))
                == JsonArray(other.d, static_cast<Internal::Array *>(other.d->header->root()));
}

/*!
 \fn bool JsonDocument::operator!=(const JsonDocument &other) const

    returns \c true if \a other is not equal to this document
 */

/*!
    returns \c true if this document is null.

    Null documents are documents created through the default constructor.

    Documents created from UTF-8 encoded text or the binary format are
    validated during parsing. If validation fails, the returned document
    will also be null.
 */
bool JsonDocument::isNull() const
{
    return (d == 0);
}


static void objectContentToJson(const Object *o, std::string &json, int indent, bool compact);
static void arrayContentToJson(const Array *a, std::string &json, int indent, bool compact);

static uint8_t hexdig(uint32_t u)
{
    return (u < 0xa ? '0' + u : 'a' + u - 0xa);
}

static std::string escapedString(const std::string &in)
{
    std::string ba;
    ba.reserve(in.length());

    auto src = in.begin();
    auto end = in.end();

    while (src != end) {
        uint8_t u = (*src++);
        if (u < 0x20 || u == 0x22 || u == 0x5c) {
            ba.push_back('\\');
            switch (u) {
            case 0x22:
                ba.push_back('"');
                break;
            case 0x5c:
                ba.push_back('\\');
                break;
            case 0x8:
                ba.push_back('b');
                break;
            case 0xc:
                ba.push_back('f');
                break;
            case 0xa:
                ba.push_back('n');
                break;
            case 0xd:
                ba.push_back('r');
                break;
            case 0x9:
                ba.push_back('t');
                break;
            default:
                ba.push_back('u');
                ba.push_back('0');
                ba.push_back('0');
                ba.push_back(hexdig(u>>4));
                ba.push_back(hexdig(u & 0xf));
           }
        } else {
            ba.push_back(u);
        }
    }

    return ba;
}

static void valueToJson(const Base *b, const Value &v, std::string &json, int indent, bool compact)
{
    JsonValue::Type type = (JsonValue::Type)(uint32_t)v.type;
    switch (type) {
    case JsonValue::Bool:
        json += v.toBoolean() ? "true" : "false";
        break;
    case JsonValue::Double: {
        const double d = v.toDouble(b);
        if (std::isfinite(d)) {
            // +2 to format to ensure the expected precision
            const int n = std::numeric_limits<double>::digits10 + 2;
            char buf[30] = {0};
            sprintf(buf, "%.*g", n, d);
            // Hack:
            if (buf[0] == '-' && buf[1] == '0' && buf[2] == '\0')
                json += "0";
            else
                json += buf;
        } else {
            json += "null"; // +INF || -INF || NaN (see RFC4627#section2.4)
        }
        break;
    }
    case JsonValue::String:
        json += '"';
        json += escapedString(v.toString(b));
        json += '"';
        break;
    case JsonValue::Array:
        json += compact ? "[" : "[\n";
        arrayContentToJson(static_cast<Array *>(v.base(b)), json, indent + (compact ? 0 : 1), compact);
        json += std::string(4*indent, ' ');
        json += ']';
        break;
    case JsonValue::Object:
        json += compact ? "{" : "{\n";
        objectContentToJson(static_cast<Object *>(v.base(b)), json, indent + (compact ? 0 : 1), compact);
        json += std::string(4*indent, ' ');
        json += '}';
        break;
    case JsonValue::Null:
    default:
        json += "null";
    }
}

static void arrayContentToJson(const Array *a, std::string &json, int indent, bool compact)
{
    if (!a || !a->length)
        return;

    std::string indentString(4*indent, ' ');

    uint32_t i = 0;
    while (1) {
        json += indentString;
        valueToJson(a, a->at(i), json, indent, compact);

        if (++i == a->length) {
            if (!compact)
                json += '\n';
            break;
        }

        json += compact ? "," : ",\n";
    }
}

static void objectContentToJson(const Object *o, std::string &json, int indent, bool compact)
{
    if (!o || !o->length)
        return;

    std::string indentString(4*indent, ' ');

    uint32_t i = 0;
    while (1) {
        Entry *e = o->entryAt(i);
        json += indentString;
        json += '"';
        json += escapedString(e->key());
        json += compact ? "\":" : "\": ";
        valueToJson(o, e->value, json, indent, compact);

        if (++i == o->length) {
            if (!compact)
                json += '\n';
            break;
        }

        json += compact ? "," : ",\n";
    }
}

namespace Internal {

void objectToJson(const Object *o, std::string &json, int indent, bool compact)
{
    json.reserve(json.size() + (o ? (int)o->size : 16));
    json += compact ? "{" : "{\n";
    objectContentToJson(o, json, indent + (compact ? 0 : 1), compact);
    json += std::string(4*indent, ' ');
    json += compact ? "}" : "}\n";
}

void arrayToJson(const Array *a, std::string &json, int indent, bool compact)
{
    json.reserve(json.size() + (a ? (int)a->size : 16));
    json += compact ? "[" : "[\n";
    arrayContentToJson(a, json, indent + (compact ? 0 : 1), compact);
    json += std::string(4*indent, ' ');
    json += compact ? "]" : "]\n";
}

}



/*!
    \class JsonParseError
    \inmodule QtCore
    \ingroup json
    \ingroup shared
    \reentrant
    \since 5.0

    \brief The JsonParseError class is used to report errors during JSON parsing.

    \sa {JSON Support in Qt}, {JSON Save Game Example}
*/

/*!
    \enum JsonParseError::ParseError

    This enum describes the type of error that occurred during the parsing of a JSON document.

    \value NoError                  No error occurred
    \value UnterminatedObject       An object is not correctly terminated with a closing curly bracket
    \value MissingNameSeparator     A comma separating different items is missing
    \value UnterminatedArray        The array is not correctly terminated with a closing square bracket
    \value MissingValueSeparator    A colon separating keys from values inside objects is missing
    \value IllegalValue             The value is illegal
    \value TerminationByNumber      The input stream ended while parsing a number
    \value IllegalNumber            The number is not well formed
    \value IllegalEscapeSequence    An illegal escape sequence occurred in the input
    \value IllegalUTF8String        An illegal UTF8 sequence occurred in the input
    \value UnterminatedString       A string wasn't terminated with a quote
    \value MissingObject            An object was expected but couldn't be found
    \value DeepNesting              The JSON document is too deeply nested for the parser to parse it
    \value DocumentTooLarge         The JSON document is too large for the parser to parse it
    \value GarbageAtEnd             The parsed document contains additional garbage characters at the end

*/

/*!
    \variable JsonParseError::error

    Contains the type of the parse error. Is equal to JsonParseError::NoError if the document
    was parsed correctly.

    \sa ParseError, errorString()
*/


/*!
    \variable JsonParseError::offset

    Contains the offset in the input string where the parse error occurred.

    \sa error, errorString()
*/

using namespace Internal;

Parser::Parser(const char *json, int length)
    : head(json), json(json), data(nullptr), dataLength(0), current(0), nestingLevel(0), lastError(JsonParseError::NoError)
{
    end = json + length;
}



/*

begin-array     = ws %x5B ws  ; [ left square bracket

begin-object    = ws %x7B ws  ; { left curly bracket

end-array       = ws %x5D ws  ; ] right square bracket

end-object      = ws %x7D ws  ; } right curly bracket

name-separator  = ws %x3A ws  ; : colon

value-separator = ws %x2C ws  ; , comma

Insignificant whitespace is allowed before or after any of the six
structural characters.

ws = *(
          %x20 /              ; Space
          %x09 /              ; Horizontal tab
          %x0A /              ; Line feed or New line
          %x0D                ; Carriage return
      )

*/

enum {
    Space = 0x20,
    Tab = 0x09,
    LineFeed = 0x0a,
    Return = 0x0d,
    BeginArray = 0x5b,
    BeginObject = 0x7b,
    EndArray = 0x5d,
    EndObject = 0x7d,
    NameSeparator = 0x3a,
    ValueSeparator = 0x2c,
    Quote = 0x22
};

void Parser::eatBOM()
{
    // eat UTF-8 byte order mark
    if (end - json > 3
            && (unsigned char)json[0] == 0xef
            && (unsigned char)json[1] == 0xbb
            && (unsigned char)json[2] == 0xbf)
        json += 3;
}

bool Parser::eatSpace()
{
    while (json < end) {
        if (*json > Space)
            break;
        if (*json != Space &&
            *json != Tab &&
            *json != LineFeed &&
            *json != Return)
            break;
        ++json;
    }
    return (json < end);
}

char Parser::nextToken()
{
    if (!eatSpace())
        return 0;
    char token = *json++;
    switch (token) {
    case BeginArray:
    case BeginObject:
    case NameSeparator:
    case ValueSeparator:
    case EndArray:
    case EndObject:
        eatSpace();
    case Quote:
        break;
    default:
        token = 0;
        break;
    }
    return token;
}

/*
    JSON-text = object / array
*/
JsonDocument Parser::parse(JsonParseError *error)
{
#ifdef PARSER_DEBUG
    indent = 0;
    std::cerr << ">>>>> parser begin";
#endif
    // allocate some space
    dataLength = static_cast<int>(std::max(end - json, std::ptrdiff_t(256)));
    data = (char *)malloc(dataLength);

    // fill in Header data
    Header *h = (Header *)data;
    h->tag = JsonDocument::BinaryFormatTag;
    h->version = 1u;

    current = sizeof(Header);

    eatBOM();
    char token = nextToken();

    DEBUG << std::hex << (uint32_t)token;
    if (token == BeginArray) {
        if (!parseArray())
            goto error;
    } else if (token == BeginObject) {
        if (!parseObject())
            goto error;
    } else {
        lastError = JsonParseError::IllegalValue;
        goto error;
    }

    eatSpace();
    if (json < end) {
        lastError = JsonParseError::GarbageAtEnd;
        goto error;
    }

    END;
    {
        if (error) {
            error->offset = 0;
            error->error = JsonParseError::NoError;
        }
        const auto d = new Data(data, current);
        return JsonDocument(d);
    }

error:
#ifdef PARSER_DEBUG
    std::cerr << ">>>>> parser error";
#endif
    if (error) {
        error->offset = static_cast<int>(json - head);
        error->error  = lastError;
    }
    free(data);
    return JsonDocument();
}


void Parser::ParsedObject::insert(uint32_t offset)
{
    const Entry *newEntry = reinterpret_cast<const Entry *>(parser->data + objectPosition + offset);
    size_t min = 0;
    size_t n = offsets.size();
    while (n > 0) {
        size_t half = n >> 1;
        size_t middle = min + half;
        if (*entryAt(middle) >= *newEntry) {
            n = half;
        } else {
            min = middle + 1;
            n -= half + 1;
        }
    }
    if (min < offsets.size() && *entryAt(min) == *newEntry) {
        offsets[min] = offset;
    } else {
        offsets.insert(offsets.begin() + min, offset);
    }
}

/*
    object = begin-object [ member *( value-separator member ) ]
    end-object
*/

bool Parser::parseObject()
{
    if (++nestingLevel > nestingLimit) {
        lastError = JsonParseError::DeepNesting;
        return false;
    }

    int objectOffset = reserveSpace(sizeof(Object));
    BEGIN << "parseObject pos=" << objectOffset << current << json;

    ParsedObject parsedObject(this, objectOffset);

    char token = nextToken();
    while (token == Quote) {
        int off = current - objectOffset;
        if (!parseMember(objectOffset))
            return false;
        parsedObject.insert(off);
        token = nextToken();
        if (token != ValueSeparator)
            break;
        token = nextToken();
        if (token == EndObject) {
            lastError = JsonParseError::MissingObject;
            return false;
        }
    }

    DEBUG << "end token=" << token;
    if (token != EndObject) {
        lastError = JsonParseError::UnterminatedObject;
        return false;
    }

    DEBUG << "numEntries" << parsedObject.offsets.size();
    int table = objectOffset;
    // finalize the object
    if (parsedObject.offsets.size()) {
        int tableSize = static_cast<int>(parsedObject.offsets.size()) * sizeof(uint32_t);
        table = reserveSpace(tableSize);
        memcpy(data + table, &*parsedObject.offsets.begin(), tableSize);
    }

    Object *o = (Object *)(data + objectOffset);
    o->tableOffset = table - objectOffset;
    o->size = current - objectOffset;
    o->is_object = true;
    o->length = static_cast<int>(parsedObject.offsets.size());

    DEBUG << "current=" << current;
    END;

    --nestingLevel;
    return true;
}

/*
    member = string name-separator value
*/
bool Parser::parseMember(int baseOffset)
{
    int entryOffset = reserveSpace(sizeof(Entry));
    BEGIN << "parseMember pos=" << entryOffset;

    if (!parseString())
        return false;
    char token = nextToken();
    if (token != NameSeparator) {
        lastError = JsonParseError::MissingNameSeparator;
        return false;
    }
    Value val;
    if (!parseValue(&val, baseOffset))
        return false;

    // finalize the entry
    Entry *e = (Entry *)(data + entryOffset);
    e->value = val;

    END;
    return true;
}

/*
    array = begin-array [ value *( value-separator value ) ] end-array
*/
bool Parser::parseArray()
{
    BEGIN << "parseArray";

    if (++nestingLevel > nestingLimit) {
        lastError = JsonParseError::DeepNesting;
        return false;
    }

    int arrayOffset = reserveSpace(sizeof(Array));

    std::vector<Value> values;
    values.reserve(64);

    if (!eatSpace()) {
        lastError = JsonParseError::UnterminatedArray;
        return false;
    }
    if (*json == EndArray) {
        nextToken();
    } else {
        while (1) {
            Value val;
            if (!parseValue(&val, arrayOffset))
                return false;
            values.push_back(val);
            char token = nextToken();
            if (token == EndArray)
                break;
            else if (token != ValueSeparator) {
                if (!eatSpace())
                    lastError = JsonParseError::UnterminatedArray;
                else
                    lastError = JsonParseError::MissingValueSeparator;
                return false;
            }
        }
    }

    DEBUG << "size =" << values.size();
    int table = arrayOffset;
    // finalize the object
    if (values.size()) {
        int tableSize = static_cast<int>(values.size() * sizeof(Value));
        table = reserveSpace(tableSize);
        memcpy(data + table, values.data(), tableSize);
    }

    Array *a = (Array *)(data + arrayOffset);
    a->tableOffset = table - arrayOffset;
    a->size = current - arrayOffset;
    a->is_object = false;
    a->length = static_cast<int>(values.size());

    DEBUG << "current=" << current;
    END;

    --nestingLevel;
    return true;
}

/*
value = false / null / true / object / array / number / string

*/

bool Parser::parseValue(Value *val, int baseOffset)
{
    BEGIN << "parse Value" << json;
    val->_dummy = 0;

    switch (*json++) {
    case 'n':
        if (end - json < 4) {
            lastError = JsonParseError::IllegalValue;
            return false;
        }
        if (*json++ == 'u' &&
            *json++ == 'l' &&
            *json++ == 'l') {
            val->type = JsonValue::Null;
            DEBUG << "value: null";
            END;
            return true;
        }
        lastError = JsonParseError::IllegalValue;
        return false;
    case 't':
        if (end - json < 4) {
            lastError = JsonParseError::IllegalValue;
            return false;
        }
        if (*json++ == 'r' &&
            *json++ == 'u' &&
            *json++ == 'e') {
            val->type = JsonValue::Bool;
            val->value = true;
            DEBUG << "value: true";
            END;
            return true;
        }
        lastError = JsonParseError::IllegalValue;
        return false;
    case 'f':
        if (end - json < 5) {
            lastError = JsonParseError::IllegalValue;
            return false;
        }
        if (*json++ == 'a' &&
            *json++ == 'l' &&
            *json++ == 's' &&
            *json++ == 'e') {
            val->type = JsonValue::Bool;
            val->value = false;
            DEBUG << "value: false";
            END;
            return true;
        }
        lastError = JsonParseError::IllegalValue;
        return false;
    case Quote: {
        val->type = JsonValue::String;
        if (current - baseOffset >= Value::MaxSize) {
            lastError = JsonParseError::DocumentTooLarge;
            return false;
        }
        val->value = current - baseOffset;
        if (!parseString())
            return false;
        val->intValue = false;
        DEBUG << "value: string";
        END;
        return true;
    }
    case BeginArray:
        val->type = JsonValue::Array;
        if (current - baseOffset >= Value::MaxSize) {
            lastError = JsonParseError::DocumentTooLarge;
            return false;
        }
        val->value = current - baseOffset;
        if (!parseArray())
            return false;
        DEBUG << "value: array";
        END;
        return true;
    case BeginObject:
        val->type = JsonValue::Object;
        if (current - baseOffset >= Value::MaxSize) {
            lastError = JsonParseError::DocumentTooLarge;
            return false;
        }
        val->value = current - baseOffset;
        if (!parseObject())
            return false;
        DEBUG << "value: object";
        END;
        return true;
    case EndArray:
        lastError = JsonParseError::MissingObject;
        return false;
    default:
        --json;
        if (!parseNumber(val, baseOffset))
            return false;
        DEBUG << "value: number";
        END;
    }

    return true;
}





/*
        number = [ minus ] int [ frac ] [ exp ]
        decimal-point = %x2E       ; .
        digit1-9 = %x31-39         ; 1-9
        e = %x65 / %x45            ; e E
        exp = e [ minus / plus ] 1*DIGIT
        frac = decimal-point 1*DIGIT
        int = zero / ( digit1-9 *DIGIT )
        minus = %x2D               ; -
        plus = %x2B                ; +
        zero = %x30                ; 0

*/

bool Parser::parseNumber(Value *val, int baseOffset)
{
    BEGIN << "parseNumber" << json;
    val->type = JsonValue::Double;

    const char *start = json;
    bool isInt = true;

    // minus
    if (json < end && *json == '-')
        ++json;

    // int = zero / ( digit1-9 *DIGIT )
    if (json < end && *json == '0') {
        ++json;
    } else {
        while (json < end && *json >= '0' && *json <= '9')
            ++json;
    }

    // frac = decimal-point 1*DIGIT
    if (json < end && *json == '.') {
        isInt = false;
        ++json;
        while (json < end && *json >= '0' && *json <= '9')
            ++json;
    }

    // exp = e [ minus / plus ] 1*DIGIT
    if (json < end && (*json == 'e' || *json == 'E')) {
        isInt = false;
        ++json;
        if (json < end && (*json == '-' || *json == '+'))
            ++json;
        while (json < end && *json >= '0' && *json <= '9')
            ++json;
    }

    if (json >= end) {
        lastError = JsonParseError::TerminationByNumber;
        return false;
    }

    if (isInt) {
        char *endptr = const_cast<char *>(json);
        long long int n = strtoll(start, &endptr, 0);
        if (endptr != start && n < (1<<25) && n > -(1<<25)) {
            val->int_value = int(n);
            val->intValue = true;
            END;
            return true;
        }
    }

    char *endptr = const_cast<char *>(json);
    double d = strtod(start, &endptr);

    if (start == endptr || std::isinf(d)) {
        lastError = JsonParseError::IllegalNumber;
        return false;
    }

    int pos = reserveSpace(sizeof(double));
    memcpy(data + pos, &d, sizeof(double));
    if (current - baseOffset >= Value::MaxSize) {
        lastError = JsonParseError::DocumentTooLarge;
        return false;
    }
    val->value = pos - baseOffset;
    val->intValue = false;

    END;
    return true;
}

/*

        string = quotation-mark *char quotation-mark

        char = unescaped /
               escape (
                   %x22 /          ; "    quotation mark  U+0022
                   %x5C /          ; \    reverse solidus U+005C
                   %x2F /          ; /    solidus         U+002F
                   %x62 /          ; b    backspace       U+0008
                   %x66 /          ; f    form feed       U+000C
                   %x6E /          ; n    line feed       U+000A
                   %x72 /          ; r    carriage return U+000D
                   %x74 /          ; t    tab             U+0009
                   %x75 4HEXDIG )  ; uXXXX                U+XXXX

        escape = %x5C              ; \

        quotation-mark = %x22      ; "

        unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
 */
static bool addHexDigit(char digit, uint32_t *result)
{
    *result <<= 4;
    if (digit >= '0' && digit <= '9')
        *result |= (digit - '0');
    else if (digit >= 'a' && digit <= 'f')
        *result |= (digit - 'a') + 10;
    else if (digit >= 'A' && digit <= 'F')
        *result |= (digit - 'A') + 10;
    else
        return false;
    return true;
}

bool Parser::parseEscapeSequence()
{
    DEBUG << "scan escape" << (char)*json;
    const char escaped = *json++;
    switch (escaped) {
    case '"':
        addChar('"'); break;
    case '\\':
        addChar('\\'); break;
    case '/':
        addChar('/'); break;
    case 'b':
        addChar(0x8); break;
    case 'f':
        addChar(0xc); break;
    case 'n':
        addChar(0xa); break;
    case 'r':
        addChar(0xd); break;
    case 't':
        addChar(0x9); break;
    case 'u': {
        uint32_t c = 0;
        if (json > end - 4)
            return false;
        for (int i = 0; i < 4; ++i) {
            if (!addHexDigit(*json, &c))
                return false;
            ++json;
        }
        if (c < 0x80) {
            addChar(c);
            break;
        }
        if (c < 0x800) {
            addChar(192 + c / 64);
            addChar(128 + c % 64);
            break;
        }
        if (c - 0xd800u < 0x800) {
            return false;
        }
        if (c < 0x10000) {
            addChar(224 + c / 4096);
            addChar(128 + c / 64 % 64);
            addChar(128 + c % 64);
            break;
        }
        if (c < 0x110000) {
            addChar(240 + c / 262144);
            addChar(128 + c / 4096 % 64);
            addChar(128 + c / 64 % 64);
            addChar(128 + c % 64);
            break;
        }
        return false;
    }
    default:
        // this is not as strict as one could be, but allows for more Json files
        // to be parsed correctly.
        addChar(escaped);
        break;
    }
    return true;
}

bool Parser::parseString()
{
    const char *inStart = json;

    // First try quick pass without escapes.
    if (true) {
        while (1) {
            if (json >= end) {
                ++json;
                lastError = JsonParseError::UnterminatedString;
                return false;
            }

            const char c = *json;
            if (c == '"') {
                // write string length and padding.
                const int len = static_cast<int>(json - inStart);
                const int pos = reserveSpace(4 + alignedSize(len));
                toInternal(data + pos, inStart, len);
                END;

                ++json;
                return true;
            }

            if (c == '\\')
                break;
            ++json;
        }
    }

    // Try again with escapes.
    const int outStart = reserveSpace(4);
    json = inStart;
    while (1) {
        if (json >= end) {
            ++json;
            lastError = JsonParseError::UnterminatedString;
            return false;
        }

        if (*json == '"') {
            ++json;
            // write string length and padding.
            *(int *)(data + outStart) = current - outStart - 4;
            reserveSpace((4 - current) & 3);
            END;
            return true;
        }

        if (*json == '\\') {
            ++json;
            if (json >= end || !parseEscapeSequence()) {
                lastError = JsonParseError::IllegalEscapeSequence;
                return false;
            }
        } else {
            addChar(*json++);
        }
    }
}

namespace Internal {

static const Base emptyArray = {sizeof(Base), {0}, 0};
static const Base emptyObject = {sizeof(Base), {0}, 0};


void Data::compact()
{
    // assert(sizeof(Value) == sizeof(offset));

    if (!compactionCounter)
        return;

    Base *base = header->root();
    int reserve = 0;
    if (base->is_object) {
        const auto o = static_cast<Object *>(base);
        for (int i = 0; i < (int)o->length; ++i)
            reserve += o->entryAt(i)->usedStorage(o);
    } else {
        const auto a = static_cast<Array *>(base);
        for (int i = 0; i < (int)a->length; ++i)
            reserve += (*a)[i].usedStorage(a);
    }

    int size = sizeof(Base) + reserve + base->length*sizeof(offset);
    int alloc = sizeof(Header) + size;
    Header *h = (Header *) malloc(alloc);
    h->tag = JsonDocument::BinaryFormatTag;
    h->version = 1;
    Base *b = h->root();
    b->size = size;
    b->is_object = header->root()->is_object;
    b->length = base->length;
    b->tableOffset = reserve + sizeof(Array);

    int offset = sizeof(Base);
    if (b->is_object) {
        const auto o = static_cast<const Object *>(base);
        const auto no = static_cast<const Object *>(b);

        for (int i = 0; i < (int)o->length; ++i) {
            no->table()[i] = offset;

            const Entry *e = o->entryAt(i);
            Entry *ne = no->entryAt(i);
            int s = e->size();
            memcpy(ne, e, s);
            offset += s;
            int dataSize = e->value.usedStorage(o);
            if (dataSize) {
                memcpy((char *)no + offset, e->value.data(o), dataSize);
                ne->value.value = offset;
                offset += dataSize;
            }
        }
    } else {
        const auto a = static_cast<Array *>(base);
        const auto na = static_cast<Array *>(b);

        for (int i = 0; i < (int)a->length; ++i) {
            const Value &v = (*a)[i];
            Value &nv = (*na)[i];
            nv = v;
            int dataSize = v.usedStorage(a);
            if (dataSize) {
                memcpy((char *)na + offset, v.data(a), dataSize);
                nv.value = offset;
                offset += dataSize;
            }
        }
    }
    // assert(offset == (int)b->tableOffset);

    free(header);
    header = h;
    this->alloc = alloc;
    compactionCounter = 0;
}

bool Data::valid() const
{
    if (header->tag != JsonDocument::BinaryFormatTag || header->version != 1u)
        return false;

    bool res = false;
    if (header->root()->is_object)
        res = static_cast<Object *>(header->root())->isValid();
    else
        res = static_cast<Array *>(header->root())->isValid();

    return res;
}


int Base::reserveSpace(uint32_t dataSize, int posInTable, uint32_t numItems, bool replace)
{
    // assert(posInTable >= 0 && posInTable <= (int)length);
    if (size + dataSize >= Value::MaxSize) {
        fprintf(stderr, "Json: Document too large to store in data structure %d %d %d\n", (uint32_t)size, dataSize, Value::MaxSize);
        return 0;
    }

    offset off = tableOffset;
    // move table to new position
    if (replace) {
        memmove((char *)(table()) + dataSize, table(), length*sizeof(offset));
    } else {
        memmove((char *)(table() + posInTable + numItems) + dataSize, table() + posInTable, (length - posInTable)*sizeof(offset));
        memmove((char *)(table()) + dataSize, table(), posInTable*sizeof(offset));
    }
    tableOffset += dataSize;
    for (int i = 0; i < (int)numItems; ++i)
        table()[posInTable + i] = off;
    size += dataSize;
    if (!replace) {
        length += numItems;
        size += numItems * sizeof(offset);
    }
    return off;
}

void Base::removeItems(int pos, int numItems)
{
    // assert(pos >= 0 && pos <= (int)length);
    if (pos + numItems < (int)length)
        memmove(table() + pos, table() + pos + numItems, (length - pos - numItems)*sizeof(offset));
    length -= numItems;
}

int Object::indexOf(const std::string &key, bool *exists)
{
    int min = 0;
    int n = length;
    while (n > 0) {
        int half = n >> 1;
        int middle = min + half;
        if (*entryAt(middle) >= key) {
            n = half;
        } else {
            min = middle + 1;
            n -= half + 1;
        }
    }
    if (min < (int)length && *entryAt(min) == key) {
        *exists = true;
        return min;
    }
    *exists = false;
    return min;
}

bool Object::isValid() const
{
    if (tableOffset + length*sizeof(offset) > size)
        return false;

    std::string lastKey;
    for (uint32_t i = 0; i < length; ++i) {
        offset entryOffset = table()[i];
        if (entryOffset + sizeof(Entry) >= tableOffset)
            return false;
        Entry *e = entryAt(i);
        int s = e->size();
        if (table()[i] + s > tableOffset)
            return false;
        std::string key = e->key();
        if (key < lastKey)
            return false;
        if (!e->value.isValid(this))
            return false;
        lastKey = key;
    }
    return true;
}

bool Array::isValid() const
{
    if (tableOffset + length*sizeof(offset) > size)
        return false;

    for (uint32_t i = 0; i < length; ++i) {
        if (!at(i).isValid(this))
            return false;
    }
    return true;
}


bool Entry::operator==(const std::string &key) const
{
    return shallowKey() == key;
}

bool Entry::operator==(const Entry &other) const
{
    return shallowKey() == other.shallowKey();
}

bool Entry::operator>=(const Entry &other) const
{
    return shallowKey() >= other.shallowKey();
}


int Value::usedStorage(const Base *b) const
{
    int s = 0;
    switch (type) {
    case JsonValue::Double:
        if (intValue)
            break;
        s = sizeof(double);
        break;
    case JsonValue::String: {
        char *d = data(b);
        s = sizeof(int) + (*(int *)d);
        break;
    }
    case JsonValue::Array:
    case JsonValue::Object:
        s = base(b)->size;
        break;
    case JsonValue::Null:
    case JsonValue::Bool:
    default:
        break;
    }
    return alignedSize(s);
}

bool Value::isValid(const Base *b) const
{
    int offset = 0;
    switch (type) {
    case JsonValue::Double:
        if (intValue)
            break;
        // fall through
    case JsonValue::String:
    case JsonValue::Array:
    case JsonValue::Object:
        offset = value;
        break;
    case JsonValue::Null:
    case JsonValue::Bool:
    default:
        break;
    }

    if (!offset)
        return true;
    if (offset + sizeof(uint32_t) > b->tableOffset)
        return false;

    int s = usedStorage(b);
    if (!s)
        return true;
    if (s < 0 || offset + s > (int)b->tableOffset)
        return false;
    if (type == JsonValue::Array)
        return static_cast<Array *>(base(b))->isValid();
    if (type == JsonValue::Object)
        return static_cast<Object *>(base(b))->isValid();
    return true;
}

/*!
    \internal
 */
int Value::requiredStorage(JsonValue &v, bool *compressed)
{
    *compressed = false;
    switch (v.t) {
    case JsonValue::Double:
        if (Internal::compressedNumber(v.dbl) != INT_MAX) {
            *compressed = true;
            return 0;
        }
        return sizeof(double);
    case JsonValue::String: {
        std::string s = v.toString().data();
        *compressed = false;
        return Internal::qStringSize(s);
    }
    case JsonValue::Array:
    case JsonValue::Object:
        if (v.d && v.d->compactionCounter) {
            v.detach();
            v.d->compact();
            v.base = static_cast<Internal::Base *>(v.d->header->root());
        }
        return v.base ? v.base->size : sizeof(Internal::Base);
    case JsonValue::Undefined:
    case JsonValue::Null:
    case JsonValue::Bool:
        break;
    }
    return 0;
}

/*!
    \internal
 */
uint32_t Value::valueToStore(const JsonValue &v, uint32_t offset)
{
    switch (v.t) {
    case JsonValue::Undefined:
    case JsonValue::Null:
        break;
    case JsonValue::Bool:
        return v.b;
    case JsonValue::Double: {
        int c = Internal::compressedNumber(v.dbl);
        if (c != INT_MAX)
            return c;
    }
        // fall through
    case JsonValue::String:
    case JsonValue::Array:
    case JsonValue::Object:
        return offset;
    }
    return 0;
}

/*!
    \internal
 */

void Value::copyData(const JsonValue &v, char *dest, bool compressed)
{
    switch (v.t) {
    case JsonValue::Double:
        if (!compressed)
            memcpy(dest, &v.ui, 8);
        break;
    case JsonValue::String: {
        std::string str = v.toString();
        Internal::copyString(dest, str);
        break;
    }
    case JsonValue::Array:
    case JsonValue::Object: {
        const Internal::Base *b = v.base;
        if (!b)
            b = (v.t == JsonValue::Array ? &emptyArray : &emptyObject);
        memcpy(dest, b, b->size);
        break;
    }
    default:
        break;
    }
}

} // namespace Internal
} // namespace Json