VDSObjectParser.cpp 23.6 KB
Newer Older
1
2
#include "VDSObjectParser.h"
#include "Base64.h"
Jørgen Lind's avatar
Jørgen Lind committed
3
#include "CompilerDefines.h"
4
5
#include <sstream>
#include <locale.h>
6
#include <stdint.h>
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

#include <fmt/format.h>

#ifdef _WIN32
typedef _locale_t locale_t;
#define strtod_l _strtod_l
#define strtof_l _strtof_l
#define strtoll  _strtoi64
#define strtoull _strtoui64
#endif

static locale_t &
GetCLocale()
{
#ifdef _WIN32
  static locale_t hCLocale = _create_locale(LC_CTYPE, "C");
#else
  static locale_t hCLocale = newlocale(LC_CTYPE_MASK, "C", NULL);
#endif
  return hCLocale;
}

bool InitializeParser(const char * vdsFileName, Parser **parser, const char * parseString = "")
{
  *parser = new Parser();

  if (strlen(parseString) == 0)
  {
    return (*parser)->ReadSerializedVDSObject(vdsFileName);
  }
  else
  {
    (*parser)->setBuffer(parseString);
  }

  return true;
}

bool ParseVDS(Parser **parser)
{
  if (*parser == nullptr)
  {
    return false;
  }
  const char *buffer = (*parser)->getBuffer();
  if (buffer == nullptr)
  {
    return false;
  }
  return VDSObj((*parser)->getParserState(), &buffer, *(*(parser))->getRoot());
}

bool Parser::ReadSerializedVDSObject(const char *vdsFileName)
{
  HueBulkDataStore * dataStore = nullptr;
  HueBulkDataStore::FileInterface *fileInterface = nullptr;

  dataStore = HueBulkDataStore::Open(vdsFileName);
  if (dataStore == nullptr)
  {
    return false;
  }

  fileInterface = dataStore->OpenFile("VDSObject");
  if (fileInterface == NULL)
  {
    HueBulkDataStore::Close(dataStore);
    return false;
  }

  chunkBuffer = fileInterface->ReadChunkData(0);

  if (chunkBuffer == nullptr || chunkBuffer->Size() == 0)
  {
    HueBulkDataStore::Close(dataStore);
    return false;
  }

  if (dataStore != nullptr)
  {
    HueBulkDataStore::Close(dataStore);
  }
  return true;
}

void DeInitializeParser(Parser **parser)
{
  if (*parser != nullptr)
  {
    delete (*parser);
  }
}

size_t GetVDSObjectJsonString(const Parser *parser, char *jsonStringBuffer, size_t bufferSize)
{
  Json::StreamWriterBuilder swb;
  swb["commentStyle"] = "None";
  swb["indentation"] = " ";
  Json::StreamWriter *writer = swb.newStreamWriter();
  std::ostringstream oss;
  writer->write(*parser->getRoot(), &oss);

  if (jsonStringBuffer)
  {
    strncpy(jsonStringBuffer, oss.str().c_str(), bufferSize);
  }

  return oss.str().size();
}

Json::Value TranslateVolumeDataLayoutDescriptor(Json::Value const & root)
{
  int brickSize = 0;
  sscanf(root["FullVCSize"].asCString(), "HUEVCSIZE_%d", &brickSize);

  int lodLevels = 0;
  sscanf(root["LODLevels"].asCString(), "LODLevel%d", &lodLevels);

  Json::Value layoutDescriptorJson;

  layoutDescriptorJson["brickSize"] = fmt::format("BrickSize_{}", brickSize);
  layoutDescriptorJson["negativeMargin"] = root["NegativeMargin"].asInt();
  layoutDescriptorJson["positiveMargin"] = root["PositiveMargin"].asInt();
  layoutDescriptorJson["brickSize2DMultiplier"] = 4; // FIXME: Check if object type is VDSSpread and set to 1 in that case
  layoutDescriptorJson["lodLevels"] = (lodLevels == 0) ? std::string("LODLevels_None") : fmt::format("LODLevels_{}", lodLevels);
  layoutDescriptorJson["create2DLODs"] = (root["Create2DLODs"].asString() != "FALSE");
  layoutDescriptorJson["forceFullResolutionDimension"] = (root["ForceFullResolutionDimension"].asString() != "FALSE");
  layoutDescriptorJson["fullResolutionDimension"] = root["FullResolutionDimension"].asInt();
  return layoutDescriptorJson;
}

