summaryrefslogtreecommitdiffstats
path: root/storage/connect/bson.cpp
blob: 44d53ba17bd32b7d85399f908ef6e6d79addcd07 (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
/*************** bson CPP Declares Source Code File (.H) ***************/
/*  Name: bson.cpp   Version 1.0                                       */
/*                                                                     */
/*  (C) Copyright to the author Olivier BERTRAND          2020         */
/*                                                                     */
/*  This file contains the BJSON classes functions.                    */
/***********************************************************************/

/***********************************************************************/
/*  Include relevant sections of the MariaDB header file.              */
/***********************************************************************/
#include <my_global.h>
#include <m_string.h>

/***********************************************************************/
/*  Include application header files:                                  */
/*  global.h    is header containing all global declarations.          */
/*  plgdbsem.h  is header containing the DB application declarations.  */
/*  bson.h      is header containing the BSON classes declarations.    */
/***********************************************************************/
#include "global.h"
#include "plgdbsem.h"
#include "bson.h"

/***********************************************************************/
/*  Check macro.                                                       */
/***********************************************************************/
#if defined(_DEBUG)
#define CheckType(X,Y) if (!X || X ->Type != Y) throw MSG(VALTYPE_NOMATCH);
#else
#define CheckType(X,Y)
#endif

#if defined(_WIN32)
#define EL  "\r\n"
#else
#define EL  "\n"
#undef     SE_CATCH                  // Does not work for Linux
#endif

int GetJsonDefPrec(void);

#if defined(SE_CATCH)
/**************************************************************************/
/*  This is the support of catching C interrupts to prevent crashes.      */
/**************************************************************************/
#include <eh.h>

class SE_Exception {
public:
  SE_Exception(unsigned int n, PEXCEPTION_RECORD p) : nSE(n), eRec(p) {}
  ~SE_Exception() {}

  unsigned int      nSE;
  PEXCEPTION_RECORD eRec;
};  // end of class SE_Exception

void trans_func(unsigned int u, _EXCEPTION_POINTERS* pExp) {
  throw SE_Exception(u, pExp->ExceptionRecord);
} // end of trans_func

char* GetExceptionDesc(PGLOBAL g, unsigned int e);
#endif   // SE_CATCH

/* --------------------------- Class BDOC ---------------------------- */

/***********************************************************************/
/*  BDOC constructor.                                                  */
/***********************************************************************/
BDOC::BDOC(PGLOBAL G) : BJSON(G, NULL)
{ 
  jp = NULL;
  s = NULL;
  len = 0;
  pretty = 3;
  pty[0] = pty[1] = pty[2] = true;
  comma = false;
} // end of BDOC constructor

/***********************************************************************/
/* Parse a json string.                                                */
/* Note: when pretty is not known, the caller set pretty to 3.         */
/***********************************************************************/
PBVAL BDOC::ParseJson(PGLOBAL g, char* js, size_t lng)
{
  size_t i;
  bool  b = false;
  PBVAL bvp = NULL;

  s = js;
  len = lng;
  xtrc(1, "BDOC::ParseJson: s=%.10s len=%zd\n", s, len);

  if (!s || !len) {
    strcpy(g->Message, "Void JSON object");
    return NULL;
  } // endif s

  // Trying to guess the pretty format
  if (s[0] == '[' && (s[1] == '\n' || (s[1] == '\r' && s[2] == '\n')))
    pty[0] = false;

  try {
    bvp = NewVal();
    bvp->Type = TYPE_UNKNOWN;

    for (i = 0; i < len; i++)
      switch (s[i]) {
      case '[':
        if (bvp->Type != TYPE_UNKNOWN)
          bvp->To_Val = ParseAsArray(i);
        else
          bvp->To_Val = ParseArray(++i);

        bvp->Type = TYPE_JAR;
        break;
      case '{':
        if (bvp->Type != TYPE_UNKNOWN) {
          bvp->To_Val = ParseAsArray(i);
          bvp->Type = TYPE_JAR;
        } else {
          bvp->To_Val = ParseObject(++i);
          bvp->Type = TYPE_JOB;
        } // endif Type

        break;
      case ' ':
      case '\t':
      case '\n':
      case '\r':
        break;
      case ',':
        if (bvp->Type != TYPE_UNKNOWN && (pretty == 1 || pretty == 3)) {
          comma = true;
          pty[0] = pty[2] = false;
          break;
        } // endif pretty

        snprintf(g->Message, sizeof(g->Message), "Unexpected ',' (pretty=%d)", pretty);
        throw 3;
      case '(':
        b = true;
        break;
      case ')':
        if (b) {
          b = false;
          break;
        } // endif b
        /* fall through */
      default:
        if (bvp->Type != TYPE_UNKNOWN) {
          bvp->To_Val = ParseAsArray(i);
          bvp->Type = TYPE_JAR;
        } else if ((bvp->To_Val = MOF(ParseValue(i, NewVal()))))
          bvp->Type = TYPE_JVAL;
        else
          throw 4;

        break;
      }; // endswitch s[i]

    if (bvp->Type == TYPE_UNKNOWN)
      snprintf(g->Message, sizeof(g->Message), "Invalid Json string '%.*s'", MY_MIN((int)len, 50), s);
    else if (pretty == 3) {
      for (i = 0; i < 3; i++)
        if (pty[i]) {
          pretty = i;
          break;
        } // endif pty

    } // endif ptyp

  } catch (int n) {
    if (trace(1))
      htrc("Exception %d: %s\n", n, G->Message);
    GetMsg(g);
    bvp = NULL;
  } catch (const char* msg) {
    strcpy(g->Message, msg);
    bvp = NULL;
  } // end catch

  return bvp;
} // end of ParseJson

/***********************************************************************/
/* Parse several items as being in an array.                           */
/***********************************************************************/
OFFSET BDOC::ParseAsArray(size_t& i) {
  if (pty[0] && (!pretty || pretty > 2)) {
    OFFSET jsp;

    if ((jsp = ParseArray((i = 0))) && pretty == 3)
      pretty = (pty[0]) ? 0 : 3;

    return jsp;
  } else
    strcpy(G->Message, "More than one item in file");

  return 0;
} // end of ParseAsArray

/***********************************************************************/
/* Parse a JSON Array.                                                 */
/***********************************************************************/
OFFSET BDOC::ParseArray(size_t& i)
{
  int   level = 0;
  bool  b = (!i);
  PBVAL vlp, firstvlp, lastvlp;

  vlp = firstvlp = lastvlp = NULL;

  for (; i < len; i++)
    switch (s[i]) {
    case ',':
      if (level < 2) {
        snprintf(G->Message, sizeof(G->Message), "Unexpected ',' near %.*s", (int) ARGS);
        throw 1;
      } else
        level = 1;

      break;
    case ']':
      if (level == 1) {
        snprintf(G->Message, sizeof(G->Message), "Unexpected ',]' near %.*s", (int) ARGS);
        throw 1;
      } // endif level

      return MOF(firstvlp);
    case '\n':
      if (!b)
        pty[0] = pty[1] = false;
    case '\r':
    case ' ':
    case '\t':
      break;
    default:
      if (level == 2) {
        snprintf(G->Message, sizeof(G->Message), "Unexpected value near %.*s", (int) ARGS);
        throw 1;
      } else if (lastvlp) {
        vlp = ParseValue(i, NewVal());
        lastvlp->Next = MOF(vlp);
        lastvlp = vlp;
      } else
        firstvlp = lastvlp = ParseValue(i, NewVal());

      level = (b) ? 1 : 2;
      break;
    }; // endswitch s[i]

  if (b) {
    // Case of Pretty == 0
    return MOF(firstvlp);
  } // endif b

  throw ("Unexpected EOF in array");
} // end of ParseArray

/***********************************************************************/
/* Parse a JSON Object.                                                */
/***********************************************************************/
OFFSET BDOC::ParseObject(size_t& i)
{
  OFFSET key;
  int    level = 0;
  PBPR   bpp, firstbpp, lastbpp;

  bpp = firstbpp = lastbpp = NULL;

  for (; i < len; i++)
    switch (s[i]) {
    case '"':
      if (level < 2) {
        key = ParseString(++i);
        bpp = NewPair(key);

        if (lastbpp) {
          lastbpp->Vlp.Next = MOF(bpp);
          lastbpp = bpp;
        } else 
          firstbpp = lastbpp = bpp;

        level = 2;
      } else {
        snprintf(G->Message, sizeof(G->Message), "misplaced string near %.*s", (int) ARGS);
        throw 2;
      } // endif level

      break;
    case ':':
      if (level == 2) {
        ParseValue(++i, GetVlp(lastbpp));
        level = 3;
      } else {
        snprintf(G->Message, sizeof(G->Message), "Unexpected ':' near %.*s", (int) ARGS);
        throw 2;
      } // endif level

      break;
    case ',':
      if (level < 3) {
        snprintf(G->Message, sizeof(G->Message), "Unexpected ',' near %.*s", (int) ARGS);
        throw 2;
      } else
        level = 1;

      break;
    case '}':
      if (!(level == 0 || level == 3)) {
        snprintf(G->Message, sizeof(G->Message), "Unexpected '}' near %.*s", (int) ARGS);
        throw 2;
      } // endif level

      return MOF(firstbpp);
    case '\n':
      pty[0] = pty[1] = false;
    case '\r':
    case ' ':
    case '\t':
      break;
    default:
      snprintf(G->Message, sizeof(G->Message), "Unexpected character '%c' near %.*s",
        s[i], (int) ARGS);
      throw 2;
    }; // endswitch s[i]

  strcpy(G->Message, "Unexpected EOF in Object");
  throw 2;
} // end of ParseObject

/***********************************************************************/
/* Parse a JSON Value.                                                 */
/***********************************************************************/
PBVAL BDOC::ParseValue(size_t& i, PBVAL bvp)
{
  for (; i < len; i++)
    switch (s[i]) {
    case '\n':
      pty[0] = pty[1] = false;
    case '\r':
    case ' ':
    case '\t':
      break;
    default:
      goto suite;
    } // endswitch

suite:
  switch (s[i]) {
  case '[':
    bvp->To_Val = ParseArray(++i);
    bvp->Type = TYPE_JAR;
    break;
  case '{':
    bvp->To_Val = ParseObject(++i);
    bvp->Type = TYPE_JOB;
    break;
  case '"':
    bvp->To_Val = ParseString(++i);
    bvp->Type = TYPE_STRG;
    break;
  case 't':
    if (!strncmp(s + i, "true", 4)) {
      bvp->B = true;
      bvp->Type = TYPE_BOOL;
      i += 3;
    } else
      goto err;

    break;
  case 'f':
    if (!strncmp(s + i, "false", 5)) {
      bvp->B = false;
      bvp->Type = TYPE_BOOL;
      i += 4;
    } else
      goto err;

    break;
  case 'n':
    if (!strncmp(s + i, "null", 4)) {
      bvp->Type = TYPE_NULL;
      i += 3;
    } else
      goto err;

    break;
  case '-':
  default:
    if (s[i] == '-' || isdigit(s[i]))
      ParseNumeric(i, bvp);
    else
      goto err;

  }; // endswitch s[i]

  return bvp;

err:
  snprintf(G->Message, sizeof(G->Message), "Unexpected character '%c' near %.*s", s[i], (int) ARGS);
  throw 3;
} // end of ParseValue

/***********************************************************************/
/*  Unescape and parse a JSON string.                                  */
/***********************************************************************/
OFFSET BDOC::ParseString(size_t& i)
{
  uchar* p;
  int    n = 0;

  // Be sure of memory availability
  if (((size_t)len + 1 - i) > ((PPOOLHEADER)G->Sarea)->FreeBlk)
    throw("ParseString: Out of memory");

  // The size to allocate is not known yet
  p = (uchar*)BsonSubAlloc(0);

  for (; i < len; i++)
    switch (s[i]) {
    case '"':
      p[n++] = 0;
      BsonSubAlloc(n);
      return MOF(p);
    case '\\':
      if (++i < len) {
        if (s[i] == 'u') {
          if (len - i > 5) {
            //            if (charset == utf8) {
            char xs[5];
            uint hex;

            xs[0] = s[++i];
            xs[1] = s[++i];
            xs[2] = s[++i];
            xs[3] = s[++i];
            xs[4] = 0;
            hex = strtoul(xs, NULL, 16);

            if (hex < 0x80) {
              p[n] = (uchar)hex;
            } else if (hex < 0x800) {
              p[n++] = (uchar)(0xC0 | (hex >> 6));
              p[n] = (uchar)(0x80 | (hex & 0x3F));
            } else if (hex < 0x10000) {
              p[n++] = (uchar)(0xE0 | (hex >> 12));
              p[n++] = (uchar)(0x80 | ((hex >> 6) & 0x3f));
              p[n] = (uchar)(0x80 | (hex & 0x3f));
            } else
              p[n] = '?';

#if 0
          } else {
            char xs[3];
            UINT hex;

            i += 2;
            xs[0] = s[++i];
            xs[1] = s[++i];
            xs[2] = 0;
            hex = strtoul(xs, NULL, 16);
            p[n] = (char)hex;
          } // endif charset
#endif // 0
        } else
          goto err;

      } else switch (s[i]) {
      case 't': p[n] = '\t'; break;
      case 'n': p[n] = '\n'; break;
      case 'r': p[n] = '\r'; break;
      case 'b': p[n] = '\b'; break;
      case 'f': p[n] = '\f'; break;
      default:  p[n] = s[i]; break;
      } // endswitch

      n++;
    } else
      goto err;

    break;
      default:
        p[n++] = s[i];
        break;
}; // endswitch s[i]

err:
throw("Unexpected EOF in String");
} // end of ParseString

