OVR_JSON.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. /************************************************************************************
  2. PublicHeader: None
  3. Filename : OVR_JSON.h
  4. Content : JSON format reader and writer
  5. Created : April 9, 2013
  6. Author : Brant Lewis
  7. Notes :
  8. The code is a derivative of the cJSON library written by Dave Gamble and subject
  9. to the following permissive copyright.
  10. Copyright (c) 2009 Dave Gamble
  11. Permission is hereby granted, free of charge, to any person obtaining a copy
  12. of this software and associated documentation files (the "Software"), to deal
  13. in the Software without restriction, including without limitation the rights
  14. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. copies of the Software, and to permit persons to whom the Software is
  16. furnished to do so, subject to the following conditions:
  17. The above copyright notice and this permission notice shall be included in
  18. all copies or substantial portions of the Software.
  19. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. THE SOFTWARE.
  26. Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved.
  27. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
  28. you may not use the Oculus VR Rift SDK except in compliance with the License,
  29. which is provided at the time of installation or download, or which
  30. otherwise accompanies this software in either electronic or hard copy form.
  31. You may obtain a copy of the License at
  32. http://www.oculusvr.com/licenses/LICENSE-3.2
  33. Unless required by applicable law or agreed to in writing, the Oculus VR SDK
  34. distributed under the License is distributed on an "AS IS" BASIS,
  35. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36. See the License for the specific language governing permissions and
  37. limitations under the License.
  38. ************************************************************************************/
  39. #include <string.h>
  40. #include <stdio.h>
  41. #include <math.h>
  42. #include <stdlib.h>
  43. #include <float.h>
  44. #include <limits.h>
  45. #include <ctype.h>
  46. #include "OVR_JSON.h"
  47. #include "OVR_SysFile.h"
  48. #include "OVR_Log.h"
  49. namespace OVR {
  50. //-----------------------------------------------------------------------------
  51. // Create a new copy of a string
  52. static char* JSON_strdup(const char* str)
  53. {
  54. size_t len = OVR_strlen(str) + 1;
  55. char* copy = (char*)OVR_ALLOC(len);
  56. if (!copy)
  57. return 0;
  58. memcpy(copy, str, len);
  59. return copy;
  60. }
  61. //-----------------------------------------------------------------------------
  62. // Render the number from the given item into a string.
  63. static char* PrintInt(int valueint)
  64. {
  65. char *str;
  66. str = (char*)OVR_ALLOC(21); // 2^64+1 can be represented in 21 chars.
  67. if (str)
  68. {
  69. OVR_sprintf(str, 21, "%d", valueint);
  70. }
  71. return str;
  72. }
  73. //-----------------------------------------------------------------------------
  74. // Render the number from the given item into a string.
  75. static char* PrintNumber(double d)
  76. {
  77. char *str;
  78. int valueint = (int)d;
  79. if ((fabs(((double)valueint)-d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
  80. {
  81. return PrintInt(valueint);
  82. }
  83. else
  84. {
  85. const size_t kCapacity = 64;
  86. str=(char*)OVR_ALLOC(kCapacity); // This is a nice tradeoff.
  87. if (str)
  88. {
  89. // The JSON Standard, section 7.8.3, specifies that decimals are always expressed with '.' and
  90. // not some locale-specific decimal such as ',' or ' '. However, since we are using the C standard
  91. // library below to write a floating point number, we need to make sure that it's writing a '.'
  92. // and not something else. We can't change the locale (even temporarily) here, as it will affect
  93. // the whole process by default. That are compiler-specific ways to change this per-thread, but
  94. // below we implement the simple solution of simply fixing the decimal after the string was written.
  95. if ((fabs(floor(d)-d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
  96. OVR_sprintf(str, kCapacity, "%.0f", d);
  97. else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
  98. OVR_sprintf(str, kCapacity, "%e", d);
  99. else
  100. OVR_sprintf(str, kCapacity, "%f", d);
  101. // Convert any found ',' or ''' char to '.'. This will happen only if the locale was set to write a ','
  102. // instead of a '.' for the decimal point. Decimal points are represented only by one of these
  103. // three characters in practice.
  104. for(char* p = str; *p; p++)
  105. {
  106. if((*p == ',') || (*p == '\''))
  107. {
  108. *p = '.';
  109. break;
  110. }
  111. }
  112. }
  113. }
  114. return str;
  115. }
  116. // Parse the input text into an un-escaped cstring, and populate item.
  117. static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  118. // Helper to assign error sting and return 0.
  119. const char* AssignError(const char** perror, const char *errorMessage)
  120. {
  121. if (perror)
  122. *perror = errorMessage;
  123. return 0;
  124. }
  125. //-----------------------------------------------------------------------------
  126. // ***** JSON Node class
  127. JSON::JSON(JSONItemType itemType) :
  128. Type(itemType), dValue(0.)
  129. {
  130. }
  131. JSON::~JSON()
  132. {
  133. JSON* child = Children.GetFirst();
  134. while (!Children.IsNull(child))
  135. {
  136. child->RemoveNode();
  137. child->Release();
  138. child = Children.GetFirst();
  139. }
  140. }
  141. //-----------------------------------------------------------------------------
  142. // Parse the input text to generate a number, and populate the result into item
  143. // Returns the text position after the parsed number
  144. const char* JSON::parseNumber(const char *num)
  145. {
  146. const char* num_start = num;
  147. double n=0, scale=0;
  148. int subscale = 0,
  149. signsubscale = 1;
  150. bool positiveSign = true;
  151. const char decimalSeparator = '.'; // The JSON standard specifies that numbers use '.' regardless of locale.
  152. // Could use sscanf for this?
  153. if (*num == '-')
  154. {
  155. positiveSign = false;
  156. num++; // Has sign?
  157. }
  158. if (*num == '0')
  159. {
  160. num++; // is zero
  161. }
  162. if (*num>='1' && *num<='9')
  163. {
  164. do
  165. {
  166. n = (n*10.0) + (*num++ - '0');
  167. }
  168. while (*num>='0' && *num<='9'); // Number?
  169. }
  170. if ((*num=='.' || *num==decimalSeparator) && num[1]>='0' && num[1]<='9')
  171. {
  172. num++;
  173. do
  174. {
  175. n=(n*10.0)+(*num++ -'0');
  176. scale--;
  177. }
  178. while (*num>='0' && *num<='9'); // Fractional part?
  179. }
  180. if (*num=='e' || *num=='E') // Exponent?
  181. {
  182. num++;
  183. if (*num == '+')
  184. {
  185. num++;
  186. }
  187. else if (*num=='-')
  188. {
  189. signsubscale=-1;
  190. num++; // With sign?
  191. }
  192. while (*num >= '0' && *num <= '9')
  193. {
  194. subscale = (subscale * 10) + (*num++ - '0'); // Number?
  195. }
  196. }
  197. // Number = +/- number.fraction * 10^+/- exponent
  198. n *= pow(10.0, (scale + subscale*signsubscale));
  199. if (!positiveSign)
  200. {
  201. n = -n;
  202. }
  203. // Assign parsed value.
  204. Type = JSON_Number;
  205. dValue = n;
  206. Value.AssignString(num_start, num - num_start);
  207. return num;
  208. }
  209. // Parses a hex string up to the specified number of digits.
  210. // Returns the first character after the string.
  211. const char* ParseHex(unsigned* val, unsigned digits, const char* str)
  212. {
  213. *val = 0;
  214. for(unsigned digitCount = 0; digitCount < digits; digitCount++, str++)
  215. {
  216. unsigned v = *str;
  217. if ((v >= '0') && (v <= '9'))
  218. v -= '0';
  219. else if ((v >= 'a') && (v <= 'f'))
  220. v = 10 + v - 'a';
  221. else if ((v >= 'A') && (v <= 'F'))
  222. v = 10 + v - 'A';
  223. else
  224. break;
  225. *val = *val * 16 + v;
  226. }
  227. return str;
  228. }
  229. //-----------------------------------------------------------------------------
  230. // Parses the input text into a string item and returns the text position after
  231. // the parsed string
  232. const char* JSON::parseString(const char* str, const char** perror)
  233. {
  234. const char* ptr = str+1;
  235. const char* p;
  236. char* ptr2;
  237. char* out;
  238. int len=0;
  239. unsigned uc, uc2;
  240. if (*str!='\"')
  241. {
  242. return AssignError(perror, "Syntax Error: Missing quote");
  243. }
  244. while (*ptr!='\"' && *ptr && ++len)
  245. {
  246. if (*ptr++ == '\\') ptr++; // Skip escaped quotes.
  247. }
  248. // This is how long we need for the string, roughly.
  249. out=(char*)OVR_ALLOC(len+1);
  250. if (!out)
  251. return 0;
  252. ptr = str+1;
  253. ptr2= out;
  254. while (*ptr!='\"' && *ptr)
  255. {
  256. if (*ptr!='\\')
  257. {
  258. *ptr2++ = *ptr++;
  259. }
  260. else
  261. {
  262. ptr++;
  263. switch (*ptr)
  264. {
  265. case 'b': *ptr2++ = '\b'; break;
  266. case 'f': *ptr2++ = '\f'; break;
  267. case 'n': *ptr2++ = '\n'; break;
  268. case 'r': *ptr2++ = '\r'; break;
  269. case 't': *ptr2++ = '\t'; break;
  270. // Transcode utf16 to utf8.
  271. case 'u':
  272. // Get the unicode char.
  273. p = ParseHex(&uc, 4, ptr + 1);
  274. if (ptr != p)
  275. ptr = p - 1;
  276. if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0)
  277. break; // Check for invalid.
  278. // UTF16 surrogate pairs.
  279. if (uc>=0xD800 && uc<=0xDBFF)
  280. {
  281. if (ptr[1]!='\\' || ptr[2]!='u')
  282. break; // Missing second-half of surrogate.
  283. p= ParseHex(&uc2, 4, ptr + 3);
  284. if (ptr != p)
  285. ptr = p - 1;
  286. if (uc2<0xDC00 || uc2>0xDFFF)
  287. break; // Invalid second-half of surrogate.
  288. uc = 0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
  289. }
  290. len=4;
  291. if (uc<0x80)
  292. len=1;
  293. else if (uc<0x800)
  294. len=2;
  295. else if (uc<0x10000)
  296. len=3;
  297. ptr2+=len;
  298. switch (len)
  299. {
  300. case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  301. //no break, fall through
  302. case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  303. //no break
  304. case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  305. //no break
  306. case 1: *--ptr2 = (char)(uc | firstByteMark[len]);
  307. //no break
  308. }
  309. ptr2+=len;
  310. break;
  311. default:
  312. *ptr2++ = *ptr;
  313. break;
  314. }
  315. ptr++;
  316. }
  317. }
  318. *ptr2 = 0;
  319. if (*ptr=='\"')
  320. ptr++;
  321. // Make a copy of the string
  322. Value=out;
  323. OVR_FREE(out);
  324. Type=JSON_String;
  325. return ptr;
  326. }
  327. //-----------------------------------------------------------------------------
  328. // Render the string provided to an escaped version that can be printed.
  329. char* PrintString(const char* str)
  330. {
  331. const char *ptr;
  332. char *ptr2,*out;
  333. int len=0;
  334. unsigned char token;
  335. if (!str)
  336. return JSON_strdup("");
  337. ptr=str;
  338. token=*ptr;
  339. while (token && ++len)\
  340. {
  341. if (strchr("\"\\\b\f\n\r\t",token))
  342. len++;
  343. else if (token<32)
  344. len+=5;
  345. ptr++;
  346. token=*ptr;
  347. }
  348. int buff_size = len+3;
  349. out=(char*)OVR_ALLOC(buff_size);
  350. if (!out)
  351. return 0;
  352. ptr2 = out;
  353. ptr = str;
  354. *ptr2++ = '\"';
  355. while (*ptr)
  356. {
  357. if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\')
  358. *ptr2++=*ptr++;
  359. else
  360. {
  361. *ptr2++='\\';
  362. switch (token=*ptr++)
  363. {
  364. case '\\': *ptr2++='\\'; break;
  365. case '\"': *ptr2++='\"'; break;
  366. case '\b': *ptr2++='b'; break;
  367. case '\f': *ptr2++='f'; break;
  368. case '\n': *ptr2++='n'; break;
  369. case '\r': *ptr2++='r'; break;
  370. case '\t': *ptr2++='t'; break;
  371. default:
  372. OVR_sprintf(ptr2, buff_size - (ptr2-out), "u%04x",token);
  373. ptr2+=5;
  374. break; // Escape and print.
  375. }
  376. }
  377. }
  378. *ptr2++='\"';
  379. *ptr2++=0;
  380. return out;
  381. }
  382. //-----------------------------------------------------------------------------
  383. // Utility to jump whitespace and cr/lf
  384. static const char* skip(const char* in)
  385. {
  386. while (in && *in && (unsigned char)*in<=' ')
  387. in++;
  388. return in;
  389. }
  390. //-----------------------------------------------------------------------------
  391. // Parses the supplied buffer of JSON text and returns a JSON object tree
  392. // The returned object must be Released after use
  393. JSON* JSON::Parse(const char* buff, const char** perror)
  394. {
  395. const char* end = 0;
  396. JSON* json = new JSON();
  397. if (!json)
  398. {
  399. AssignError(perror, "Error: Failed to allocate memory");
  400. return 0;
  401. }
  402. end = json->parseValue(skip(buff), perror);
  403. if (!end)
  404. {
  405. json->Release();
  406. return NULL;
  407. } // parse failure. ep is set.
  408. return json;
  409. }
  410. //-----------------------------------------------------------------------------
  411. // This version works for buffers that are not null terminated strings.
  412. JSON* JSON::ParseBuffer(const char *buff, int len, const char** perror)
  413. {
  414. // Our JSON parser does not support length-based parsing,
  415. // so ensure it is null-terminated.
  416. char *termStr = new char[len + 1];
  417. memcpy(termStr, buff, len);
  418. termStr[len] = '\0';
  419. JSON *objJson = Parse(termStr, perror);
  420. delete[]termStr;
  421. return objJson;
  422. }
  423. //-----------------------------------------------------------------------------
  424. // Parser core - when encountering text, process appropriately.
  425. const char* JSON::parseValue(const char* buff, const char** perror)
  426. {
  427. if (perror)
  428. *perror = 0;
  429. if (!buff)
  430. return NULL; // Fail on null.
  431. if (!OVR_strncmp(buff, "null", 4))
  432. {
  433. Type = JSON_Null;
  434. return buff + 4;
  435. }
  436. if (!OVR_strncmp(buff, "false", 5))
  437. {
  438. Type = JSON_Bool;
  439. Value = "false";
  440. dValue = 0.;
  441. return buff + 5;
  442. }
  443. if (!OVR_strncmp(buff, "true", 4))
  444. {
  445. Type = JSON_Bool;
  446. Value = "true";
  447. dValue = 1.;
  448. return buff + 4;
  449. }
  450. if (*buff=='\"')
  451. {
  452. return parseString(buff, perror);
  453. }
  454. if (*buff=='-' || (*buff>='0' && *buff<='9'))
  455. {
  456. return parseNumber(buff);
  457. }
  458. if (*buff=='[')
  459. {
  460. return parseArray(buff, perror);
  461. }
  462. if (*buff=='{')
  463. {
  464. return parseObject(buff, perror);
  465. }
  466. return AssignError(perror, "Syntax Error: Invalid syntax");
  467. }
  468. //-----------------------------------------------------------------------------
  469. // Render a value to text.
  470. char* JSON::PrintValue(int depth, bool fmt)
  471. {
  472. char *out=0;
  473. switch (Type)
  474. {
  475. case JSON_Null: out = JSON_strdup("null"); break;
  476. case JSON_Bool:
  477. if ((int)dValue == 0)
  478. out = JSON_strdup("false");
  479. else
  480. out = JSON_strdup("true");
  481. break;
  482. case JSON_Number: out = PrintNumber(dValue); break;
  483. case JSON_String: out = PrintString(Value); break;
  484. case JSON_Array: out = PrintArray(depth, fmt); break;
  485. case JSON_Object: out = PrintObject(depth, fmt); break;
  486. case JSON_None: OVR_ASSERT_LOG(false, ("Bad JSON type.")); break;
  487. }
  488. return out;
  489. }
  490. //-----------------------------------------------------------------------------
  491. // Build an array object from input text and returns the text position after
  492. // the parsed array
  493. const char* JSON::parseArray(const char* buff, const char** perror)
  494. {
  495. JSON *child;
  496. if (*buff!='[')
  497. {
  498. return AssignError(perror, "Syntax Error: Missing opening bracket");
  499. }
  500. Type=JSON_Array;
  501. buff=skip(buff+1);
  502. if (*buff==']')
  503. return buff+1; // empty array.
  504. child = new JSON();
  505. if (!child)
  506. return 0; // memory fail
  507. Children.PushBack(child);
  508. buff=skip(child->parseValue(skip(buff), perror)); // skip any spacing, get the buff.
  509. if (!buff)
  510. return 0;
  511. while (*buff==',')
  512. {
  513. JSON *new_item = new JSON();
  514. if (!new_item)
  515. return AssignError(perror, "Error: Failed to allocate memory");
  516. Children.PushBack(new_item);
  517. buff=skip(new_item->parseValue(skip(buff+1), perror));
  518. if (!buff)
  519. return AssignError(perror, "Error: Failed to allocate memory");
  520. }
  521. if (*buff==']')
  522. return buff+1; // end of array
  523. return AssignError(perror, "Syntax Error: Missing ending bracket");
  524. }
  525. //-----------------------------------------------------------------------------
  526. // Render an array to text. The returned text must be freed
  527. char* JSON::PrintArray(int depth, bool fmt)
  528. {
  529. char ** entries;
  530. char * out = 0, *ptr,*ret;
  531. intptr_t len = 5;
  532. bool fail = false;
  533. // How many entries in the array?
  534. int numentries = GetItemCount();
  535. if (!numentries)
  536. {
  537. out=(char*)OVR_ALLOC(3);
  538. if (out)
  539. OVR_strcpy(out, 3, "[]");
  540. return out;
  541. }
  542. // Allocate an array to hold the values for each
  543. entries=(char**)OVR_ALLOC(numentries*sizeof(char*));
  544. if (!entries)
  545. return 0;
  546. memset(entries,0,numentries*sizeof(char*));
  547. //// Retrieve all the results:
  548. JSON* child = Children.GetFirst();
  549. for (int i=0; i<numentries; i++)
  550. {
  551. //JSON* child = Children[i];
  552. ret=child->PrintValue(depth+1, fmt);
  553. entries[i]=ret;
  554. if (ret)
  555. len+=OVR_strlen(ret)+2+(fmt?1:0);
  556. else
  557. {
  558. fail = true;
  559. break;
  560. }
  561. child = Children.GetNext(child);
  562. }
  563. // If we didn't fail, try to malloc the output string
  564. if (!fail)
  565. out=(char*)OVR_ALLOC(len);
  566. // If that fails, we fail.
  567. if (!out)
  568. fail = true;
  569. // Handle failure.
  570. if (fail)
  571. {
  572. for (int i=0; i<numentries; i++)
  573. {
  574. if (entries[i])
  575. OVR_FREE(entries[i]);
  576. }
  577. OVR_FREE(entries);
  578. return 0;
  579. }
  580. // Compose the output array.
  581. *out='[';
  582. ptr=out+1;
  583. *ptr=0;
  584. for (int i=0; i<numentries; i++)
  585. {
  586. OVR_strcpy(ptr, len - (ptr-out), entries[i]);
  587. ptr+=OVR_strlen(entries[i]);
  588. if (i!=numentries-1)
  589. {
  590. *ptr++=',';
  591. if (fmt)
  592. *ptr++=' ';
  593. *ptr=0;
  594. }
  595. OVR_FREE(entries[i]);
  596. }
  597. OVR_FREE(entries);
  598. *ptr++=']';
  599. *ptr++=0;
  600. return out;
  601. }
  602. //-----------------------------------------------------------------------------
  603. // Build an object from the supplied text and returns the text position after
  604. // the parsed object
  605. const char* JSON::parseObject(const char* buff, const char** perror)
  606. {
  607. if (*buff!='{')
  608. {
  609. return AssignError(perror, "Syntax Error: Missing opening brace");
  610. }
  611. Type=JSON_Object;
  612. buff=skip(buff+1);
  613. if (*buff=='}')
  614. return buff+1; // empty array.
  615. JSON* child = new JSON();
  616. Children.PushBack(child);
  617. buff=skip(child->parseString(skip(buff), perror));
  618. if (!buff)
  619. return 0;
  620. child->Name = child->Value;
  621. child->Value.Clear();
  622. if (*buff!=':')
  623. {
  624. return AssignError(perror, "Syntax Error: Missing colon");
  625. }
  626. buff=skip(child->parseValue(skip(buff+1), perror)); // skip any spacing, get the value.
  627. if (!buff)
  628. return 0;
  629. while (*buff==',')
  630. {
  631. child = new JSON();
  632. if (!child)
  633. return 0; // memory fail
  634. Children.PushBack(child);
  635. buff=skip(child->parseString(skip(buff+1), perror));
  636. if (!buff)
  637. return 0;
  638. child->Name=child->Value;
  639. child->Value.Clear();
  640. if (*buff!=':')
  641. {
  642. return AssignError(perror, "Syntax Error: Missing colon");
  643. } // fail!
  644. // Skip any spacing, get the value.
  645. buff=skip(child->parseValue(skip(buff+1), perror));
  646. if (!buff)
  647. return 0;
  648. }
  649. if (*buff=='}')
  650. return buff+1; // end of array
  651. return AssignError(perror, "Syntax Error: Missing closing brace");
  652. }
  653. //-----------------------------------------------------------------------------
  654. // Render an object to text. The returned string must be freed
  655. char* JSON::PrintObject(int depth, bool fmt)
  656. {
  657. char** entries = 0, **names = 0;
  658. char* out = 0;
  659. char* ptr, *ret, *str;
  660. intptr_t len = 7, i = 0, j;
  661. bool fail = false;
  662. // Count the number of entries.
  663. int numentries = GetItemCount();
  664. // Explicitly handle empty object case
  665. if (numentries == 0)
  666. {
  667. out=(char*)OVR_ALLOC(fmt?depth+4:4);
  668. if (!out)
  669. return 0;
  670. ptr=out;
  671. *ptr++='{';
  672. if (fmt)
  673. {
  674. #ifdef OVR_OS_WIN32
  675. *ptr++ = '\r';
  676. #endif
  677. *ptr++ = '\n';
  678. for (i=0;i<depth-1;i++)
  679. *ptr++='\t';
  680. }
  681. *ptr++='}';
  682. *ptr++=0;
  683. return out;
  684. }
  685. // Allocate space for the names and the objects
  686. entries=(char**)OVR_ALLOC(numentries*sizeof(char*));
  687. if (!entries)
  688. return 0;
  689. names=(char**)OVR_ALLOC(numentries*sizeof(char*));
  690. if (!names)
  691. {
  692. OVR_FREE(entries);
  693. return 0;
  694. }
  695. memset(entries,0,sizeof(char*)*numentries);
  696. memset(names,0,sizeof(char*)*numentries);
  697. // Collect all the results into our arrays:
  698. depth++;
  699. if (fmt)
  700. len+=depth;
  701. JSON* child = Children.GetFirst();
  702. while (!Children.IsNull(child))
  703. {
  704. names[i] = str = PrintString(child->Name);
  705. entries[i++] = ret = child->PrintValue(depth, fmt);
  706. if (str && ret)
  707. {
  708. len += OVR_strlen(ret)+OVR_strlen(str)+2+(fmt?3+depth:0);
  709. }
  710. else
  711. {
  712. fail = true;
  713. break;
  714. }
  715. child = Children.GetNext(child);
  716. }
  717. // Try to allocate the output string
  718. if (!fail)
  719. out=(char*)OVR_ALLOC(len);
  720. if (!out)
  721. fail=true;
  722. // Handle failure
  723. if (fail)
  724. {
  725. for (i=0;i<numentries;i++)
  726. {
  727. if (names[i])
  728. OVR_FREE(names[i]);
  729. if (entries[i])
  730. OVR_FREE(entries[i]);}
  731. OVR_FREE(names);
  732. OVR_FREE(entries);
  733. return 0;
  734. }
  735. // Compose the output:
  736. *out = '{';
  737. ptr = out+1;
  738. if (fmt)
  739. {
  740. #ifdef OVR_OS_WIN32
  741. *ptr++ = '\r';
  742. #endif
  743. *ptr++ = '\n';
  744. }
  745. *ptr = 0;
  746. for (i=0; i<numentries; i++)
  747. {
  748. if (fmt)
  749. {
  750. for (j = 0; j < depth; j++)
  751. {
  752. *ptr++ = '\t';
  753. }
  754. }
  755. OVR_strcpy(ptr, len - (ptr-out), names[i]);
  756. ptr += OVR_strlen(names[i]);
  757. *ptr++ =':';
  758. if (fmt)
  759. {
  760. *ptr++ = '\t';
  761. }
  762. OVR_strcpy(ptr, len - (ptr-out), entries[i]);
  763. ptr+=OVR_strlen(entries[i]);
  764. if (i != numentries - 1)
  765. {
  766. *ptr++ = ',';
  767. }
  768. if (fmt)
  769. {
  770. #ifdef OVR_OS_WIN32
  771. *ptr++ = '\r';
  772. #endif
  773. *ptr++ = '\n';
  774. }
  775. *ptr = 0;
  776. OVR_FREE(names[i]);
  777. OVR_FREE(entries[i]);
  778. }
  779. OVR_FREE(names);
  780. OVR_FREE(entries);
  781. if (fmt)
  782. {
  783. for (i = 0; i < depth - 1; i++)
  784. {
  785. *ptr++ = '\t';
  786. }
  787. }
  788. *ptr++='}';
  789. *ptr++=0;
  790. return out;
  791. }
  792. // Returns the number of child items in the object
  793. // Counts the number of items in the object.
  794. unsigned JSON::GetItemCount() const
  795. {
  796. unsigned count = 0;
  797. for (const JSON* p = Children.GetFirst(); !Children.IsNull(p); p = Children.GetNext(p))
  798. {
  799. count++;
  800. }
  801. return count;
  802. }
  803. JSON* JSON::GetItemByIndex(unsigned index)
  804. {
  805. unsigned i = 0;
  806. JSON* child = 0;
  807. if (!Children.IsEmpty())
  808. {
  809. child = Children.GetFirst();
  810. while (i < index)
  811. {
  812. if (Children.IsLast(child))
  813. {
  814. child = 0;
  815. break;
  816. }
  817. child = child->GetNext();
  818. i++;
  819. }
  820. }
  821. return child;
  822. }
  823. // Returns the child item with the given name or NULL if not found
  824. JSON* JSON::GetItemByName(const char* name)
  825. {
  826. JSON* child = 0;
  827. if (!Children.IsEmpty())
  828. {
  829. child = Children.GetFirst();
  830. while (OVR_strcmp(child->Name, name) != 0)
  831. {
  832. if (Children.IsLast(child))
  833. {
  834. child = 0;
  835. break;
  836. }
  837. child = child->GetNext();
  838. }
  839. }
  840. return child;
  841. }
  842. //-----------------------------------------------------------------------------
  843. // Adds a new item to the end of the child list
  844. void JSON::AddItem(const char *string, JSON *item)
  845. {
  846. if (item)
  847. {
  848. item->Name = string;
  849. Children.PushBack(item);
  850. }
  851. }
  852. /*
  853. // Removes and frees the items at the given index
  854. void JSON::DeleteItem(unsigned int index)
  855. {
  856. unsigned int num_items = 0;
  857. JSON* child = Children.GetFirst();
  858. while (!Children.IsNull(child) && num_items < index)
  859. {
  860. num_items++;
  861. child = Children.GetNext(child);
  862. }
  863. if (!Children.IsNull(child))
  864. child->RemoveNode();
  865. child->Release();
  866. }
  867. }
  868. // Replaces and frees the item at the give index with the new item
  869. void JSON::ReplaceItem(unsigned int index, JSON* new_item)
  870. {
  871. unsigned int num_items = 0;
  872. JSON* child = Children.GetFirst();
  873. while (!Children.IsNull(child) && num_items < index)
  874. {
  875. num_items++;
  876. child = Children.GetNext(child);
  877. }
  878. if (!Children.IsNull(child))
  879. {
  880. child->ReplaceNodeWith(new_item);
  881. child->Release();
  882. }
  883. }
  884. */
  885. // Removes and frees the last child item
  886. void JSON::RemoveLast()
  887. {
  888. JSON* child = Children.GetLast();
  889. if (!Children.IsNull(child))
  890. {
  891. child->RemoveNode();
  892. child->Release();
  893. }
  894. }
  895. JSON* JSON::CreateBool(bool b)
  896. {
  897. JSON *item = new JSON(JSON_Bool);
  898. if (item)
  899. {
  900. item->dValue = b ? 1. : 0.;
  901. item->Value = b ? "true" : "false";
  902. }
  903. return item;
  904. }
  905. JSON* JSON::CreateNumber(double num)
  906. {
  907. JSON *item = new JSON(JSON_Number);
  908. if (item)
  909. {
  910. item->dValue = num;
  911. }
  912. return item;
  913. }
  914. JSON* JSON::CreateInt(int num)
  915. {
  916. JSON *item = new JSON(JSON_Number);
  917. if (item)
  918. {
  919. item->dValue = num;
  920. }
  921. return item;
  922. }
  923. JSON* JSON::CreateString(const char *s)
  924. {
  925. JSON *item = new JSON(JSON_String);
  926. if (item && s)
  927. {
  928. item->Value = s;
  929. }
  930. return item;
  931. }
  932. //-----------------------------------------------------------------------------
  933. // Get elements by name
  934. double JSON::GetNumberByName(const char *name, double defValue)
  935. {
  936. JSON* item = GetItemByName(name);
  937. if (!item || item->Type != JSON_Number)
  938. {
  939. return defValue;
  940. }
  941. else
  942. {
  943. return item->dValue;
  944. }
  945. }
  946. int JSON::GetIntByName(const char *name, int defValue)
  947. {
  948. JSON* item = GetItemByName(name);
  949. if (!item || item->Type != JSON_Number)
  950. {
  951. return defValue;
  952. }
  953. else
  954. {
  955. return (int)item->dValue;
  956. }
  957. }
  958. bool JSON::GetBoolByName(const char *name, bool defValue)
  959. {
  960. JSON* item = GetItemByName(name);
  961. if (!item || item->Type != JSON_Bool)
  962. {
  963. return defValue;
  964. }
  965. else
  966. {
  967. return (int)item->dValue != 0;
  968. }
  969. }
  970. String JSON::GetStringByName(const char *name, const String &defValue)
  971. {
  972. JSON* item = GetItemByName(name);
  973. if (!item || item->Type != JSON_String)
  974. {
  975. return defValue;
  976. }
  977. else
  978. {
  979. return item->Value;
  980. }
  981. }
  982. int JSON::GetArrayByName(const char *name, double values[], int count)
  983. {
  984. JSON* array = GetItemByName(name);
  985. if (!array || array->Type != JSON_Array)
  986. return 0;
  987. int i = 0;
  988. for (JSON* child = array->Children.GetFirst(); !array->Children.IsNull(child); child = array->Children.GetNext(child))
  989. {
  990. if (i >= count)
  991. break;
  992. values[i++] = child->dValue;
  993. }
  994. OVR_ASSERT(i <= count);
  995. return i;
  996. }
  997. //-----------------------------------------------------------------------------
  998. // Adds an element to an array object type
  999. void JSON::AddArrayElement(JSON *item)
  1000. {
  1001. if (item)
  1002. {
  1003. Children.PushBack(item);
  1004. }
  1005. }
  1006. // Inserts an element into a valid array position
  1007. void JSON::InsertArrayElement(int index, JSON *item)
  1008. {
  1009. if (!item)
  1010. {
  1011. return;
  1012. }
  1013. if (index == 0)
  1014. {
  1015. Children.PushFront(item);
  1016. return;
  1017. }
  1018. JSON* iter = Children.GetFirst();
  1019. int i=0;
  1020. while (iter && i<index)
  1021. {
  1022. iter = Children.GetNext(iter);
  1023. i++;
  1024. }
  1025. if (iter)
  1026. iter->InsertNodeBefore(item);
  1027. else
  1028. Children.PushBack(item);
  1029. }
  1030. // Returns the size of an array
  1031. int JSON::GetArraySize()
  1032. {
  1033. if (Type == JSON_Array)
  1034. {
  1035. return GetItemCount();
  1036. }
  1037. return 0;
  1038. }
  1039. // Returns the number value an the give array index
  1040. double JSON::GetArrayNumber(int index)
  1041. {
  1042. if (Type == JSON_Array)
  1043. {
  1044. JSON* number = GetItemByIndex(index);
  1045. return number ? number->dValue : 0.0;
  1046. }
  1047. return 0;
  1048. }
  1049. // Returns the string value at the given array index
  1050. const char* JSON::GetArrayString(int index)
  1051. {
  1052. if (Type == JSON_Array)
  1053. {
  1054. JSON* number = GetItemByIndex(index);
  1055. return number ? number->Value : 0;
  1056. }
  1057. return 0;
  1058. }
  1059. JSON* JSON::Copy()
  1060. {
  1061. JSON* copy = new JSON(Type);
  1062. copy->Name = Name;
  1063. copy->Value = Value;
  1064. copy->dValue = dValue;
  1065. JSON* child = Children.GetFirst();
  1066. while (!Children.IsNull(child))
  1067. {
  1068. copy->Children.PushBack(child->Copy());
  1069. child = Children.GetNext(child);
  1070. }
  1071. return copy;
  1072. }
  1073. char* JSON::PrintValue(bool fmt)
  1074. {
  1075. return PrintValue(0, fmt);
  1076. }
  1077. //-----------------------------------------------------------------------------
  1078. // Loads and parses the given JSON file pathname and returns a JSON object tree.
  1079. // The returned object must be Released after use.
  1080. JSON* JSON::Load(const char* path, const char** perror)
  1081. {
  1082. SysFile f;
  1083. if (!f.Open(path, File::Open_Read, File::Mode_Read))
  1084. {
  1085. AssignError(perror, "Failed to open file");
  1086. return NULL;
  1087. }
  1088. int len = f.GetLength();
  1089. uint8_t* buff = (uint8_t*)OVR_ALLOC(len + 1);
  1090. int bytes = f.Read(buff, len);
  1091. f.Close();
  1092. if (bytes == 0 || bytes != len)
  1093. {
  1094. OVR_FREE(buff);
  1095. return NULL;
  1096. }
  1097. // Ensure the result is null-terminated since Parse() expects null-terminated input.
  1098. buff[len] = '\0';
  1099. JSON* json = JSON::Parse((char*)buff, perror);
  1100. OVR_FREE(buff);
  1101. return json;
  1102. }
  1103. //-----------------------------------------------------------------------------
  1104. // Serializes the JSON object and writes to the give file path
  1105. bool JSON::Save(const char* path)
  1106. {
  1107. SysFile f;
  1108. if (!f.Open(path, File::Open_Write | File::Open_Create | File::Open_Truncate, File::Mode_Write))
  1109. return false;
  1110. char* text = PrintValue(0, true);
  1111. if (text)
  1112. {
  1113. intptr_t len = OVR_strlen(text);
  1114. OVR_ASSERT(len <= (intptr_t)(int)len);
  1115. int bytes = f.Write((uint8_t*)text, (int)len);
  1116. f.Close();
  1117. OVR_FREE(text);
  1118. return (bytes == len);
  1119. }
  1120. else
  1121. {
  1122. return false;
  1123. }
  1124. }
  1125. //-----------------------------------------------------------------------------
  1126. // Serializes the JSON object to a String
  1127. String JSON::Stringify(bool fmt)
  1128. {
  1129. char* text = PrintValue(0, fmt);
  1130. String copy(text);
  1131. OVR_FREE(text);
  1132. return copy;
  1133. }
  1134. } // namespace OVR