Json::Value TranslateAxisDescriptors(Json::Value const & root)
{
  int dimensionality = 0;
  sscanf(root["Dimensions"].asCString(), "HUEDIMENSION_%d", &dimensionality);

  Json::Value axisDescriptorsJson(Json::arrayValue);

  for(int dimension = 0; dimension < dimensionality; dimension++)
  {
    Json::Value axisDescriptorJson;

    axisDescriptorJson["numSamples"]    = root[fmt::format("Dimension{}Size", dimension)].asInt();
    axisDescriptorJson["name"]          = root[fmt::format("Dimension{}Name", dimension)].asString();
    axisDescriptorJson["unit"]          = root[fmt::format("Dimension{}Unit", dimension)].asString();
    axisDescriptorJson["coordinateMin"] = root[fmt::format("Dimension{}Coordinate", dimension)]["Min"].asFloat();
    axisDescriptorJson["coordinateMax"] = root[fmt::format("Dimension{}Coordinate", dimension)]["Max"].asFloat();

    axisDescriptorsJson.append(axisDescriptorJson);
  }

  return axisDescriptorsJson;
}

std::string TranslateVCVoxelFormat(std::string const &vcVoxelFormat)
{
  const char vcVoxelFormatPrefix[] = "HUEVOXELFORMAT_";
  const size_t prefixLength = sizeof(vcVoxelFormatPrefix) - 1;

  if(vcVoxelFormat.substr(0, prefixLength) == vcVoxelFormatPrefix)
  {
    std::string format = vcVoxelFormat.substr(prefixLength);
    return (format == "1BIT") ? std::string("Format_1Bit") : fmt::format("Format_{}", format);
  }

  assert(0 && "Illegal format"); return "";
}

Json::Value TranslateChannelDescriptor(Json::Value const & root, bool isPrimaryChannel)
{
  int components = 0;
  sscanf(root[isPrimaryChannel ? "VoxelComponents" : "Components"].asCString(), "HUEVOXELCOMPONENTS_%d", &components);

  Json::Value valueRangeJson(Json::arrayValue);

  valueRangeJson.append(root["ValueRange"]["Min"].asFloat());
  valueRangeJson.append(root["ValueRange"]["Max"].asFloat());

  Json::Value channelDescriptorJson;

  channelDescriptorJson["format"] = TranslateVCVoxelFormat(root[isPrimaryChannel ? "VoxelFormat" : "Format"].asString());
  channelDescriptorJson["components"] = fmt::format("Components_{}", components);
  channelDescriptorJson["name"] = root[isPrimaryChannel ? "ValueName" : "Name"].asString();
  channelDescriptorJson["unit"] = root[isPrimaryChannel ? "ValueUnit" : "Unit"].asString();
  channelDescriptorJson["valueRange"] = valueRangeJson;
  channelDescriptorJson["channelMapping"] = isPrimaryChannel ? "Direct" : (root["ChannelMapping"].asUInt64() == 1976800267773298824ULL ? "PerTrace" : "Direct");
  channelDescriptorJson["mappedValues"] = isPrimaryChannel ? 0 : root["MappedValues"].asInt();
  channelDescriptorJson["discrete"] = (root["DiscreteData"].asString() != "FALSE");
  channelDescriptorJson["renderable"] = isPrimaryChannel ? true : (root["Renderable"].asString() != "FALSE");
  channelDescriptorJson["allowLossyCompression"] = isPrimaryChannel ? !(root["DiscreteData"].asString() != "FALSE") : (root["AllowLossyCompression"].asString() != "FALSE");
  channelDescriptorJson["useNoValue"] = (root["UseNoValue"].asString() != "FALSE");
  channelDescriptorJson["noValue"] = root["NoValue"].asFloat();
  channelDescriptorJson["integerScale"] = root["IntegerScale"].asFloat();
  channelDescriptorJson["integerOffset"] = root["IntegerOffset"].asFloat();

  return channelDescriptorJson;
}