/***********************************************************************/
/* Parse a JSON numeric value.                                         */
/***********************************************************************/
void BDOC::ParseNumeric(size_t& i, PBVAL vlp)
{
  char  buf[50];
  int   n = 0;
  short nd = 0;
  bool  has_dot = false;
  bool  has_e = false;
  bool  found_digit = false;

  for (; i < len; i++) {
    switch (s[i]) {
    case '.':
      if (!found_digit || has_dot || has_e)
        goto err;

      has_dot = true;
      break;
    case 'e':
    case 'E':
      if (!found_digit || has_e)
        goto err;

      has_e = true;
      found_digit = false;
      break;
    case '+':
      if (!has_e)
        goto err;

      // fall through
    case '-':
      if (found_digit)
        goto err;

      break;
    default:
      if (isdigit(s[i])) {
        if (has_dot && !has_e)
          nd++;       // Number of decimals

        found_digit = true;
      } else
        goto fin;

    }; // endswitch s[i]

    buf[n++] = s[i];
  } // endfor i

fin:
  if (found_digit) {
    buf[n] = 0;

    if (has_dot || has_e) {
      double dv = atof(buf);

      if (nd >= 6 || dv > FLT_MAX || dv < FLT_MIN) {
        double* dvp = (double*)PlugSubAlloc(G, NULL, sizeof(double));

        *dvp = dv;
        vlp->To_Val = MOF(dvp);
        vlp->Type = TYPE_DBL;
      } else {
        vlp->F = (float)dv;
        vlp->Type = TYPE_FLOAT;
      } // endif nd

      vlp->Nd = MY_MIN(nd, 16);
    } else {
      longlong iv = strtoll(buf, NULL, 10);

      if (iv > INT_MAX32 || iv < INT_MIN32) {
        longlong *llp = (longlong*)PlugSubAlloc(G, NULL, sizeof(longlong));

        *llp = iv;
        vlp->To_Val = MOF(llp);
        vlp->Type = TYPE_BINT;
      } else {
        vlp->N = (int)iv;
        vlp->Type = TYPE_INTG;
      } // endif iv

    } // endif has

    i--;  // Unstack  following character
    return;
  } else
    throw("No digit found");

err:
  throw("Unexpected EOF in number");
} // end of ParseNumeric

