PageRenderTime 22ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Miranda IM - CK Release/Miranda/Plugins/imo2sproxy/src/common/cJSON.c

http://miranda-dev.googlecode.com/
C | 365 lines | 275 code | 42 blank | 48 comment | 80 complexity | 5b24de269e2b21cbc76a33fe9ada1c7f MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, AGPL-1.0, BSD-3-Clause, LGPL-2.1
  1. /*
  2. Copyright (c) 2009 Dave Gamble
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. // cJSON
  20. // JSON parser in C.
  21. #include <string.h>
  22. #include <stdio.h>
  23. #include <math.h>
  24. #include <stdlib.h>
  25. #include <float.h>
  26. #include "cJSON.h"
  27. #ifdef WIN32
  28. #define strcasecmp stricmp
  29. #endif
  30. // Internal constructor.
  31. static cJSON *cJSON_New_Item() { return (cJSON*)calloc(sizeof(cJSON),1); }
  32. // Delete a cJSON structure.
  33. void cJSON_Delete(cJSON *c)
  34. {
  35. cJSON *next;
  36. while (c)
  37. {
  38. next=c->next;
  39. if (c->child) cJSON_Delete(c->child);
  40. if (c->valuestring) free(c->valuestring);
  41. if (c->string) free(c->string);
  42. free(c);
  43. c=next;
  44. }
  45. }
  46. // Parse the input text to generate a number, and populate the result into item.
  47. static const char *parse_number(cJSON *item,const char *num)
  48. {
  49. double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
  50. // Could use sscanf for this?
  51. if (*num=='-') sign=-1,num++; // Has sign?
  52. if (*num=='0') num++; // is zero
  53. if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); // Number?
  54. if (*num=='.') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} // Fractional part?
  55. if (*num=='e' || *num=='E') // Exponent?
  56. { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; // With sign?
  57. while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); // Number?
  58. }
  59. n=sign*n*pow(10.0,(scale+subscale*signsubscale)); // number = +/- number.fraction * 10^+/- exponent
  60. item->valuedouble=n;
  61. item->valueint=(int)n;
  62. item->type=cJSON_Number;
  63. return num;
  64. }
  65. // Render the number nicely from the given item into a string.
  66. static char *print_number(cJSON *item)
  67. {
  68. char *str;
  69. double d=item->valuedouble;
  70. if (fabs(((double)item->valueint)-d)<=DBL_EPSILON)
  71. {
  72. str=malloc(21); // 2^64+1 can be represented in 21 chars.
  73. sprintf(str,"%d",item->valueint);
  74. }
  75. else
  76. {
  77. str=malloc(64); // This is a nice tradeoff.
  78. if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
  79. else sprintf(str,"%f",d);
  80. }
  81. return str;
  82. }
  83. // Parse the input text into an unescaped cstring, and populate item.
  84. static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  85. static const char *parse_string(cJSON *item,const char *str)
  86. {
  87. const unsigned char *ptr=str+1;
  88. unsigned char *ptr2;
  89. char *out;int len=0;unsigned uc;
  90. if (*str!='\"') return 0; // not a string!
  91. while (*ptr!='\"' && *ptr>31 && ++len) if (*ptr++ == '\\') ptr++; // Skip escaped quotes.
  92. out=(char*)malloc(len+1); // This is how long we need for the string, roughly.
  93. ptr=str+1;ptr2=out;
  94. while (*ptr!='\"' && *ptr>31)
  95. {
  96. if (*ptr!='\\') *ptr2++=*ptr++;
  97. else
  98. {
  99. ptr++;
  100. switch (*ptr)
  101. {
  102. case 'b': *ptr2++='\b'; break;
  103. case 'f': *ptr2++='\f'; break;
  104. case 'n': *ptr2++='\n'; break;
  105. case 'r': *ptr2++='\r'; break;
  106. case 't': *ptr2++='\t'; break;
  107. case 'u': // transcode utf16 to utf8. DOES NOT SUPPORT SURROGATE PAIRS CORRECTLY.
  108. sscanf(ptr+1,"%4x",&uc); // get the unicode char.
  109. len=3;if (uc<0x80) len=1;else if (uc<0x800) len=2;ptr2+=len;
  110. switch (len) {
  111. case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  112. case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  113. case 1: *--ptr2 =(uc | firstByteMark[len]);
  114. }
  115. ptr2+=len;ptr+=4;
  116. break;
  117. default: *ptr2++=*ptr; break;
  118. }
  119. ptr++;
  120. }
  121. }
  122. *ptr2=0;
  123. if (*ptr=='\"') ptr++;
  124. item->valuestring=out;
  125. item->type=cJSON_String;
  126. return ptr;
  127. }
  128. // Render the cstring provided to an escaped version that can be printed.
  129. static char *print_string_ptr(const char *str)
  130. {
  131. const unsigned char *ptr; unsigned char *ptr2,*out;int len=0;
  132. ptr=str;while (*ptr && ++len) {if (*ptr<32 || *ptr=='\"' || *ptr=='\\') len++;ptr++;}
  133. out=(char*)malloc(len+3);
  134. ptr2=out;ptr=str;
  135. *ptr2++='\"';
  136. while (*ptr)
  137. {
  138. if (*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
  139. else
  140. {
  141. *ptr2++='\\';
  142. switch (*ptr++)
  143. {
  144. case '\\': *ptr2++='\\'; break;
  145. case '\"': *ptr2++='\"'; break;
  146. case '\b': *ptr2++='b'; break;
  147. case '\f': *ptr2++='f'; break;
  148. case '\n': *ptr2++='n'; break;
  149. case '\r': *ptr2++='r'; break;
  150. case '\t': *ptr2++='t'; break;
  151. default: ptr2--; break; // eviscerate with prejudice.
  152. }
  153. }
  154. }
  155. *ptr2++='\"';*ptr2++=0;
  156. return out;
  157. }
  158. // Invote print_string_ptr (which is useful) on an item.
  159. static char *print_string(cJSON *item) {return print_string_ptr(item->valuestring);}
  160. // Predeclare these prototypes.
  161. static const char *parse_value(cJSON *item,const char *value);
  162. static char *print_value(cJSON *item,int depth);
  163. static const char *parse_array(cJSON *item,const char *value);
  164. static char *print_array(cJSON *item,int depth);
  165. static const char *parse_object(cJSON *item,const char *value);
  166. static char *print_object(cJSON *item,int depth);
  167. // Parse an object - create a new root, and populate.
  168. cJSON *cJSON_Parse(const char *value) {cJSON *c=cJSON_New_Item();parse_value(c,value);return c;}
  169. // Render a cJSON item/entity/structure to text.
  170. char *cJSON_Print(cJSON *item) {return print_value(item,0);}
  171. // Parser core - when encountering text, process appropriately.
  172. static const char *parse_value(cJSON *item,const char *value)
  173. {
  174. if (!value) return 0; // Fail on null.
  175. if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
  176. if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
  177. if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
  178. if (*value=='\"') { return parse_string(item,value); }
  179. if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
  180. if (*value=='[') { return parse_array(item,value); }
  181. if (*value=='{') { return parse_object(item,value); }
  182. return 0; // failure.
  183. }
  184. // Render a value to text.
  185. static char *print_value(cJSON *item,int depth)
  186. {
  187. char *out=0;
  188. switch (item->type)
  189. {
  190. case cJSON_NULL: out=strdup("null"); break;
  191. case cJSON_False: out=strdup("false");break;
  192. case cJSON_True: out=strdup("true"); break;
  193. case cJSON_Number: out=print_number(item);break;
  194. case cJSON_String: out=print_string(item);break;
  195. case cJSON_Array: out=print_array(item,depth);break;
  196. case cJSON_Object: out=print_object(item,depth);break;
  197. }
  198. return out;
  199. }
  200. // Utility to jump whitespace and cr/lf
  201. static const char *skip(const char *in) {while (in && *in<=32) in++; return in;}
  202. // Build an array from input text.
  203. static const char *parse_array(cJSON *item,const char *value)
  204. {
  205. cJSON *child;
  206. if (*value!='[') return 0; // not an array!
  207. item->type=cJSON_Array;
  208. value=skip(value+1);
  209. if (*value==']') return value+1; // empty array.
  210. item->child=child=cJSON_New_Item();
  211. value=skip(parse_value(child,skip(value))); // skip any spacing, get the value.
  212. while (*value==',')
  213. {
  214. cJSON *new_item;
  215. if (!(new_item=cJSON_New_Item())) return 0; // memory fail
  216. child->next=new_item;new_item->prev=child;child=new_item;
  217. value=skip(parse_value(child,skip(value+1)));
  218. }
  219. if (*value==']') return value+1; // end of array
  220. return 0; // malformed.
  221. }
  222. // Render an array to text
  223. static char *print_array(cJSON *item,int depth)
  224. {
  225. char *out,*ptr,*ret;int len=5;
  226. cJSON *child=item->child;
  227. out=malloc(len);*out='[';
  228. ptr=out+1;*ptr=0;
  229. while (child)
  230. {
  231. ret=print_value(child,depth+1);
  232. if (!ret) {free(out);return 0;} // Check for failure!
  233. len+=strlen(ret)+3;
  234. out=realloc(out,len);
  235. ptr=out+strlen(out);
  236. ptr+=sprintf(ptr,"%s",ret);
  237. if (child->next) {*ptr++=',';*ptr++=' ';*ptr=0;}
  238. child=child->next;
  239. free(ret);
  240. }
  241. *ptr++=']';*ptr++=0;
  242. return out;
  243. }
  244. // Build an object from the text.
  245. static const char *parse_object(cJSON *item,const char *value)
  246. {
  247. cJSON *child;
  248. if (*value!='{') return 0; // not an object!
  249. item->type=cJSON_Object;
  250. value=skip(value+1);
  251. if (*value=='}') return value+1; // empty array.
  252. item->child=child=cJSON_New_Item();
  253. value=skip(parse_string(child,skip(value)));
  254. child->string=child->valuestring;child->valuestring=0;
  255. if (*value!=':') return 0; // fail!
  256. value=skip(parse_value(child,skip(value+1))); // skip any spacing, get the value.
  257. while (*value==',')
  258. {
  259. cJSON *new_item;
  260. if (!(new_item=cJSON_New_Item())) return 0; // memory fail
  261. child->next=new_item;new_item->prev=child;child=new_item;
  262. value=skip(parse_string(child,skip(value+1)));
  263. child->string=child->valuestring;child->valuestring=0;
  264. if (*value!=':') return 0; // fail!
  265. value=skip(parse_value(child,skip(value+1))); // skip any spacing, get the value.
  266. }
  267. if (*value=='}') return value+1; // end of array
  268. return 0; // malformed.
  269. }
  270. // Render an object to text.
  271. static char *print_object(cJSON *item,int depth)
  272. {
  273. char *out,*ptr,*ret,*str;int len=7;//,i;
  274. cJSON *child=item->child;
  275. depth++;out=malloc(len+depth);*out='{';
  276. ptr=out+1;*ptr++=' ';*ptr=0;
  277. while (child)
  278. {
  279. str=print_string_ptr(child->string);
  280. if (!str) {free(out);return 0;}
  281. ret=print_value(child,depth);
  282. if (!ret) {free(out);return 0;} // Check for failure!
  283. len+=strlen(ret)+strlen(str)+4+depth;
  284. out=realloc(out,len);
  285. ptr=out+strlen(out);
  286. // for (i=0;i<depth;i++) *ptr++='\t';
  287. ptr+=sprintf(ptr,"%s",str);
  288. *ptr++=':';*ptr++=' ';
  289. ptr+=sprintf(ptr,"%s",ret);
  290. if (child->next) *ptr++=',';
  291. *ptr++=' ';*ptr=0;
  292. child=child->next;
  293. free(str);free(ret);
  294. }
  295. // for (i=0;i<depth-1;i++) *ptr++='\t';
  296. *ptr++='}';*ptr++=0;
  297. return out;
  298. }
  299. // Get Array size/item / object item.
  300. int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
  301. cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item) item--,c=c->next; return c;}
  302. cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && strcasecmp(c->string,string)) c=c->next; return c;}
  303. // Utility for array list handling.
  304. static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
  305. // Add item to array/object.
  306. void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
  307. void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (item->string) free(item->string);item->string=strdup(string);cJSON_AddItemToArray(object,item);}
  308. // Create basic types:
  309. cJSON *cJSON_CreateNull() {cJSON *item=cJSON_New_Item();item->type=cJSON_NULL;return item;}
  310. cJSON *cJSON_CreateTrue() {cJSON *item=cJSON_New_Item();item->type=cJSON_True;return item;}
  311. cJSON *cJSON_CreateFalse() {cJSON *item=cJSON_New_Item();item->type=cJSON_False;return item;}
  312. cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;return item;}
  313. cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();item->type=cJSON_String;item->valuestring=strdup(string);return item;}
  314. cJSON *cJSON_CreateArray() {cJSON *item=cJSON_New_Item();item->type=cJSON_Array;return item;}
  315. cJSON *cJSON_CreateObject() {cJSON *item=cJSON_New_Item();item->type=cJSON_Object;return item;}
  316. // Create Arrays:
  317. cJSON *cJSON_CreateIntArray(int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  318. cJSON *cJSON_CreateFloatArray(float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  319. cJSON *cJSON_CreateDoubleArray(double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  320. cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}