Json::Value TranslateChannelDescriptors(Json::Value const & root)
{
  Json::Value channelDescriptorsJson(Json::arrayValue);

  channelDescriptorsJson.append(TranslateChannelDescriptor(root, true));

  Json::Value volumeDataChannelDescriptorArray = root["VolumeDataChannelDescriptor"];

  if(volumeDataChannelDescriptorArray.isArray())
  {
    for(int channel = 0; channel < (int)volumeDataChannelDescriptorArray.size(); channel++)
    {
      channelDescriptorsJson.append(TranslateChannelDescriptor(volumeDataChannelDescriptorArray[channel], false));
    }
  }
  return channelDescriptorsJson;
}

int DecodeHexChar(char hexChar)
{
  return (hexChar >= '0' && hexChar <= '9') ? hexChar - '0' + 0   :
         (hexChar >= 'a' && hexChar <= 'f') ? hexChar - 'a' + 0xa :
         (hexChar >= 'A' && hexChar <= 'F') ? hexChar - 'A' + 0xA : -1;
}

bool HexStringDecode(const char *data, int64_t len, std::vector<unsigned char> &result)
{
  bool error = false;

  result.reserve(result.size() + len / 2);

  while(len > 0)
  {
    int hi = DecodeHexChar(*data++); len--; if(hi == -1 || len == 0) { error = true; break; }
    int lo = DecodeHexChar(*data++); len--; if(lo == -1            ) { error = true; break; }
    int value = (hi << 4) | (lo);
    result.push_back(value);
  }

  return !error;
}

Json::Value TranslateBLOB(Json::Value const & root)
{
  if(!root.isString()) return Json::Value();

  const char *str, *cend;
  root.getString(&str, &cend);

  std::vector<uint8_t> blob;
  HexStringDecode(str, cend - str, blob);

  std::vector<char> base64;
  Base64Encode(blob.data(), blob.size(), base64);

  return Json::Value(&base64[0], &base64[0] + base64.size());
}

Json::Value TranslateVector(Json::Value const & root)
{
  Json::Value vectorJson(Json::arrayValue);

  const char* element[] = { "X", "Y", "Z", "T" };

  int i = 0;
  switch(root.size())
  {
Jørgen Lind's avatar
Jørgen Lind committed
272
273
  case 4: vectorJson.append(root[element[i++]]); FALLTHROUGH;
  case 3: vectorJson.append(root[element[i++]]); FALLTHROUGH;
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
  case 2: vectorJson.append(root[element[i++]]);
          vectorJson.append(root[element[i++]]);
  }

  return vectorJson;
}

Json::Value TranslateMetadata(Json::Value const & root)
{
  Json::Value
    metadataListJson(Json::arrayValue);

  for(auto const & metadata : root["MetadataList"])
  {
    Json::Value
      metadataJson(Json::objectValue);

    metadataJson["type"] = metadata["Type"].asString();
    metadataJson["category"] = metadata["Category"].asString();
    metadataJson["name"] = metadata["Name"].asString();

    if(metadata["Type"].asString().find("Vector") != std::string::npos)
    {
      metadataJson["value"] = TranslateVector(metadata["Value"]);
    }
    else if(metadata["Type"].asString() == "BLOB")
    {
      metadataJson["value"] = TranslateBLOB(metadata["Value"]);
    }
    else // scalar or string value
    {
      metadataJson["value"] = metadata["Value"];
    }

    metadataListJson.append(metadataJson);
  }

  return metadataListJson;
}