/***********************************************************************/
/* Serialize a BJSON document tree:                                    */
/***********************************************************************/
PSZ BDOC::Serialize(PGLOBAL g, PBVAL bvp, char* fn, int pretty)
{
  PSZ   str = NULL;
  bool  b = false, err = true;
  FILE* fs = NULL;

  G->Message[0] = 0;

  try {
    if (!bvp) {
      safe_strcpy(g->Message, sizeof(g->Message), "Null json tree");
      throw 1;
    } else if (!fn) {
      // Serialize to a string
      jp = new(g) JOUTSTR(g);
      b = pretty == 1;
    } else {
      if (!(fs = fopen(fn, "wb"))) {
        snprintf(g->Message, sizeof(g->Message), MSG(OPEN_MODE_ERROR) ": %s",
          "w", (int)errno, fn, strerror(errno));
        throw 2;
      } else if (pretty >= 2) {
        // Serialize to a pretty file
        jp = new(g)JOUTPRT(g, fs);
      } else {
        // Serialize to a flat file
        b = true;
        jp = new(g)JOUTFILE(g, fs, pretty);
      } // endif's

    } // endif's

    switch (bvp->Type) {
    case TYPE_JAR:
      err = SerializeArray(bvp->To_Val, b);
      break;
    case TYPE_JOB:
      err = ((b && jp->Prty()) && jp->WriteChr('\t'));
      err |= SerializeObject(bvp->To_Val);
      break;
    case TYPE_JVAL:
      err = SerializeValue(MVP(bvp->To_Val));
      break;
    default:
      err = SerializeValue(bvp, true);
    } // endswitch Type

    if (fs) {
      fputs(EL, fs);
      fclose(fs);
      str = (err) ? NULL : strcpy(g->Message, "Ok");
    } else if (!err) {
      str = ((JOUTSTR*)jp)->Strp;
      jp->WriteChr('\0');
      PlugSubAlloc(g, NULL, ((JOUTSTR*)jp)->N);
    } else if (G->Message[0])
        strcpy(g->Message, "Error in Serialize");
      else
        GetMsg(g);

  } catch (int n) {
    if (trace(1))
      htrc("Exception %d: %s\n", n, G->Message);
    GetMsg(g);
    str = NULL;
  } catch (const char* msg) {
    strcpy(g->Message, msg);
    str = NULL;
  } // end catch

  return str;
} // end of Serialize


/***********************************************************************/
/* Serialize a JSON Array.                                             */
/***********************************************************************/
bool BDOC::SerializeArray(OFFSET arp, bool b)
{
  bool  first = true;
  PBVAL vp = MVP(arp);

  if (b) {
    if (jp->Prty()) {
      if (jp->WriteChr('['))
        return true;
      else if (jp->Prty() == 1 && (jp->WriteStr(EL) || jp->WriteChr('\t')))
        return true;

    } // endif Prty

  } else if (jp->WriteChr('['))
    return true;

  for (; vp; vp = MVP(vp->Next)) {
    if (first)
      first = false;
    else if ((!b || jp->Prty()) && jp->WriteChr(','))
      return true;
    else if (b) {
      if (jp->Prty() < 2 && jp->WriteStr(EL))
        return true;
      else if (jp->Prty() == 1 && jp->WriteChr('\t'))
        return true;

    } // endif b

    if (SerializeValue(vp))
      return true;

  } // endfor vp

  if (b && jp->Prty() == 1 && jp->WriteStr(EL))
    return true;

  return ((!b || jp->Prty()) && jp->WriteChr(']'));
} // end of SerializeArray