Json::Value TranslateVolumeDataLayout(Json::Value const & root)
{
  Json::Value volumeDataLayoutJson;

  volumeDataLayoutJson["layoutDescriptor"] = TranslateVolumeDataLayoutDescriptor(root);
  volumeDataLayoutJson["axisDescriptors"] = TranslateAxisDescriptors(root);
  volumeDataLayoutJson["channelDescriptors"] = TranslateChannelDescriptors(root);
  volumeDataLayoutJson["metadata"] = TranslateMetadata(root);

  return volumeDataLayoutJson;
}

size_t GetVolumeDataLayoutJsonString(const Parser *parser, char *jsonStringBuffer, size_t bufferSize)
{
  std::vector<uint8_t>
    result;

  Json::StreamWriterBuilder wbuilder;
  wbuilder["indentation"] = "    ";
  std::string document = Json::writeString(wbuilder, TranslateVolumeDataLayout(*parser->getRoot()));

  // strip carriage return
  result.reserve(document.length());
  for(char c : document)
  {
    if(c != '\r')
    {
      result.push_back(c);
    }
  }

  if (jsonStringBuffer)
  {
    memcpy(jsonStringBuffer, result.data(), std::min(bufferSize, result.size()));
    if(result.size() < bufferSize)
    {
      // fill remaining space in buffer with zeroes to be compatible with snprintf/strncpy
      memset(jsonStringBuffer + result.size(), 0, bufferSize - result.size());
    }
  }

  return result.size();
}

bool ParserState::getNextToken(const char ** buffer)
{
  foundNumber = false;
  foundFractionalNumber = false;
  foundQuotedString = false;
  const char *pbuffer = *buffer;
  _tokenStart = nullptr;
  _tokenEnd = nullptr;

  while (isspace(*pbuffer))
  {
    pbuffer++;
  }

  if (*pbuffer)
  {
    _tokenStart = pbuffer;

    switch (*pbuffer)
    {
    case ':':
      pbuffer++;
      if (*pbuffer == ':')
      { // Namespace
        pbuffer++;
      }
      break;
      // Single character token
    case '{': case '}': case ',': case '.': case '=': case ';': case '|':
    case '!': case '#': case '%': case '&': case '/': case '(': case ')':
      pbuffer++;
      break;
      // Negative number or "->"
    case '-':
      if (pbuffer[1] == '>')
      {
        pbuffer += 2;
        break;
      }
Jørgen Lind's avatar
Jørgen Lind committed
397
      FALLTHROUGH;
398
399
400
401
402
403
404
    case '+':
      pbuffer++;

      if (!isdigit(*pbuffer))
      {
        break;
      }
Jørgen Lind's avatar
Jørgen Lind committed
405
      FALLTHROUGH;
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
      // Number
    case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
      foundNumber = true;

      while (isdigit(*pbuffer))
      {
        pbuffer++;
      }
      // Match fractional part
      if (*pbuffer == '.')
      {
        foundFractionalNumber = true;

        if (!isdigit(pbuffer[1]))
        {
          break;
        }
        pbuffer++;

        while (isdigit(*pbuffer))
        {
          pbuffer++;
        }
      }
      // Match exponent
      if (*pbuffer == 'E' || *pbuffer == 'e')
      {
        foundFractionalNumber = true;

        if (!isdigit(pbuffer[1]))
        {
          if ((pbuffer[1] == '+' || pbuffer[1] == '-') && isdigit(pbuffer[2]))
          {
            pbuffer++;
          }
          else
          {
            break;
          }
        }
        pbuffer++;

        while (isdigit(*pbuffer))
        {
          pbuffer++;
        }
      }
      break;
      // Quoted string
    case '\"':
      pbuffer++;
      while (*pbuffer != '\"')
      {
        if (*pbuffer == '\0' || (pbuffer[0] == '\\' && pbuffer[1] == '\0'))
        {
          foundQuotedString = false;
          return false;
        }
        else if (*pbuffer == '\\')
        {
          pbuffer++;
        }
        pbuffer++;
      }
      pbuffer++;
      foundQuotedString = true;
      break;
      // Alphanumeric string
    default:
      pbuffer++;
      while (isalpha(*pbuffer) || isdigit(*pbuffer) || *pbuffer == '_' || *pbuffer == '.' || *pbuffer == '[' || *pbuffer == ']')
      {
        pbuffer++;
      }
      break;
    }
    _tokenEnd = pbuffer;
    *buffer = pbuffer;
    return true;
  }
  return false;
}