/***********************************************************************/
/* Serialize a JSON Object.                                            */
/***********************************************************************/
bool BDOC::SerializeObject(OFFSET obp)
{
  bool first = true;
  PBPR prp = MPP(obp);

  if (jp->WriteChr('{'))
    return true;

  for (; prp; prp = GetNext(prp)) {
    if (first)
      first = false;
    else if (jp->WriteChr(','))
      return true;

    if (jp->WriteChr('"') ||
      jp->WriteStr(MZP(prp->Key)) ||
      jp->WriteChr('"') ||
      jp->WriteChr(':') ||
      SerializeValue(GetVlp(prp)))
      return true;

  } // endfor i

  return jp->WriteChr('}');
} // end of SerializeObject

/***********************************************************************/
/* Serialize a JSON Value.                                             */
/***********************************************************************/
bool BDOC::SerializeValue(PBVAL jvp, bool b)
{
  char buf[64];

  if (jvp) switch (jvp->Type) {
  case TYPE_JAR:
    return SerializeArray(jvp->To_Val, false);
  case TYPE_JOB:
    return SerializeObject(jvp->To_Val);
  case TYPE_BOOL:
    return jp->WriteStr(jvp->B ? "true" : "false");
  case TYPE_STRG:
  case TYPE_DTM:
    if (b) {
      return jp->WriteStr(MZP(jvp->To_Val));
    } else
      return jp->Escape(MZP(jvp->To_Val));

  case TYPE_INTG:
    snprintf(buf, sizeof(buf), "%d", jvp->N);
    return jp->WriteStr(buf);
  case TYPE_BINT:
    snprintf(buf, sizeof(buf), "%lld", *(longlong*)MakePtr(Base, jvp->To_Val));
    return jp->WriteStr(buf);
  case TYPE_FLOAT:
    snprintf(buf, sizeof(buf), "%.*f", jvp->Nd, jvp->F);
    return jp->WriteStr(buf);
  case TYPE_DBL:
    snprintf(buf, sizeof(buf), "%.*lf", jvp->Nd, *(double*)MakePtr(Base, jvp->To_Val));
    return jp->WriteStr(buf);
  case TYPE_NULL:
    return jp->WriteStr("null");
  case TYPE_JVAL:
    return SerializeValue(MVP(jvp->To_Val));
  default:
    return jp->WriteStr("???");   // TODO
  } // endswitch Type

  return  jp->WriteStr("null");
} // end of SerializeValue

/* --------------------------- Class BJSON --------------------------- */

/***********************************************************************/
/*  Program for sub-allocating Bjson structures.                       */
/***********************************************************************/
void* BJSON::BsonSubAlloc(size_t size)
{
  PPOOLHEADER pph;                           /* Points on area header. */
  void* memp = G->Sarea;

  size = ((size + 3) / 4) * 4;       /* Round up size to multiple of 4 */
  pph = (PPOOLHEADER)memp;

  xtrc(16, "SubAlloc in %p size=%zd used=%zd free=%zd\n",
    memp, size, pph->To_Free, pph->FreeBlk);

  if (size > pph->FreeBlk) {   /* Not enough memory left in pool */
    snprintf(G->Message, sizeof(G->Message),
      "Not enough memory for request of %zd (used=%zd free=%zd)",
      size, pph->To_Free, pph->FreeBlk);
    xtrc(1, "BsonSubAlloc: %s\n", G->Message);

    if (Throw)
      throw(1234);
    else
      return NULL;

  } /* endif size OS32 code */

  // Do the suballocation the simplest way
  memp = MakePtr(memp, pph->To_Free); /* Points to suballocated block  */
  pph->To_Free += size;               /* New offset of pool free block */
  pph->FreeBlk -= size;               /* New size   of pool free block */
  xtrc(16, "Done memp=%p used=%zd free=%zd\n",
    memp, pph->To_Free, pph->FreeBlk);
  return memp;
} // end of BsonSubAlloc

/*********************************************************************************/
/*  Program for SubSet re-initialization of the memory pool.                     */
/*********************************************************************************/
PSZ BJSON::NewStr(PSZ str)
{
  if (str) {
    PSZ sm = (PSZ)BsonSubAlloc(strlen(str) + 1);

    strcpy(sm, str);
    return sm;
  } else
    return NULL;

} // end of NewStr

/*********************************************************************************/
/*  Program for SubSet re-initialization of the memory pool.                     */
/*********************************************************************************/
void BJSON::SubSet(bool b)
{
  PPOOLHEADER pph = (PPOOLHEADER)G->Sarea;

  pph->To_Free = (G->Saved_Size) ? G->Saved_Size : sizeof(POOLHEADER);
  pph->FreeBlk = G->Sarea_Size - pph->To_Free;

  if (b)
    G->Saved_Size = 0;

} // end of SubSet

/*********************************************************************************/
/*  Set the beginning of suballocations.                                         */
/*********************************************************************************/
void BJSON::MemSet(size_t size)
{
  PPOOLHEADER pph = (PPOOLHEADER)G->Sarea;

  pph->To_Free = size + sizeof(POOLHEADER);
  pph->FreeBlk = G->Sarea_Size - pph->To_Free;
} // end of MemSet

  /* ------------------------ Bobject functions ------------------------ */

/***********************************************************************/
/* Set a pair vlp to some PVAL values.                                 */
/***********************************************************************/
void BJSON::SetPairValue(PBPR brp, PBVAL bvp)
{
  if (bvp) {
    brp->Vlp.To_Val = bvp->To_Val;
    brp->Vlp.Nd = bvp->Nd;
    brp->Vlp.Type = bvp->Type;
  } else {
    brp->Vlp.To_Val = 0;
    brp->Vlp.Nd = 0;
    brp->Vlp.Type = TYPE_NULL;
  } // endif bvp

} // end of SetPairValue

  /***********************************************************************/
/* Sub-allocate and initialize a BPAIR.                                */
/***********************************************************************/
PBPR BJSON::NewPair(OFFSET key, int type)
{
  PBPR bpp = (PBPR)BsonSubAlloc(sizeof(BPAIR));

  bpp->Key = key;
  bpp->Vlp.Type = type;
  bpp->Vlp.To_Val = 0;
  bpp->Vlp.Nd = 0;
  bpp->Vlp.Next = 0;
  return bpp;
} // end of SubAllocPair

/***********************************************************************/
/* Return the number of pairs in this object.                          */
/***********************************************************************/
int BJSON::GetObjectSize(PBVAL bop, bool b)
{
  CheckType(bop, TYPE_JOB);
  int n = 0;

  for (PBPR brp = GetObject(bop); brp; brp = GetNext(brp))
    // If b return only non null pairs
    if (!b || (brp->Vlp.To_Val && brp->Vlp.Type != TYPE_NULL))
      n++;

  return n;
} // end of GetObjectSize