bool ParserState::matchTokenArray(const char* pToken)
{
  size_t nTokenLength = strlen(pToken);

  if ((size_t)(_tokenEnd - _tokenStart) == nTokenLength)
  {
    return strncmp(_tokenStart, pToken, nTokenLength) == 0;
  }

  return false;
}

bool ParserState::matchSingle(const char token)
{

  if (_tokenEnd == _tokenStart + 1)
  {
    if (_tokenStart[0] == token)
    {
      return true;
    }
  }

  return false;
}

bool ParserState::getAndMatchTokenArray(const char ** buffer, const char * pToken)
{
  return getNextToken(buffer) && matchTokenArray(pToken);
}

bool ParserState::getAndMatchSingleToken(const char ** buffer, const char  token)
{
  return getNextToken(buffer) && matchSingle(token);
}

// Context Free Grammar defined in Header. Each of the non-terminals in the grammar are defined as functions updating the ParserState 
// when parsing the buffer. The root is updated along the way. As a side-effect of parsing a JSON parse is constructed. This parse tree can
// subsequently be used to extract attributes using the [] notation. The JSON parse tree is constructed using the primitives and helpers from the jsoncpp 
// library (included as cpp/h).

bool VDSObj(ParserState *ps, const char **buffer, Json::Value &root)
{
  if (!ps->getNextToken(buffer))
  {
    return false;
  }
  if (ps->matchTokenArray(CREATEOBJECT))
  {
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    bool isChildKeySet = false;
    if (!ObjectDescription(ps, buffer, isChildKeySet, root, true))
    {
      return false;
    }
    return  MainObjectBody(ps, buffer, root);
  }
  return false;
}

bool MainObjectBody(ParserState *ps, const char **buffer, Json::Value &root)
{
  if (!ps->getNextToken(buffer))
  {
    return false;
  }
  if (!ps->matchSingle('{'))
  {
    return false;
  }

  if (!ps->getNextToken(buffer))
  {
    return false;
  }

  if (ps->matchSingle('}'))
  {
    return true;
  }

  else if (!SubBody(ps, buffer, root))
  {
    return false;
  }

  if (!ps->matchSingle('}'))
  {
    return false;
  }

  return true;
}

bool ObjectDescription(ParserState *ps, const char **buffer, bool &childKeySet, Json::Value &root, bool extractPersistentID)
{
  if (!ps->matchSingle('('))
  {
    return false;
  }
  if (!ps->getNextToken(buffer))
  {
    return false;
  }
  if (!ObjTypeName(ps, buffer))
  {
    return false;
  }
  if (!ps->getAndMatchSingleToken(buffer, ','))
  {
    return false;
  }
  if (!ps->getNextToken(buffer))
  {
    return false;
  }
  if (!ChildListName(ps, buffer))
  {
    return false;
  }

  // Root token
  ps->extractKey();
  if (strcmp(ps->getKey(), "") != 0)
  {
    childKeySet = true;
  }

  if (!ps->getAndMatchSingleToken(buffer, ','))
  {
    return false;
  }
  if (!ps->getNextToken(buffer))
  {
    return false;
  }
  if (!Id(ps, buffer, root, extractPersistentID))
  {
    return false;
  }
  if (!ps->getAndMatchSingleToken(buffer, ')'))
  {
    return false;
  }
  return true;
}