/***********************************************************************/
/* Add a new pair to an Object and return it.                          */
/***********************************************************************/
PBVAL BJSON::AddPair(PBVAL bop, PSZ key, int type)
{
  CheckType(bop, TYPE_JOB);
  PBPR   brp;
  OFFSET nrp = NewPair(key, type);

  if (bop->To_Val) {
    for (brp = GetObject(bop); brp->Vlp.Next; brp = GetNext(brp));

    brp->Vlp.Next = nrp;
  } else
    bop->To_Val = nrp;

  bop->Nd++;
  return GetVlp(MPP(nrp));
} // end of AddPair

/***********************************************************************/
/* Return all object keys as an array.                                 */
/***********************************************************************/
PBVAL BJSON::GetKeyList(PBVAL bop)
{
  CheckType(bop, TYPE_JOB);
  PBVAL arp = NewVal(TYPE_JAR);

  for (PBPR brp = GetObject(bop); brp; brp = GetNext(brp))
    AddArrayValue(arp, MOF(SubAllocVal(brp->Key, TYPE_STRG)));

  return arp;
} // end of GetKeyList

/***********************************************************************/
/* Return all object values as an array.                               */
/***********************************************************************/
PBVAL BJSON::GetObjectValList(PBVAL bop)
{
  CheckType(bop, TYPE_JOB);
  PBVAL arp = NewVal(TYPE_JAR);

  for (PBPR brp = GetObject(bop); brp; brp = GetNext(brp))
    AddArrayValue(arp, DupVal(GetVlp(brp)));

  return arp;
} // end of GetObjectValList

/***********************************************************************/
/* Get the value corresponding to the given key.                       */
/***********************************************************************/
PBVAL BJSON::GetKeyValue(PBVAL bop, PSZ key)
{
  CheckType(bop, TYPE_JOB);

  for (PBPR brp = GetObject(bop); brp; brp = GetNext(brp))
    if (!strcmp(GetKey(brp), key))
      return GetVlp(brp);

  return NULL;
} // end of GetKeyValue;

/***********************************************************************/
/* Return the text corresponding to all keys (XML like).               */
/***********************************************************************/
PSZ BJSON::GetObjectText(PGLOBAL g, PBVAL bop, PSTRG text)
{
  CheckType(bop, TYPE_JOB);
  PBPR brp = GetObject(bop);

  if (brp) {
    bool b;

    if (!text) {
      text = new(g) STRING(g, 256);
      b = true;
    } else {
      if (text->GetLastChar() != ' ')
        text->Append(' ');

      b = false;
    }	// endif text

    if (b && !brp->Vlp.Next && !strcmp(MZP(brp->Key), "$date")) {
      int i;
      PSZ s;

      GetValueText(g, GetVlp(brp), text);
      s = text->GetStr();
      i = (s[1] == '-' ? 2 : 1);

      if (IsNum(s + i)) {
        // Date is in milliseconds
        int j = text->GetLength();

        if (j >= 4 + i) {
          s[j - 3] = 0;        // Change it to seconds
          text->SetLength((uint)strlen(s));
        } else
          text->Set(" 0");

      } // endif text

    } else for (; brp; brp = GetNext(brp)) {
      GetValueText(g, GetVlp(brp), text);

      if (brp->Vlp.Next)
        text->Append(' ');

    }	// endfor brp

    if (b) {
      text->Trim();
      return text->GetStr();
    }	// endif b

  } // endif bop

  return NULL;
} // end of GetObjectText;

/***********************************************************************/
/* Set or add a value corresponding to the given key.                  */
/***********************************************************************/
void BJSON::SetKeyValue(PBVAL bop, OFFSET bvp, PSZ key)
{
  CheckType(bop, TYPE_JOB);
  PBPR brp, prp = NULL;

  if (bop->To_Val) {
    for (brp = GetObject(bop); brp; brp = GetNext(brp))
      if (!strcmp(GetKey(brp), key))
        break;
      else
        prp = brp;

    if (!brp)
      brp = MPP(prp->Vlp.Next = NewPair(key));

  } else
    brp = MPP(bop->To_Val = NewPair(key));

  SetPairValue(brp, MVP(bvp));
  bop->Nd++;
} // end of SetKeyValue

/***********************************************************************/
/* Merge two objects.                                                  */
/***********************************************************************/
PBVAL BJSON::MergeObject(PBVAL bop1, PBVAL bop2)
{
  CheckType(bop1, TYPE_JOB);
  CheckType(bop2, TYPE_JOB);

  if (bop1->To_Val)
    for (PBPR brp = GetObject(bop2); brp; brp = GetNext(brp))
      SetKeyValue(bop1, GetVlp(brp), GetKey(brp));

  else {
    bop1->To_Val = bop2->To_Val;
    bop1->Nd = bop2->Nd;
  } // endelse To_Val

  return bop1;
} // end of MergeObject;

/***********************************************************************/
/* Delete a value corresponding to the given key.                      */
/***********************************************************************/
bool BJSON::DeleteKey(PBVAL bop, PCSZ key)
{
  CheckType(bop, TYPE_JOB);
  PBPR brp, pbrp = NULL;

  for (brp = GetObject(bop); brp; brp = GetNext(brp))
    if (!strcmp(MZP(brp->Key), key)) {
      if (pbrp) {
        pbrp->Vlp.Next = brp->Vlp.Next;
      } else
        bop->To_Val = brp->Vlp.Next;

      bop->Nd--;
      return true;;
    } else
      pbrp = brp;

  return false;
} // end of DeleteKey

/***********************************************************************/
/* True if void or if all members are nulls.                           */
/***********************************************************************/
bool BJSON::IsObjectNull(PBVAL bop)
{
  CheckType(bop, TYPE_JOB);

  for (PBPR brp = GetObject(bop); brp; brp = GetNext(brp))
    if (brp->Vlp.To_Val && brp->Vlp.Type != TYPE_NULL)
      return false;

  return true;
} // end of IsObjectNull

/* ------------------------- Barray functions ------------------------ */

/***********************************************************************/
/* Return the number of values in this object.                         */
/***********************************************************************/
int BJSON::GetArraySize(PBVAL bap, bool b)
{
  CheckType(bap, TYPE_JAR);
  int n = 0;

  for (PBVAL bvp = GetArray(bap); bvp; bvp = GetNext(bvp))
    //  If b, return only non null values
    if (!b || bvp->Type != TYPE_NULL)
      n++;

  return n;
} // end of GetArraySize

/***********************************************************************/
/* Get the Nth value of an Array.                                      */
/***********************************************************************/
PBVAL BJSON::GetArrayValue(PBVAL bap, int n)
{
  CheckType(bap, TYPE_JAR);
  int i = 0;

  if (n < 0)
    n += GetArraySize(bap);

  for (PBVAL bvp = GetArray(bap); bvp; bvp = GetNext(bvp), i++)
    if (i == n)
      return bvp;

  return NULL;
} // end of GetArrayValue

/***********************************************************************/
/* Add a Value to the Array Value list.                                */
/***********************************************************************/
void BJSON::AddArrayValue(PBVAL bap, OFFSET nbv, int* x)
{
  CheckType(bap, TYPE_JAR);
  int   i = 0;
  PBVAL bvp, lbp = NULL;

  if (!nbv)
    nbv = MOF(NewVal());

  for (bvp = GetArray(bap); bvp; bvp = GetNext(bvp), i++)
    if (x && i == *x)
      break;
    else
      lbp = bvp;

  if (lbp) {
    MVP(nbv)->Next = lbp->Next;
    lbp->Next = nbv;
  } else {
    MVP(nbv)->Next = bap->To_Val;
    bap->To_Val = nbv;
  } // endif lbp

  bap->Nd++;
} // end of AddArrayValue

/***********************************************************************/
/* Merge two arrays.                                                   */
/***********************************************************************/
void BJSON::MergeArray(PBVAL bap1, PBVAL bap2)
{
  CheckType(bap1, TYPE_JAR);
  CheckType(bap2, TYPE_JAR);

  if (bap1->To_Val) {
    for (PBVAL bvp = GetArray(bap2); bvp; bvp = GetNext(bvp))
      AddArrayValue(bap1, MOF(DupVal(bvp)));

  } else {
    bap1->To_Val = bap2->To_Val;
    bap1->Nd = bap2->Nd;
  } // endif To_Val

} // end of MergeArray

/***********************************************************************/
/* Set the nth Value of the Array Value list or add it.                */
/***********************************************************************/
void BJSON::SetArrayValue(PBVAL bap, PBVAL nvp, int n)
{
  CheckType(bap, TYPE_JAR);
  int   i = 0;
  PBVAL bvp = NULL;

  for (bvp = GetArray(bap); i < n; i++, bvp = bvp ? GetNext(bvp) : NULL)
    if (!bvp)
      AddArrayValue(bap, NewVal());

  if (!bvp)
    AddArrayValue(bap, MOF(nvp));
  else
    SetValueVal(bvp, nvp);

} // end of SetValue

/***********************************************************************/
/* Return the text corresponding to all values.                        */
/***********************************************************************/
PSZ BJSON::GetArrayText(PGLOBAL g, PBVAL bap, PSTRG text)
{
  CheckType(bap, TYPE_JAR);

  if (bap->To_Val) {
    bool  b;

    if (!text) {
      text = new(g) STRING(g, 256);
      b = true;
    } else {
      if (text->GetLastChar() != ' ')
        text->Append(" (");
      else
        text->Append('(');

      b = false;
    } // endif text

    for (PBVAL bvp = GetArray(bap); bvp; bvp = GetNext(bvp)) {
      GetValueText(g, bvp, text);

      if (bvp->Next)
        text->Append(", ");
      else if (!b)
        text->Append(')');

    }	// endfor bvp

    if (b) {
      text->Trim();
      return text->GetStr();
    }	// endif b

  } // endif To_Val

  return NULL;
} // end of GetText;

/***********************************************************************/
/* Delete a Value from the Arrays Value list.                          */
/***********************************************************************/
bool BJSON::DeleteValue(PBVAL bap, int n)
{
  CheckType(bap, TYPE_JAR);
  int   i = 0;
  PBVAL bvp, pvp = NULL;

  for (bvp = GetArray(bap); bvp; i++, bvp = GetNext(bvp))
    if (i == n) {
      if (pvp)
        pvp->Next = bvp->Next;
      else
        bap->To_Val = bvp->Next;

      bap->Nd--;
      return true;;
    } else
      pvp = bvp;

  return false;
} // end of DeleteValue

/***********************************************************************/
/* True if void or if all members are nulls.                           */
/***********************************************************************/
bool BJSON::IsArrayNull(PBVAL bap)
{
  CheckType(bap, TYPE_JAR);

  for (PBVAL bvp = GetArray(bap); bvp; bvp = GetNext(bvp))
    if (bvp->Type != TYPE_NULL)
      return false;

  return true;
} // end of IsNull

/* ------------------------- Bvalue functions ------------------------ */

/***********************************************************************/
/* Sub-allocate and clear a BVAL.                                      */
/***********************************************************************/
PBVAL BJSON::NewVal(int type)
{
  PBVAL bvp = (PBVAL)BsonSubAlloc(sizeof(BVAL));

  bvp->To_Val = 0;
  bvp->Nd = 0;
  bvp->Type = type;
  bvp->Next = 0;
  return bvp;
} // end of SubAllocVal

/***********************************************************************/
/* Sub-allocate and initialize a BVAL as type.                         */
/***********************************************************************/
PBVAL BJSON::SubAllocVal(OFFSET toval, int type, short nd)
{
  PBVAL bvp = NewVal(type);

  bvp->To_Val = toval;
  bvp->Nd = nd;
  return bvp;
} // end of SubAllocVal

/***********************************************************************/
/* Sub-allocate and initialize a BVAL as string.                       */
/***********************************************************************/
PBVAL BJSON::SubAllocStr(OFFSET toval, short nd)
{
  PBVAL bvp = NewVal(TYPE_STRG);

  bvp->To_Val = toval;
  bvp->Nd = nd;
  return bvp;
} // end of SubAllocStr

/***********************************************************************/
/* Allocate a BVALUE with a given string or numeric value.             */
/***********************************************************************/
PBVAL BJSON::NewVal(PVAL valp)
{
  PBVAL vlp = NewVal();

  SetValue(vlp, valp);
  return vlp;
} // end of SubAllocVal

/***********************************************************************/
/* Sub-allocate and initialize a BVAL from another BVAL.               */
/***********************************************************************/
PBVAL BJSON::DupVal(PBVAL bvlp)
{
  if (bvlp) {
    PBVAL bvp = NewVal();

    *bvp = *bvlp;
    bvp->Next = 0;
    return bvp;
  } else
    return NULL;

} // end of DupVal