bool SubBody(ParserState *ps, const char **buffer, Json::Value & root)
{
  if (ps->matchTokenArray(CREATEOBJECT))
  {
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    bool childKeySet = false;
    if (!ObjectDescription(ps, buffer, childKeySet, root))
    {
      return false;
    }
    if (childKeySet)
    {
      if (!parseChildCreateObj(ps, buffer, root))
      {
        return false;
      }
    }
    else
    {
      if (!KeyValueBody(ps, buffer, root))
      {
        return false;
      }
    }
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    return SubBody(ps, buffer, root);
  }
  else if (KeyValue(ps, buffer, root))
  {
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    if (ps->matchSingle('}'))
    {
      return true;
    }

    return SubBody(ps, buffer, root);
  }

  return true;
}

bool parseChildCreateObj(ParserState *ps, const char **buffer, Json::Value &root)
{
692
  std::vector<char> key(ps->getKey(), ps->getKey() + strlen(ps->getKey()) + 1);
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

  if (ps->getObjectRoot().find(&key[0], &key[0] + strlen(&key[0])) == NULL)
  {
    ps->getObjectRoot()[ps->getKey()] = Json::arrayValue;
  }

  Json::Value parsedValue = Json::objectValue;
  if (!KeyValueBody(ps, buffer, parsedValue))
  {
    return false;
  }
  else
  {
    ps->getObjectRoot()[&key[0]].append(parsedValue);
  }
  return true;
}

bool KeyValueBody(ParserState *ps, const char **buffer, Json::Value &root)
{
  if (!ps->getNextToken(buffer))
  {
    return false;
  }
  if (!ps->matchSingle('{'))
  {
    return false;
  }

  if (!ps->getNextToken(buffer))
  {
    return false;
  }

  if (ps->matchSingle('}'))
  {
    return true;
  }

  KeyValueSeq(ps, buffer, root);


  if (!ps->matchSingle('}'))
  {
    return false;
  }

  return true;
}

bool KeyValue(ParserState *ps, const char **buffer, Json::Value &root)
{
  if (LeftName(ps, buffer))
  {
    ps->extractKey();

    if (!ps->getNextToken(buffer))
    {
      return false;
    }

    if (ps->matchSingle('='))
    {
      if (!ps->getNextToken(buffer))
      {
        return false;
      }
      if (!Value(ps, buffer, root))
      {
        return false;
      }
      if (!ps->getNextToken(buffer))
      {
        return false;
      }
      return ps->matchSingle(';');
    }
    else if (ps->matchSingle(':'))
    {
      if (!ps->getNextToken(buffer))
      {
        return false;
      }
      if (!SubObject(ps, buffer, root))
      {
        return false;
      }
      return true;
    }
    else
    {
      return false;
    }
  }
  else
  {
    return false;
  }

  return true;
}

bool KeyValueSeq(ParserState *ps, const char ** buffer, Json::Value & root)
{
  // This funtion will only return false if there is an error getting the next token.
  // According to the grammar, this function is called when matching a SUBOBJECT non-terminal and is 
  // always followed by a match of '}'.
  while (KeyValue(ps, buffer, root))
  {
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
  }
  return true;
}


bool LeftName(ParserState *ps, const char **buffer)
{
  const char *pc = ps->getTokenStart();
  while (pc != ps->getTokenEnd())
  {
    if (isalpha(*pc) || isdigit(*pc) || *pc == '_')
    {
      pc++;
      continue;
    }
    return false;
  }

  return true;
}