/***********************************************************************/
/* Return the size of value's value.                                   */
/***********************************************************************/
int BJSON::GetSize(PBVAL vlp, bool b)
{
  switch (vlp->Type) {
  case TYPE_JAR:
    return GetArraySize(vlp);
  case TYPE_JOB:
    return GetObjectSize(vlp);
  default:
    return 1;
  } // enswitch Type

} // end of GetSize

PBVAL BJSON::GetBson(PBVAL bvp)
{ 
  PBVAL bp = NULL;

  switch (bvp->Type) {
    case TYPE_JAR:
      bp = MVP(bvp->To_Val);
      break;
    case TYPE_JOB:
      bp = GetVlp(MPP(bvp->To_Val));
      break;
    default:
      bp = bvp;
      break;
  } // endswitch Type

  return bp;
} // end of GetBson

/***********************************************************************/
/* Return the Value's as a Value struct.                               */
/***********************************************************************/
PVAL BJSON::GetValue(PGLOBAL g, PBVAL vp)
{
  double d;
  PVAL   valp;
  PBVAL  vlp = vp->Type == TYPE_JVAL ? MVP(vp->To_Val) : vp;

  switch (vlp->Type) {
    case TYPE_STRG:
    case TYPE_DBL:
    case TYPE_BINT:
      valp = AllocateValue(g, MP(vlp->To_Val), vlp->Type, vlp->Nd);
      break;
    case TYPE_INTG:
    case TYPE_BOOL:
      valp = AllocateValue(g, vlp, vlp->Type);
      break;
    case TYPE_FLOAT:
      d = (double)vlp->F;
      valp = AllocateValue(g, &d, TYPE_DOUBLE, vlp->Nd);
      break;
    default:
      valp = NULL;
      break;
  } // endswitch Type

  return valp;
} // end of GetValue

/***********************************************************************/
/* Return the Value's Integer value.                                   */
/***********************************************************************/
int BJSON::GetInteger(PBVAL vp) {
  int   n;
  PBVAL vlp = (vp->Type == TYPE_JVAL) ? MVP(vp->To_Val) : vp;

  switch (vlp->Type) {
  case TYPE_INTG:
    n = vlp->N;
    break;
  case TYPE_FLOAT:
    n = (int)vlp->F;
    break;
  case TYPE_DTM:
  case TYPE_STRG:
    n = atoi(MZP(vlp->To_Val));
    break;
  case TYPE_BOOL:
    n = (vlp->B) ? 1 : 0;
    break;
  case TYPE_BINT: 
    n = (int)*(longlong*)MP(vlp->To_Val);
    break;
  case TYPE_DBL:
    n = (int)*(double*)MP(vlp->To_Val);
    break;
  default:
    n = 0;
  } // endswitch Type

  return n;
} // end of GetInteger

/***********************************************************************/
/* Return the Value's Big integer value.                               */
/***********************************************************************/
longlong BJSON::GetBigint(PBVAL vp) {
  longlong lln;
  PBVAL vlp = (vp->Type == TYPE_JVAL) ? MVP(vp->To_Val) : vp;

  switch (vlp->Type) {
  case TYPE_BINT: 
    lln = *(longlong*)MP(vlp->To_Val);
    break;
  case TYPE_INTG: 
    lln = (longlong)vlp->N;
    break;
  case TYPE_FLOAT: 
    lln = (longlong)vlp->F;
    break;
  case TYPE_DBL:
    lln = (longlong)*(double*)MP(vlp->To_Val);
    break;
  case TYPE_DTM:
  case TYPE_STRG: 
    lln = atoll(MZP(vlp->To_Val));
    break;
  case TYPE_BOOL:
    lln = (vlp->B) ? 1 : 0;
    break;
  default:
    lln = 0;
  } // endswitch Type

  return lln;
} // end of GetBigint

/***********************************************************************/
/* Return the Value's Double value.                                    */
/***********************************************************************/
double BJSON::GetDouble(PBVAL vp)
{
  double d;
  PBVAL vlp = (vp->Type == TYPE_JVAL) ? MVP(vp->To_Val) : vp;

  switch (vlp->Type) {
    case TYPE_DBL:
      d = *(double*)MP(vlp->To_Val);
      break;
    case TYPE_BINT:
      d = (double)*(longlong*)MP(vlp->To_Val);
      break;
    case TYPE_INTG:
      d = (double)vlp->N;
      break;
    case TYPE_FLOAT:
      d = (double)vlp->F;
      break;
    case TYPE_DTM:
    case TYPE_STRG:
      d = atof(MZP(vlp->To_Val));
      break;
    case TYPE_BOOL:
      d = (vlp->B) ? 1.0 : 0.0;
      break;
    default:
      d = 0.0;
  } // endswitch Type

  return d;
} // end of GetDouble

/***********************************************************************/
/* Return the Value's String value.                                    */
/***********************************************************************/
PSZ BJSON::GetString(PBVAL vp, char* buff)
{
  char  buf[32];
  char* p = (buff) ? buff : buf;
  PBVAL vlp = (vp->Type == TYPE_JVAL) ? MVP(vp->To_Val) : vp;

  switch (vlp->Type) {
  case TYPE_DTM:
  case TYPE_STRG:
    p = MZP(vlp->To_Val);
    break;
  case TYPE_INTG:
    sprintf(p, "%d", vlp->N);
    break;
  case TYPE_FLOAT:
    sprintf(p, "%.*f", vlp->Nd, vlp->F);
    break;
  case TYPE_BINT:
    sprintf(p, "%lld", *(longlong*)MP(vlp->To_Val));
    break;
  case TYPE_DBL:
    sprintf(p, "%.*lf", vlp->Nd, *(double*)MP(vlp->To_Val));
    break;
  case TYPE_BOOL:
    p = (PSZ)((vlp->B) ? "true" : "false");
    break;
  case TYPE_NULL:
    p = (PSZ)"null";
    break;
  default:
    p = NULL;
  } // endswitch Type

  return (p == buf) ? (PSZ)PlugDup(G, buf) : p;
} // end of GetString

/***********************************************************************/
/* Return the Value's String value.                                    */
/***********************************************************************/
PSZ BJSON::GetValueText(PGLOBAL g, PBVAL vlp, PSTRG text)
{
  if (vlp->Type == TYPE_JOB)
    return GetObjectText(g, vlp, text);
  else if (vlp->Type == TYPE_JAR)
    return GetArrayText(g, vlp, text);

  char buff[32];
  PSZ  s = (vlp->Type == TYPE_NULL) ? NULL : GetString(vlp, buff);

  if (s)
    text->Append(s);
  else if (GetJsonNull())
    text->Append(GetJsonNull());

  return NULL;
} // end of GetText