bool SubObject(ParserState *ps, const char ** buffer, Json::Value &root)
{
  if (!ps->matchSingle('{'))
  {
    return false;
  }

  if (!ps->getNextToken(buffer))
  {
    return false;
  }

  long long n = PositiveNumber(ps, buffer);
  if (n > 0)
  {
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    if (!ps->matchSingle(','))
    {
      return false;
    }

    std::vector<char> arrayKey;
    if (strcmp(ps->getKey(), "") != 0)
    {
      root[ps->getKey()] = Json::arrayValue;
      size_t length = strlen(ps->getKey());
      arrayKey.resize(length + 1);
      memset(&arrayKey[0], 0, length + 1);
      strncpy(&arrayKey[0], ps->getKey(), length);
    }
    int i = 0;
    while (n > 0)
    {
      if (!ps->getNextToken(buffer))
      {
        return false;
      }
      if (!ps->matchSingle('{'))
      {
        return false;
      }
      if (!ps->getNextToken(buffer))
      {
        return false;
      }

      KeyValueSeq(ps, buffer, root[&arrayKey[0]][i++]);

      if (!ps->matchSingle('}'))
      {
        return false;
      }
      if (n != 1)
      {
        if (!ps->getAndMatchSingleToken(buffer, ','))
        {
          return false;
        }
      }
      n -= 1;
    }
    if (n > 0)
    {
      return false;
    }
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    if (!ps->matchSingle('}'))
    {
      return false;
    }
  }
  else
  {
    if (strcmp(ps->getKey(), "") != 0)
    {
      root[ps->getKey()] = Json::objectValue;
    }

    KeyValueSeq(ps, buffer, root[ps->getKey()]);
    if (!ps->matchSingle('}'))
    {
      return false;
    }
  }
  return true;
}

bool Value(ParserState *ps, const char ** buffer, Json::Value &root)
{
  return BLOBValue(ps, buffer, root) || PNNumber(ps, buffer, root) || QuotedString(ps, buffer, root);
}

bool PNNumber(ParserState *ps, const char ** buffer, Json::Value &root)
{
  bool parseRet = ps->isTokenNumber();
  if (parseRet)
  {
    ps->extractStringVal();
    if(ps->isTokenFractionalNumber())
    {
      root[ps->getKey()] = Json::Value(strtod_l(ps->getStringVal(), NULL, GetCLocale()));
    }
    else
    {
      if(ps->getStringVal()[0] == '-' || ps->getStringVal()[0] == '+')
      {
940
        root[ps->getKey()] = Json::Value((int64_t)strtoll(ps->getStringVal(), NULL, 10));
941
942
943
      }
      else
      {
944
        root[ps->getKey()] = Json::Value((uint64_t)strtoull(ps->getStringVal(), NULL, 10));
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
      }
    }
  }
  return parseRet;
}

bool QuotedString(ParserState *ps, const char **buffer, Json::Value &root)
{
  bool parseRet = ps->isTokenQuotedString();
  if (parseRet)
  {
    ps->extractStringVal();
    root[ps->getKey()] = Json::Value(ps->getStringVal());
  }
  return parseRet;
}

bool BLOBValue(ParserState *ps, const char **buffer, Json::Value &root)
{
  if (ps->matchSingle('N') && *(buffer[0]) == ':')
  {
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    if (!ps->matchSingle(':'))
    {
      return false;
    }
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    long long skipBytes = PositiveNumber(ps, buffer) * 2;
    if (skipBytes < 0)
    {
      return false;
    }
    if (!ps->getNextToken(buffer))
    {
      return false;
    }
    if (!ps->matchSingle(':'))
    {
      return false;
    }
    if (skipBytes == 0)
    {
      return true;
    }

    root[ps->getKey()] = Json::Value(std::string(*buffer, skipBytes));
    *buffer += skipBytes;

    return true;
  }
For faster browsing, not all history is shown. View entire blame