void BJSON::SetValueObj(PBVAL vlp, PBVAL bop)
{
  CheckType(bop, TYPE_JOB);
  vlp->To_Val = bop->To_Val;
  vlp->Nd = bop->Nd;
  vlp->Type = TYPE_JOB;
} // end of SetValueObj;

void BJSON::SetValueArr(PBVAL vlp, PBVAL bap)
{
  CheckType(bap, TYPE_JAR);
  vlp->To_Val = bap->To_Val;
  vlp->Nd = bap->Nd;
  vlp->Type = TYPE_JAR;
} // end of SetValue;

void BJSON::SetValueVal(PBVAL vlp, PBVAL vp)
{
  vlp->To_Val = vp->To_Val;
  vlp->Nd = vp->Nd;
  vlp->Type = vp->Type;
} // end of SetValue;

PBVAL BJSON::SetValue(PBVAL vlp, PVAL valp)
{
  if (!vlp)
    vlp = NewVal();

  if (!valp || valp->IsNull()) {
    vlp->Type = TYPE_NULL;
  } else switch (valp->GetType()) {
    case TYPE_DATE:
      if (((DTVAL*)valp)->IsFormatted())
        vlp->To_Val = DupStr(valp->GetCharValue());
      else {
        char buf[32];

        vlp->To_Val = DupStr(valp->GetCharString(buf));
      }	// endif Formatted

      vlp->Type = TYPE_DTM;
      break;
    case TYPE_STRING:
      vlp->To_Val = DupStr(valp->GetCharValue());
      vlp->Type = TYPE_STRG;
      break;
    case TYPE_DOUBLE:
    case TYPE_DECIM:
    { double d = valp->GetFloatValue();
      int    nd = (IsTypeNum(valp->GetType())) ? valp->GetValPrec() : 0;

      if (nd > 0 && nd <= 6 && d >= FLT_MIN && d <= FLT_MAX) {
        vlp->F = (float)valp->GetFloatValue();
        vlp->Type = TYPE_FLOAT;
      } else {
        double* dp = (double*)BsonSubAlloc(sizeof(double));

        *dp = d;
        vlp->To_Val = MOF(dp);
        vlp->Type = TYPE_DBL;
      } // endif Nd

      vlp->Nd = MY_MIN(nd, 16);
    } break;
    case TYPE_TINY:
      vlp->B = valp->GetTinyValue() != 0;
      vlp->Type = TYPE_BOOL;
      break;
    case TYPE_INT:
      vlp->N = valp->GetIntValue();
      vlp->Type = TYPE_INTG;
      break;
    case TYPE_BIGINT:
      if (valp->GetBigintValue() >= INT_MIN32 &&
        valp->GetBigintValue() <= INT_MAX32) {
        vlp->N = valp->GetIntValue();
        vlp->Type = TYPE_INTG;
      } else {
        longlong* llp = (longlong*)BsonSubAlloc(sizeof(longlong));

        *llp = valp->GetBigintValue();
        vlp->To_Val = MOF(llp);
        vlp->Type = TYPE_BINT;
      } // endif BigintValue

      break;
    default:
      snprintf(G->Message, sizeof(G->Message), "Unsupported typ %d\n", valp->GetType());
      throw(777);
  } // endswitch Type

  return vlp;
} // end of SetValue

/***********************************************************************/
/* Set the Value's value as the given integer.                         */
/***********************************************************************/
void BJSON::SetInteger(PBVAL vlp, int n)
{
  vlp->N = n;
  vlp->Type = TYPE_INTG;
} // end of SetInteger

/***********************************************************************/
/* Set the Value's Boolean value as a tiny integer.                    */
/***********************************************************************/
void BJSON::SetBool(PBVAL vlp, bool b)
{
  vlp->B = b;
  vlp->Type = TYPE_BOOL;
} // end of SetTiny

/***********************************************************************/
/* Set the Value's value as the given big integer.                     */
/***********************************************************************/
void BJSON::SetBigint(PBVAL vlp, longlong ll)
{
  if (ll >= INT_MIN32 && ll <= INT_MAX32) {
    vlp->N = (int)ll;
    vlp->Type = TYPE_INTG;
  } else {
    longlong* llp = (longlong*)PlugSubAlloc(G, NULL, sizeof(longlong));

    *llp = ll;
    vlp->To_Val = MOF(llp);
    vlp->Type = TYPE_BINT;
  } // endif ll

} // end of SetBigint

/***********************************************************************/
/* Set the Value's value as the given DOUBLE.                          */
/***********************************************************************/
void BJSON::SetFloat(PBVAL vlp, double d, int prec)
{
  int nd = MY_MIN((prec < 0) ? GetJsonDefPrec() : prec, 16);

  if (nd < 6 && d >= FLT_MIN && d <= FLT_MAX) {
    vlp->F = (float)d;
    vlp->Type = TYPE_FLOAT;
  } else {
    double* dp = (double*)BsonSubAlloc(sizeof(double));

    *dp = d;
    vlp->To_Val = MOF(dp);
    vlp->Type = TYPE_DBL;
  } // endif nd

  vlp->Nd = nd;
} // end of SetFloat

/***********************************************************************/
/* Set the Value's value as the given DOUBLE representation.                          */
/***********************************************************************/
void BJSON::SetFloat(PBVAL vlp, PSZ s)
{
  char  *p = strchr(s, '.');
  int    nd = 0;
  double d = atof(s);

  if (p) {
    for (++p; isdigit(*p); nd++, p++);
    for (--p; *p == '0'; nd--, p--);
  } // endif p

  SetFloat(vlp, d, nd);
} // end of SetFloat

 /***********************************************************************/
/* Set the Value's value as the given string.                          */
/***********************************************************************/
void BJSON::SetString(PBVAL vlp, PSZ s, int ci)
{
  vlp->To_Val = MOF(s);
  vlp->Nd = ci;
  vlp->Type = TYPE_STRG;
} // end of SetString

/***********************************************************************/
/* True when its JSON or normal value is null.                         */
/***********************************************************************/
bool BJSON::IsValueNull(PBVAL vlp)
{
  bool b;

  switch (vlp->Type) {
  case TYPE_NULL:
    b = true;
    break;
  case TYPE_JOB:
    b = IsObjectNull(vlp);
    break;
  case TYPE_JAR:
    b = IsArrayNull(vlp);
    break;
  default:
    b = false;
  } // endswitch Type

  return b;
  } // end of IsNull