lua_cjson.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. /*
  2. @module json
  3. @summary json生成和解析库
  4. @version 1.0
  5. @date 2020.02.18
  6. @demo json
  7. @tag LUAT_USE_CJSON
  8. */
  9. /* Lua CJSON - JSON support for Lua
  10. *
  11. * Copyright (c) 2010-2012 Mark Pulford <mark@kyne.com.au>
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining
  14. * a copy of this software and associated documentation files (the
  15. * "Software"), to deal in the Software without restriction, including
  16. * without limitation the rights to use, copy, modify, merge, publish,
  17. * distribute, sublicense, and/or sell copies of the Software, and to
  18. * permit persons to whom the Software is furnished to do so, subject to
  19. * the following conditions:
  20. *
  21. * The above copyright notice and this permission notice shall be
  22. * included in all copies or substantial portions of the Software.
  23. *
  24. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  27. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  28. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  29. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  30. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. */
  32. /* Caveats:
  33. * - JSON "null" values are represented as lightuserdata since Lua
  34. * tables cannot contain "nil". Compare with cjson.null.
  35. * - Invalid UTF-8 characters are not detected and will be passed
  36. * untouched. If required, UTF-8 error checking should be done
  37. * outside this library.
  38. * - Javascript comments are not part of the JSON spec, and are not
  39. * currently supported.
  40. *
  41. * Note: Decoding is slower than encoding. Lua spends significant
  42. * time (30%) managing tables when parsing JSON since it is
  43. * difficult to know object/array sizes ahead of time.
  44. */
  45. #include <assert.h>
  46. #include <string.h>
  47. #include <math.h>
  48. #include <limits.h>
  49. #include <lua.h>
  50. #include <lauxlib.h>
  51. #include "strbuf.h"
  52. #include "fpconv.h"
  53. #include "printf.h"
  54. #include "float.h"
  55. #define MIN_OPT_LEVEL 2
  56. #define LUAT_LOG_TAG "json"
  57. #include "luat_log.h"
  58. //#include <lrodefs.h>
  59. //#include <auxmods.h>
  60. static char float_fmt[12];
  61. #ifdef WIN32
  62. #define snprintf _snprintf
  63. typedef unsigned char u_char;
  64. /*
  65. * This array is designed for mapping upper and lower case letter
  66. * together for a case independent comparison. The mappings are
  67. * based upon ascii character sequences.
  68. */
  69. static const u_char charmap[] = {
  70. '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
  71. '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
  72. '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
  73. '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
  74. '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
  75. '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
  76. '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
  77. '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
  78. '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
  79. '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
  80. '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
  81. '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
  82. '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
  83. '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
  84. '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
  85. '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
  86. '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
  87. '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
  88. '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
  89. '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
  90. '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
  91. '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
  92. '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
  93. '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
  94. '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
  95. '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
  96. '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
  97. '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
  98. '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
  99. '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
  100. '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
  101. '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
  102. };
  103. int
  104. strcasecmp(const char *s1, const char *s2)
  105. {
  106. const u_char *cm = charmap;
  107. const u_char *us1 = (const u_char *)s1;
  108. const u_char *us2 = (const u_char *)s2;
  109. while (cm[*us1] == cm[*us2++])
  110. if (*us1++ == '\0')
  111. return (0);
  112. return (cm[*us1] - cm[*--us2]);
  113. }
  114. int
  115. strncasecmp(const char *s1, const char *s2, size_t n)
  116. {
  117. if (n != 0) {
  118. const u_char *cm = charmap;
  119. const u_char *us1 = (const u_char *)s1;
  120. const u_char *us2 = (const u_char *)s2;
  121. do {
  122. if (cm[*us1] != cm[*us2++])
  123. return (cm[*us1] - cm[*--us2]);
  124. if (*us1++ == '\0')
  125. break;
  126. } while (--n != 0);
  127. }
  128. return (0);
  129. }
  130. #endif
  131. #define ENABLE_CJSON_GLOBAL
  132. #define MISSING_ISINF
  133. #ifndef CJSON_MODNAME
  134. #define CJSON_MODNAME "json"
  135. #endif
  136. #ifndef CJSON_VERSION
  137. #define CJSON_VERSION "2.1.0"
  138. #endif
  139. #ifndef assert
  140. #define assert(x)
  141. #endif
  142. #if !defined(isnan)
  143. #define isnan(x) (0)
  144. #endif
  145. /* Workaround for Solaris platforms missing isinf() */
  146. #if !defined(isinf) && (defined(USE_INTERNAL_ISINF) || defined(MISSING_ISINF))
  147. #define isinf(x) (!isnan(x) && isnan((x) - (x)))
  148. #endif
  149. #define DEFAULT_SPARSE_CONVERT 0
  150. #define DEFAULT_SPARSE_RATIO 2
  151. #define DEFAULT_SPARSE_SAFE 10
  152. #define DEFAULT_ENCODE_MAX_DEPTH 1000
  153. #define DEFAULT_DECODE_MAX_DEPTH 1000
  154. #define DEFAULT_ENCODE_INVALID_NUMBERS 0
  155. #define DEFAULT_DECODE_INVALID_NUMBERS 1
  156. #define DEFAULT_ENCODE_KEEP_BUFFER 0
  157. #define DEFAULT_ENCODE_NUMBER_PRECISION 7
  158. #ifdef DISABLE_INVALID_NUMBERS
  159. #undef DEFAULT_DECODE_INVALID_NUMBERS
  160. #define DEFAULT_DECODE_INVALID_NUMBERS 0
  161. #endif
  162. typedef enum {
  163. T_OBJ_BEGIN,
  164. T_OBJ_END,
  165. T_ARR_BEGIN,
  166. T_ARR_END,
  167. T_STRING,
  168. T_NUMBER,
  169. T_INTEGER,
  170. T_BOOLEAN,
  171. T_NULL,
  172. T_COLON,
  173. T_COMMA,
  174. T_END,
  175. T_WHITESPACE,
  176. T_ERROR,
  177. T_UNKNOWN
  178. } json_token_type_t;
  179. static const char *json_token_type_name[] = {
  180. "T_OBJ_BEGIN",
  181. "T_OBJ_END",
  182. "T_ARR_BEGIN",
  183. "T_ARR_END",
  184. "T_STRING",
  185. "T_NUMBER",
  186. "T_INTEGER",
  187. "T_BOOLEAN",
  188. "T_NULL",
  189. "T_COLON",
  190. "T_COMMA",
  191. "T_END",
  192. "T_WHITESPACE",
  193. "T_ERROR",
  194. "T_UNKNOWN",
  195. NULL
  196. };
  197. // typedef struct {
  198. // //json_token_type_t ch2token[256];
  199. // //char escape2char[256]; /* Decoding */
  200. // /* encode_buf is only allocated and used when
  201. // * encode_keep_buffer is set */
  202. // //strbuf_t encode_buf;
  203. // //int encode_sparse_convert;
  204. // //int encode_sparse_ratio;
  205. // //int encode_sparse_safe;
  206. // //int encode_max_depth;
  207. // //int encode_invalid_numbers; /* 2 => Encode as "null" */
  208. // //int encode_number_precision;
  209. // //int encode_keep_buffer;
  210. // //int decode_invalid_numbers;
  211. // //int decode_max_depth;
  212. // } json_config_t;
  213. typedef struct {
  214. const char *data;
  215. const char *ptr;
  216. strbuf_t *tmp; /* Temporary storage for strings */
  217. //json_config_t *cfg;
  218. int current_depth;
  219. } json_parse_t;
  220. typedef struct {
  221. json_token_type_t type;
  222. int index;
  223. union {
  224. const char *string;
  225. lua_Number number;
  226. lua_Integer lint;
  227. int boolean;
  228. } value;
  229. int string_len;
  230. } json_token_t;
  231. // static const char *char2escape[256] = {
  232. // "\\u0000", "\\u0001", "\\u0002", "\\u0003",
  233. // "\\u0004", "\\u0005", "\\u0006", "\\u0007",
  234. // "\\b", "\\t", "\\n", "\\u000b",
  235. // "\\f", "\\r", "\\u000e", "\\u000f",
  236. // "\\u0010", "\\u0011", "\\u0012", "\\u0013",
  237. // "\\u0014", "\\u0015", "\\u0016", "\\u0017",
  238. // "\\u0018", "\\u0019", "\\u001a", "\\u001b",
  239. // "\\u001c", "\\u001d", "\\u001e", "\\u001f",
  240. // NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
  241. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\/",
  242. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  243. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  244. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  245. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  246. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  247. // NULL, NULL, NULL, NULL, "\\\\", NULL, NULL, NULL,
  248. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  249. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  250. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  251. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\u007f",
  252. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  253. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  254. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  255. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  256. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  257. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  258. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  259. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  260. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  261. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  262. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  263. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  264. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  265. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  266. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  267. // NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  268. // };
  269. static const char* char2escape(unsigned char c) {
  270. switch (c)
  271. {
  272. case 0x00: return "\\u0000";
  273. case 0x01: return "\\u0001";
  274. case 0x02: return "\\u0002";
  275. case 0x03: return "\\u0003";
  276. case 0x04: return "\\u0004";
  277. case 0x05: return "\\u0005";
  278. case 0x06: return "\\u0006";
  279. case 0x07: return "\\u0007";
  280. case 0x08: return "\\b";
  281. case 0x09: return "\\t";
  282. case 0x0a: return "\\b";
  283. case 0x0b: return "\\u000b";
  284. case 0x0c: return "\\f";
  285. case 0x0d: return "\\r";
  286. case 0x0e: return "\\u000e";
  287. case 0x0f: return "\\u000f";
  288. case 0x10: return "\\u0010";
  289. case 0x11: return "\\u0011";
  290. case 0x12: return "\\u0012";
  291. case 0x13: return "\\u0013";
  292. case 0x14: return "\\u0014";
  293. case 0x15: return "\\u0015";
  294. case 0x16: return "\\u0016";
  295. case 0x17: return "\\u0017";
  296. case 0x18: return "\\u0018";
  297. case 0x19: return "\\u0019";
  298. case 0x1a: return "\\u001a";
  299. case 0x1b: return "\\u001b";
  300. case 0x1c: return "\\u001c";
  301. case 0x1d: return "\\u001d";
  302. case 0x1e: return "\\u001e";
  303. case 0x1f: return "\\u001f";
  304. case '\"': return "\\\"";
  305. case '/' : return "\\/";
  306. case '\\': return "\\\\";
  307. case 0x7f: return "\\u007f";
  308. default:
  309. return NULL;
  310. }
  311. }
  312. //-----------------------------------------------
  313. static json_token_type_t ch2token(int ch) {
  314. switch (ch)
  315. {
  316. /* Set tokens that require no further processing */
  317. case '{': return T_OBJ_BEGIN;
  318. case '}': return T_OBJ_END;
  319. case '[': return T_ARR_BEGIN;
  320. case ']': return T_ARR_END;
  321. case ',': return T_COMMA;
  322. case ':': return T_COLON;
  323. case '\0': return T_END;
  324. case ' ': return T_WHITESPACE;
  325. case '\t': return T_WHITESPACE;
  326. case '\n': return T_WHITESPACE;
  327. case '\r': return T_WHITESPACE;
  328. /* Update characters that require further processing */
  329. case 'f': return T_UNKNOWN; /* false? */
  330. case 'i': return T_UNKNOWN; /* inf, ininity? */
  331. case 'I': return T_UNKNOWN;
  332. case 'n': return T_UNKNOWN; /* null, nan? */
  333. case 'N': return T_UNKNOWN;
  334. case 't': return T_UNKNOWN; /* true? */
  335. case '"': return T_UNKNOWN; /* string? */
  336. case '+': return T_UNKNOWN; /* number? */
  337. case '-': return T_UNKNOWN;
  338. case '0':
  339. case '1':
  340. case '2':
  341. case '3':
  342. case '4':
  343. case '5':
  344. case '6':
  345. case '7':
  346. case '8':
  347. case '9':
  348. return T_UNKNOWN;
  349. default:
  350. return T_ERROR;
  351. }
  352. }
  353. static char escape2char(unsigned char c) {
  354. switch (c) {
  355. case '"': return '"';
  356. case '\\':return '\\';
  357. case '/': return '/';
  358. case 'b': return '\b';
  359. case 't': return '\t';
  360. case 'n': return '\n';
  361. case 'f': return '\f';
  362. case 'r': return '\r';
  363. case 'u': return 'u'; /* Unicode parsing required */
  364. default:
  365. return 0;
  366. }
  367. }
  368. #if defined(DISABLE_INVALID_NUMBERS) && !defined(USE_INTERNAL_FPCONV)
  369. void json_verify_invalid_number_setting(lua_State *l, int *setting)
  370. {
  371. if (*setting == 1) {
  372. *setting = 0;
  373. luaL_error(l, "Infinity, NaN, and/or hexadecimal numbers are not supported.");
  374. }
  375. }
  376. #else
  377. #define json_verify_invalid_number_setting(l, s) do { } while(0)
  378. #endif
  379. /* ===== ENCODING ===== */
  380. static void json_encode_exception(lua_State *l, strbuf_t *json, int lindex,
  381. const char *reason)
  382. {
  383. //if (!cfg->encode_keep_buffer)
  384. strbuf_free(json);
  385. luaL_error(l, "Cannot serialise %s: %s",
  386. lua_typename(l, lua_type(l, lindex)), reason);
  387. }
  388. /* json_append_string args:
  389. * - lua_State
  390. * - JSON strbuf
  391. * - String (Lua stack index)
  392. *
  393. * Returns nothing. Doesn't remove string from Lua stack */
  394. static void json_append_string(lua_State *l, strbuf_t *json, int lindex)
  395. {
  396. const char *escstr;
  397. int i;
  398. const char *str;
  399. size_t len;
  400. str = lua_tolstring(l, lindex, &len);
  401. /* Worst case is len * 6 (all unicode escapes).
  402. * This buffer is reused constantly for small strings
  403. * If there are any excess pages, they won't be hit anyway.
  404. * This gains ~5% speedup. */
  405. strbuf_ensure_empty_length(json, len * 6 + 2);
  406. if (json->is_err)
  407. return;
  408. strbuf_append_char_unsafe(json, '\"');
  409. for (i = 0; i < len; i++) {
  410. escstr = char2escape((unsigned char)str[i]);
  411. if (escstr)
  412. strbuf_append_string(json, escstr);
  413. else
  414. strbuf_append_char_unsafe(json, str[i]);
  415. }
  416. strbuf_append_char_unsafe(json, '\"');
  417. }
  418. /* Find the size of the array on the top of the Lua stack
  419. * -1 object (not a pure array)
  420. * >=0 elements in array
  421. */
  422. static int lua_array_length(lua_State *l, strbuf_t *json)
  423. {
  424. double k;
  425. int max;
  426. int items;
  427. max = 0;
  428. items = 0;
  429. lua_pushnil(l);
  430. /* table, startkey */
  431. while (lua_next(l, -2) != 0) {
  432. /* table, key, value */
  433. if (lua_type(l, -2) == LUA_TNUMBER &&
  434. (k = lua_tonumber(l, -2))) {
  435. /* Integer >= 1 ? */
  436. if (floor(k) == k && k >= 1) {
  437. if (k > max)
  438. max = k;
  439. items++;
  440. lua_pop(l, 1);
  441. continue;
  442. }
  443. }
  444. /* Must not be an array (non integer key) */
  445. lua_pop(l, 2);
  446. return -1;
  447. }
  448. /* Encode excessively sparse arrays as objects (if enabled) */
  449. if (DEFAULT_SPARSE_RATIO > 0 &&
  450. max > items * DEFAULT_SPARSE_RATIO &&
  451. max > DEFAULT_SPARSE_SAFE) {
  452. if (!DEFAULT_SPARSE_CONVERT)
  453. json_encode_exception(l, json, -1, "excessively sparse array");
  454. return -1;
  455. }
  456. return max;
  457. }
  458. static void json_check_encode_depth(lua_State *l,
  459. int current_depth, strbuf_t *json)
  460. {
  461. /* Ensure there are enough slots free to traverse a table (key,
  462. * value) and push a string for a potential error message.
  463. *
  464. * Unlike "decode", the key and value are still on the stack when
  465. * lua_checkstack() is called. Hence an extra slot for luaL_error()
  466. * below is required just in case the next check to lua_checkstack()
  467. * fails.
  468. *
  469. * While this won't cause a crash due to the EXTRA_STACK reserve
  470. * slots, it would still be an improper use of the API. */
  471. if (current_depth <= DEFAULT_ENCODE_MAX_DEPTH && lua_checkstack(l, 3))
  472. return;
  473. //if (!cfg->encode_keep_buffer)
  474. strbuf_free(json);
  475. luaL_error(l, "Cannot serialise, excessive nesting (%d)",
  476. current_depth);
  477. }
  478. static void json_append_data(lua_State *l,
  479. int current_depth, strbuf_t *json);
  480. /* json_append_array args:
  481. * - lua_State
  482. * - JSON strbuf
  483. * - Size of passwd Lua array (top of stack) */
  484. static void json_append_array(lua_State *l, int current_depth,
  485. strbuf_t *json, int array_length)
  486. {
  487. int comma, i;
  488. strbuf_append_char(json, '[');
  489. comma = 0;
  490. for (i = 1; i <= array_length; i++) {
  491. if (comma)
  492. strbuf_append_char(json, ',');
  493. else
  494. comma = 1;
  495. lua_rawgeti(l, -1, i);
  496. json_append_data(l, current_depth, json);
  497. lua_pop(l, 1);
  498. }
  499. strbuf_append_char(json, ']');
  500. }
  501. // typedef struct {
  502. // char encode_number_precision_mode; /*浮点数转化模式 默认为'g',可配置为'f' */
  503. // unsigned char encode_number_precision; /*浮点数转化精度 默认为7,可配置为0~14 */
  504. // } json_easy_config_t;
  505. // static json_easy_config_t json_easy_config = {'g',DEFAULT_ENCODE_NUMBER_PRECISION};
  506. static void json_append_number(lua_State *l,
  507. strbuf_t *json, int lindex)
  508. {
  509. double num = lua_tonumber(l, lindex);
  510. int len;
  511. //printf("json num = %ld, %f %ld", num, num, 100);
  512. if (DEFAULT_ENCODE_INVALID_NUMBERS == 0) {
  513. /* Prevent encoding invalid numbers */
  514. if (isinf(num) || isnan(num))
  515. json_encode_exception(l, json, lindex, "must not be NaN or Inf");
  516. } else if (DEFAULT_ENCODE_INVALID_NUMBERS == 1) {
  517. /* Encode invalid numbers, but handle "nan" separately
  518. * since some platforms may encode as "-nan". */
  519. if (isnan(num)) {
  520. strbuf_append_mem(json, "nan", 3);
  521. return;
  522. }
  523. } else {
  524. /* Encode invalid numbers as "null" */
  525. if (isinf(num) || isnan(num)) {
  526. strbuf_append_mem(json, "null", 4);
  527. return;
  528. }
  529. }
  530. strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE);
  531. if (json->is_err)
  532. return;
  533. if (lua_isinteger(l, lindex)) {
  534. #ifdef LUAT_CONF_VM_64bit
  535. len = snprintf_(strbuf_empty_ptr(json), FPCONV_G_FMT_BUFSIZE, "%lld", lua_tointeger(l, lindex));
  536. #else
  537. len = snprintf_(strbuf_empty_ptr(json), FPCONV_G_FMT_BUFSIZE, "%ld", lua_tointeger(l, lindex));
  538. #endif
  539. }
  540. else {
  541. lua_Number v = lua_tonumber(l, lindex);
  542. #ifdef LUAT_CONF_VM_64bit
  543. if (v <= DBL_EPSILON && v >= -DBL_EPSILON) {
  544. #else
  545. if (v <= FLT_EPSILON && v >= -FLT_EPSILON) {
  546. #endif
  547. memcpy(strbuf_empty_ptr(json), "0.0\x00", 4);
  548. len = 1;
  549. }
  550. else {
  551. len = snprintf_(strbuf_empty_ptr(json), FPCONV_G_FMT_BUFSIZE, float_fmt, v);
  552. }
  553. }
  554. //len = fpconv_g_fmt(strbuf_empty_ptr(json), num, DEFAULT_ENCODE_NUMBER_PRECISION);
  555. strbuf_extend_length(json, len);
  556. }
  557. static void json_append_object(lua_State *l,
  558. int current_depth, strbuf_t *json)
  559. {
  560. int comma, keytype;
  561. /* Object */
  562. strbuf_append_char(json, '{');
  563. lua_pushnil(l);
  564. /* table, startkey */
  565. comma = 0;
  566. while (lua_next(l, -2) != 0) {
  567. if (comma)
  568. strbuf_append_char(json, ',');
  569. else
  570. comma = 1;
  571. /* table, key, value */
  572. keytype = lua_type(l, -2);
  573. if (keytype == LUA_TNUMBER) {
  574. strbuf_append_char(json, '"');
  575. json_append_number(l, json, -2);
  576. strbuf_append_mem(json, "\":", 2);
  577. } else if (keytype == LUA_TSTRING) {
  578. json_append_string(l, json, -2);
  579. strbuf_append_char(json, ':');
  580. } else {
  581. json_encode_exception(l, json, -2,
  582. "table key must be a number or string");
  583. /* never returns */
  584. }
  585. /* table, key, value */
  586. json_append_data(l, current_depth, json);
  587. lua_pop(l, 1);
  588. /* table, key */
  589. }
  590. strbuf_append_char(json, '}');
  591. }
  592. /* Serialise Lua data into JSON string. */
  593. static void json_append_data(lua_State *l,
  594. int current_depth, strbuf_t *json)
  595. {
  596. int len;
  597. switch (lua_type(l, -1)) {
  598. case LUA_TSTRING:
  599. json_append_string(l, json, -1);
  600. break;
  601. case LUA_TNUMBER:
  602. json_append_number(l, json, -1);
  603. break;
  604. case LUA_TBOOLEAN:
  605. if (lua_toboolean(l, -1))
  606. strbuf_append_mem(json, "true", 4);
  607. else
  608. strbuf_append_mem(json, "false", 5);
  609. break;
  610. case LUA_TTABLE:
  611. current_depth++;
  612. json_check_encode_depth(l, current_depth, json);
  613. len = lua_array_length(l, json);
  614. if (len > 0)
  615. json_append_array(l, current_depth, json, len);
  616. else
  617. json_append_object(l, current_depth, json);
  618. break;
  619. case LUA_TNIL:
  620. strbuf_append_mem(json, "null", 4);
  621. break;
  622. case LUA_TLIGHTUSERDATA:
  623. if (lua_touserdata(l, -1) == NULL) {
  624. strbuf_append_mem(json, "null", 4);
  625. break;
  626. }
  627. default:
  628. /* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD,
  629. * and LUA_TLIGHTUSERDATA) cannot be serialised */
  630. json_encode_exception(l, json, -1, "type not supported");
  631. /* never returns */
  632. }
  633. }
  634. static int json_encode(lua_State *l)
  635. {
  636. //json_config_t *cfg = json_fetch_config(l);
  637. strbuf_t local_encode_buf;
  638. strbuf_t *encode_buf;
  639. char *json;
  640. int len;
  641. int ret;
  642. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  643. encode_buf = &local_encode_buf;
  644. ret = strbuf_init(encode_buf, 0);
  645. if (ret) {
  646. LLOGE("json encode out of memory!!!");
  647. return 0;
  648. }
  649. json_append_data(l, 0, encode_buf);
  650. // check if err
  651. if (local_encode_buf.is_err) {
  652. LLOGE("json encode failed by memory less");
  653. lua_pushnil(l);
  654. }
  655. else {
  656. json = strbuf_string(encode_buf, &len);
  657. lua_pushlstring(l, json, len);
  658. }
  659. strbuf_free(encode_buf);
  660. return 1;
  661. }
  662. /* ===== DECODING ===== */
  663. static void json_process_value(lua_State *l, json_parse_t *json,
  664. json_token_t *token);
  665. static int hexdigit2int(char hex)
  666. {
  667. if ('0' <= hex && hex <= '9')
  668. return hex - '0';
  669. /* Force lowercase */
  670. hex |= 0x20;
  671. if ('a' <= hex && hex <= 'f')
  672. return 10 + hex - 'a';
  673. return -1;
  674. }
  675. static int decode_hex4(const char *hex)
  676. {
  677. int digit[4];
  678. int i;
  679. /* Convert ASCII hex digit to numeric digit
  680. * Note: this returns an error for invalid hex digits, including
  681. * NULL */
  682. for (i = 0; i < 4; i++) {
  683. digit[i] = hexdigit2int(hex[i]);
  684. if (digit[i] < 0) {
  685. return -1;
  686. }
  687. }
  688. return (digit[0] << 12) +
  689. (digit[1] << 8) +
  690. (digit[2] << 4) +
  691. digit[3];
  692. }
  693. /* Converts a Unicode codepoint to UTF-8.
  694. * Returns UTF-8 string length, and up to 4 bytes in *utf8 */
  695. static int codepoint_to_utf8(char *utf8, int codepoint)
  696. {
  697. /* 0xxxxxxx */
  698. if (codepoint <= 0x7F) {
  699. utf8[0] = codepoint;
  700. return 1;
  701. }
  702. /* 110xxxxx 10xxxxxx */
  703. if (codepoint <= 0x7FF) {
  704. utf8[0] = (codepoint >> 6) | 0xC0;
  705. utf8[1] = (codepoint & 0x3F) | 0x80;
  706. return 2;
  707. }
  708. /* 1110xxxx 10xxxxxx 10xxxxxx */
  709. if (codepoint <= 0xFFFF) {
  710. utf8[0] = (codepoint >> 12) | 0xE0;
  711. utf8[1] = ((codepoint >> 6) & 0x3F) | 0x80;
  712. utf8[2] = (codepoint & 0x3F) | 0x80;
  713. return 3;
  714. }
  715. /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
  716. if (codepoint <= 0x1FFFFF) {
  717. utf8[0] = (codepoint >> 18) | 0xF0;
  718. utf8[1] = ((codepoint >> 12) & 0x3F) | 0x80;
  719. utf8[2] = ((codepoint >> 6) & 0x3F) | 0x80;
  720. utf8[3] = (codepoint & 0x3F) | 0x80;
  721. return 4;
  722. }
  723. return 0;
  724. }
  725. /* Called when index pointing to beginning of UTF-16 code escape: \uXXXX
  726. * \u is guaranteed to exist, but the remaining hex characters may be
  727. * missing.
  728. * Translate to UTF-8 and append to temporary token string.
  729. * Must advance index to the next character to be processed.
  730. * Returns: 0 success
  731. * -1 error
  732. */
  733. static int json_append_unicode_escape(json_parse_t *json)
  734. {
  735. char utf8[4]; /* Surrogate pairs require 4 UTF-8 bytes */
  736. int codepoint;
  737. int surrogate_low;
  738. int len;
  739. int escape_len = 6;
  740. /* Fetch UTF-16 code unit */
  741. codepoint = decode_hex4(json->ptr + 2);
  742. if (codepoint < 0)
  743. return -1;
  744. /* UTF-16 surrogate pairs take the following 2 byte form:
  745. * 11011 x yyyyyyyyyy
  746. * When x = 0: y is the high 10 bits of the codepoint
  747. * x = 1: y is the low 10 bits of the codepoint
  748. *
  749. * Check for a surrogate pair (high or low) */
  750. if ((codepoint & 0xF800) == 0xD800) {
  751. /* Error if the 1st surrogate is not high */
  752. if (codepoint & 0x400)
  753. return -1;
  754. /* Ensure the next code is a unicode escape */
  755. if (*(json->ptr + escape_len) != '\\' ||
  756. *(json->ptr + escape_len + 1) != 'u') {
  757. return -1;
  758. }
  759. /* Fetch the next codepoint */
  760. surrogate_low = decode_hex4(json->ptr + 2 + escape_len);
  761. if (surrogate_low < 0)
  762. return -1;
  763. /* Error if the 2nd code is not a low surrogate */
  764. if ((surrogate_low & 0xFC00) != 0xDC00)
  765. return -1;
  766. /* Calculate Unicode codepoint */
  767. codepoint = (codepoint & 0x3FF) << 10;
  768. surrogate_low &= 0x3FF;
  769. codepoint = (codepoint | surrogate_low) + 0x10000;
  770. escape_len = 12;
  771. }
  772. /* Convert codepoint to UTF-8 */
  773. len = codepoint_to_utf8(utf8, codepoint);
  774. if (!len)
  775. return -1;
  776. /* Append bytes and advance parse index */
  777. strbuf_append_mem_unsafe(json->tmp, utf8, len);
  778. json->ptr += escape_len;
  779. return 0;
  780. }
  781. static void json_set_token_error(json_token_t *token, json_parse_t *json,
  782. const char *errtype)
  783. {
  784. token->type = T_ERROR;
  785. token->index = json->ptr - json->data;
  786. token->value.string = errtype;
  787. }
  788. static void json_next_string_token(json_parse_t *json, json_token_t *token)
  789. {
  790. //char *escape2char = json->cfg->escape2char;
  791. char ch;
  792. /* Caller must ensure a string is next */
  793. assert(*json->ptr == '"');
  794. /* Skip " */
  795. json->ptr++;
  796. /* json->tmp is the temporary strbuf used to accumulate the
  797. * decoded string value.
  798. * json->tmp is sized to handle JSON containing only a string value.
  799. */
  800. strbuf_reset(json->tmp);
  801. while ((ch = *json->ptr) != '"') {
  802. if (!ch) {
  803. /* Premature end of the string */
  804. json_set_token_error(token, json, "unexpected end of string");
  805. return;
  806. }
  807. /* Handle escapes */
  808. if (ch == '\\') {
  809. /* Fetch escape character */
  810. ch = *(json->ptr + 1);
  811. /* Translate escape code and append to tmp string */
  812. ch = escape2char((unsigned char)ch);
  813. if (ch == 'u') {
  814. if (json_append_unicode_escape(json) == 0)
  815. continue;
  816. json_set_token_error(token, json,
  817. "invalid unicode escape code");
  818. return;
  819. }
  820. if (!ch) {
  821. json_set_token_error(token, json, "invalid escape code");
  822. return;
  823. }
  824. /* Skip '\' */
  825. json->ptr++;
  826. }
  827. /* Append normal character or translated single character
  828. * Unicode escapes are handled above */
  829. strbuf_append_char_unsafe(json->tmp, ch);
  830. json->ptr++;
  831. }
  832. json->ptr++; /* Eat final quote (") */
  833. strbuf_ensure_null(json->tmp);
  834. token->type = T_STRING;
  835. token->value.string = strbuf_string(json->tmp, &token->string_len);
  836. }
  837. /* JSON numbers should take the following form:
  838. * -?(0|[1-9]|[1-9][0-9]+)(.[0-9]+)?([eE][-+]?[0-9]+)?
  839. *
  840. * json_next_number_token() uses strtod() which allows other forms:
  841. * - numbers starting with '+'
  842. * - NaN, -NaN, infinity, -infinity
  843. * - hexadecimal numbers
  844. * - numbers with leading zeros
  845. *
  846. * json_is_invalid_number() detects "numbers" which may pass strtod()'s
  847. * error checking, but should not be allowed with strict JSON.
  848. *
  849. * json_is_invalid_number() may pass numbers which cause strtod()
  850. * to generate an error.
  851. */
  852. static int json_is_invalid_number(json_parse_t *json)
  853. {
  854. const char *p = json->ptr;
  855. /* Reject numbers starting with + */
  856. if (*p == '+')
  857. return 1;
  858. /* Skip minus sign if it exists */
  859. if (*p == '-')
  860. p++;
  861. /* Reject numbers starting with 0x, or leading zeros */
  862. if (*p == '0') {
  863. int ch2 = *(p + 1);
  864. if ((ch2 | 0x20) == 'x' || /* Hex */
  865. ('0' <= ch2 && ch2 <= '9')) /* Leading zero */
  866. return 1;
  867. return 0;
  868. } else if (*p <= '9') {
  869. return 0; /* Ordinary number */
  870. }
  871. /* Reject inf/nan */
  872. if (!strncasecmp(p, "inf", 3))
  873. return 1;
  874. if (!strncasecmp(p, "nan", 3))
  875. return 1;
  876. /* Pass all other numbers which may still be invalid, but
  877. * strtod() will catch them. */
  878. return 0;
  879. }
  880. static void json_next_number_token(json_parse_t *json, json_token_t *token)
  881. {
  882. char *endptr;
  883. unsigned len = 0;
  884. lua_Integer int_val = 0;
  885. token->type = T_NUMBER;
  886. token->value.number = lua_str2number(json->ptr, &endptr);
  887. if (json->ptr == endptr)
  888. json_set_token_error(token, json, "invalid number");
  889. else {
  890. // 额外尝试是否为整型
  891. #ifndef LUAT_LIB_JSON_DECODE_INTEGER_DISABLE
  892. len = (endptr - json->ptr);
  893. if (len == 1 && (*json->ptr) == '0') {
  894. token->type = T_INTEGER;
  895. token->value.lint = 0;
  896. }
  897. else {
  898. for (size_t i = 0; i < len; i++)
  899. {
  900. if (json->ptr[i] == '.') {
  901. int_val = -1;
  902. break;
  903. }
  904. }
  905. if (int_val == 0) {
  906. int_val = 0;
  907. #ifdef LUAT_CONF_VM_64bit
  908. int_val = strtoll(json->ptr, &endptr, 0);
  909. #else
  910. int_val = strtol(json->ptr, &endptr, 0);
  911. #endif
  912. if (int_val != 0) {
  913. token->type = T_INTEGER;
  914. token->value.lint = int_val;
  915. }
  916. }
  917. }
  918. #endif
  919. json->ptr = endptr; /* Skip the processed number */
  920. }
  921. return;
  922. }
  923. /* Fills in the token struct.
  924. * T_STRING will return a pointer to the json_parse_t temporary string
  925. * T_ERROR will leave the json->ptr pointer at the error.
  926. */
  927. static void json_next_token(json_parse_t *json, json_token_t *token)
  928. {
  929. //const json_token_type_t *ch2token = json->cfg->ch2token;
  930. int ch;
  931. /* Eat whitespace. */
  932. while (1) {
  933. ch = (unsigned char)*(json->ptr);
  934. token->type = ch2token(ch);
  935. if (token->type != T_WHITESPACE)
  936. break;
  937. json->ptr++;
  938. }
  939. /* Store location of new token. Required when throwing errors
  940. * for unexpected tokens (syntax errors). */
  941. token->index = json->ptr - json->data;
  942. /* Don't advance the pointer for an error or the end */
  943. if (token->type == T_ERROR) {
  944. json_set_token_error(token, json, "invalid token");
  945. return;
  946. }
  947. if (token->type == T_END) {
  948. return;
  949. }
  950. /* Found a known single character token, advance index and return */
  951. if (token->type != T_UNKNOWN) {
  952. json->ptr++;
  953. return;
  954. }
  955. /* Process characters which triggered T_UNKNOWN
  956. *
  957. * Must use strncmp() to match the front of the JSON string.
  958. * JSON identifier must be lowercase.
  959. * When strict_numbers if disabled, either case is allowed for
  960. * Infinity/NaN (since we are no longer following the spec..) */
  961. if (ch == '"') {
  962. json_next_string_token(json, token);
  963. return;
  964. } else if (ch == '-' || ('0' <= ch && ch <= '9')) {
  965. if (!DEFAULT_ENCODE_INVALID_NUMBERS && json_is_invalid_number(json)) {
  966. json_set_token_error(token, json, "invalid number");
  967. return;
  968. }
  969. json_next_number_token(json, token);
  970. return;
  971. } else if (!strncmp(json->ptr, "true", 4)) {
  972. token->type = T_BOOLEAN;
  973. token->value.boolean = 1;
  974. json->ptr += 4;
  975. return;
  976. } else if (!strncmp(json->ptr, "false", 5)) {
  977. token->type = T_BOOLEAN;
  978. token->value.boolean = 0;
  979. json->ptr += 5;
  980. return;
  981. } else if (!strncmp(json->ptr, "null", 4)) {
  982. token->type = T_NULL;
  983. json->ptr += 4;
  984. return;
  985. } else if (DEFAULT_ENCODE_INVALID_NUMBERS &&
  986. json_is_invalid_number(json)) {
  987. /* When decode_invalid_numbers is enabled, only attempt to process
  988. * numbers we know are invalid JSON (Inf, NaN, hex)
  989. * This is required to generate an appropriate token error,
  990. * otherwise all bad tokens will register as "invalid number"
  991. */
  992. json_next_number_token(json, token);
  993. return;
  994. }
  995. /* Token starts with t/f/n but isn't recognised above. */
  996. json_set_token_error(token, json, "invalid token");
  997. }
  998. /* This function does not return.
  999. * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED.
  1000. * The only supported exception is the temporary parser string
  1001. * json->tmp struct.
  1002. * json and token should exist on the stack somewhere.
  1003. * luaL_error() will long_jmp and release the stack */
  1004. static void json_throw_parse_error(lua_State *l, json_parse_t *json,
  1005. const char *exp, json_token_t *token)
  1006. {
  1007. const char *found;
  1008. strbuf_free(json->tmp);
  1009. if (token->type == T_ERROR)
  1010. found = token->value.string;
  1011. else
  1012. found = json_token_type_name[token->type];
  1013. /* Note: token->index is 0 based, display starting from 1 */
  1014. luaL_error(l, "Expected %s but found %s at character %d",
  1015. exp, found, token->index + 1);
  1016. }
  1017. static inline void json_decode_ascend(json_parse_t *json)
  1018. {
  1019. json->current_depth--;
  1020. }
  1021. static void json_decode_descend(lua_State *l, json_parse_t *json, int slots)
  1022. {
  1023. json->current_depth++;
  1024. if (json->current_depth <= DEFAULT_DECODE_MAX_DEPTH &&
  1025. lua_checkstack(l, slots)) {
  1026. return;
  1027. }
  1028. strbuf_free(json->tmp);
  1029. luaL_error(l, "Found too many nested data structures (%d) at character %d",
  1030. json->current_depth, json->ptr - json->data);
  1031. }
  1032. static void json_parse_object_context(lua_State *l, json_parse_t *json)
  1033. {
  1034. json_token_t token;
  1035. /* 3 slots required:
  1036. * .., table, key, value */
  1037. json_decode_descend(l, json, 3);
  1038. lua_newtable(l);
  1039. json_next_token(json, &token);
  1040. /* Handle empty objects */
  1041. if (token.type == T_OBJ_END) {
  1042. json_decode_ascend(json);
  1043. return;
  1044. }
  1045. while (1) {
  1046. if (token.type != T_STRING)
  1047. json_throw_parse_error(l, json, "object key string", &token);
  1048. /* Push key */
  1049. lua_pushlstring(l, token.value.string, token.string_len);
  1050. json_next_token(json, &token);
  1051. if (token.type != T_COLON)
  1052. json_throw_parse_error(l, json, "colon", &token);
  1053. /* Fetch value */
  1054. json_next_token(json, &token);
  1055. json_process_value(l, json, &token);
  1056. /* Set key = value */
  1057. lua_rawset(l, -3);
  1058. json_next_token(json, &token);
  1059. if (token.type == T_OBJ_END) {
  1060. json_decode_ascend(json);
  1061. return;
  1062. }
  1063. if (token.type != T_COMMA)
  1064. json_throw_parse_error(l, json, "comma or object end", &token);
  1065. json_next_token(json, &token);
  1066. }
  1067. }
  1068. /* Handle the array context */
  1069. static void json_parse_array_context(lua_State *l, json_parse_t *json)
  1070. {
  1071. json_token_t token;
  1072. int i;
  1073. /* 2 slots required:
  1074. * .., table, value */
  1075. json_decode_descend(l, json, 2);
  1076. lua_newtable(l);
  1077. json_next_token(json, &token);
  1078. /* Handle empty arrays */
  1079. if (token.type == T_ARR_END) {
  1080. json_decode_ascend(json);
  1081. return;
  1082. }
  1083. for (i = 1; ; i++) {
  1084. json_process_value(l, json, &token);
  1085. lua_rawseti(l, -2, i); /* arr[i] = value */
  1086. json_next_token(json, &token);
  1087. if (token.type == T_ARR_END) {
  1088. json_decode_ascend(json);
  1089. return;
  1090. }
  1091. if (token.type != T_COMMA)
  1092. json_throw_parse_error(l, json, "comma or array end", &token);
  1093. json_next_token(json, &token);
  1094. }
  1095. }
  1096. /* Handle the "value" context */
  1097. static void json_process_value(lua_State *l, json_parse_t *json,
  1098. json_token_t *token)
  1099. {
  1100. switch (token->type) {
  1101. case T_STRING:
  1102. lua_pushlstring(l, token->value.string, token->string_len);
  1103. break;;
  1104. case T_NUMBER:
  1105. lua_pushnumber(l, token->value.number);
  1106. break;;
  1107. case T_INTEGER:
  1108. lua_pushinteger(l, token->value.lint);
  1109. break;;
  1110. case T_BOOLEAN:
  1111. lua_pushboolean(l, token->value.boolean);
  1112. break;;
  1113. case T_OBJ_BEGIN:
  1114. json_parse_object_context(l, json);
  1115. break;;
  1116. case T_ARR_BEGIN:
  1117. json_parse_array_context(l, json);
  1118. break;;
  1119. case T_NULL:
  1120. /* In Lua, setting "t[k] = nil" will delete k from the table.
  1121. * Hence a NULL pointer lightuserdata object is used instead */
  1122. lua_pushlightuserdata(l, NULL);
  1123. break;;
  1124. default:
  1125. json_throw_parse_error(l, json, "value", token);
  1126. }
  1127. }
  1128. static int json_decode(lua_State *l)
  1129. {
  1130. json_parse_t json;
  1131. json_token_t token;
  1132. size_t json_len;
  1133. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1134. //json.cfg = json_fetch_config(l);
  1135. json.data = luaL_checklstring(l, 1, &json_len);
  1136. json.current_depth = 0;
  1137. json.ptr = json.data;
  1138. /* Detect Unicode other than UTF-8 (see RFC 4627, Sec 3)
  1139. *
  1140. * CJSON can support any simple data type, hence only the first
  1141. * character is guaranteed to be ASCII (at worst: '"'). This is
  1142. * still enough to detect whether the wrong encoding is in use. */
  1143. if (json_len >= 2 && (!json.data[0] || !json.data[1]))
  1144. luaL_error(l, "JSON parser does not support UTF-16 or UTF-32");
  1145. /* Ensure the temporary buffer can hold the entire string.
  1146. * This means we no longer need to do length checks since the decoded
  1147. * string must be smaller than the entire json string */
  1148. json.tmp = strbuf_new(json_len);
  1149. if (json.tmp == NULL) {
  1150. LLOGE("json decode out of memory!");
  1151. return 0;
  1152. }
  1153. json_next_token(&json, &token);
  1154. json_process_value(l, &json, &token);
  1155. /* Ensure there is no more input left */
  1156. json_next_token(&json, &token);
  1157. if (token.type != T_END)
  1158. json_throw_parse_error(l, &json, "the end", &token);
  1159. strbuf_free(json.tmp);
  1160. return 1;
  1161. }
  1162. /* ===== INITIALISATION ===== */
  1163. #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
  1164. /* Compatibility for Lua 5.1.
  1165. *
  1166. * luaL_setfuncs() is used to create a module table where the functions have
  1167. * json_config_t as their first upvalue. Code borrowed from Lua 5.2 source. */
  1168. static void luaL_setfuncs (lua_State *l, const luaL_Reg *reg, int nup)
  1169. {
  1170. int i;
  1171. luaL_checkstack(l, nup, "too many upvalues");
  1172. for (; reg->name != NULL; reg++) { /* fill the table with given functions */
  1173. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  1174. lua_pushvalue(l, -nup);
  1175. lua_pushcclosure(l, reg->func, nup); /* closure with those upvalues */
  1176. lua_setfield(l, -(nup + 2), reg->name);
  1177. }
  1178. lua_pop(l, nup); /* remove upvalues */
  1179. }
  1180. #endif
  1181. /* Call target function in protected mode with all supplied args.
  1182. * Assumes target function only returns a single non-nil value.
  1183. * Convert and return thrown errors as: nil, "error message" */
  1184. static int json_protect_conversion(lua_State *l)
  1185. {
  1186. int err;
  1187. /* Deliberately throw an error for invalid arguments */
  1188. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1189. /* pcall() the function stored as upvalue(1) */
  1190. lua_pushvalue(l, lua_upvalueindex(1));
  1191. lua_insert(l, 1);
  1192. err = lua_pcall(l, 1, 1, 0);
  1193. if (!err)
  1194. return 1;
  1195. if (err == LUA_ERRRUN) {
  1196. lua_pushnil(l);
  1197. lua_insert(l, -2);
  1198. return 2;
  1199. }
  1200. /* Since we are not using a custom error handler, the only remaining
  1201. * errors are memory related */
  1202. return luaL_error(l, "Memory allocation error in CJSON protected call");
  1203. }
  1204. /*
  1205. 将对象序列化为json字符串
  1206. @api json.encode(obj,t)
  1207. @obj 需要序列化的对象
  1208. @string 浮点数精度和模式,这项不存在的时候,为默认值"7g",数字只支持"0~14",模式只支持"f/g"
  1209. @return string 序列化后的json字符串, 失败的话返回nil
  1210. @return string 序列化失败的报错信息
  1211. @usage
  1212. json.encode(obj)-->浮点数用%.7g的方式转换为字符串
  1213. json.encode(obj,"12f")-->浮点数用%.12f的方式转换为字符串
  1214. */
  1215. static int l_json_encode_safe(lua_State *L) {
  1216. // int top = lua_gettop(L);
  1217. if (lua_isnil(L, 1)) {
  1218. lua_pushnil(L);
  1219. lua_pushliteral(L, "obj is nil");
  1220. return 1;
  1221. }
  1222. memcpy(float_fmt, "%.7g", strlen("%.7g") + 1);
  1223. size_t len = 0;
  1224. int prec = 0;
  1225. char buff[6] = {0};
  1226. if (lua_isstring(L, 2)) {
  1227. const char* mode = luaL_checklstring(L, 2, &len);
  1228. //LLOGD("json format ? %s", mode);
  1229. if (len > 1 && len < 8 && (mode[len - 1] == 'g' || mode[len - 1] == 'f')) {
  1230. if (mode[0] == '%') {
  1231. memcpy(float_fmt, mode, len + 1);
  1232. }
  1233. else {
  1234. memcpy(float_fmt + 2, mode, len + 1);
  1235. }
  1236. }
  1237. }
  1238. //LLOGD("float_fmt [%s]", float_fmt);
  1239. lua_pushcfunction(L, json_encode);
  1240. lua_pushvalue(L, 1);
  1241. int status = lua_pcall(L, 1, 1, 0);
  1242. if (status != LUA_OK) {
  1243. const char* err = lua_tostring(L, -1);
  1244. lua_pushnil(L);
  1245. lua_pushstring(L, err);
  1246. return 2;
  1247. }
  1248. return 1;
  1249. }
  1250. /*
  1251. 将字符串反序列化为对象
  1252. @api json.decode(str)
  1253. @string 需要反序列化的json字符串
  1254. @return obj 反序列化后的对象(通常是table), 失败的话返回nil
  1255. @return result 成功返回1,否则返回0
  1256. @return err 反序列化失败的报错信息
  1257. @usage
  1258. json.decode("[1,2,3,4,5,6]")
  1259. */
  1260. static int l_json_decode_safe(lua_State *L) {
  1261. int top = lua_gettop(L);
  1262. lua_pushcfunction(L, json_decode);
  1263. lua_insert(L, 1);
  1264. int status = lua_pcall(L, top, 1, 0);
  1265. if (status != LUA_OK) {
  1266. const char *msg = lua_tostring(L, -1);
  1267. lua_pushnil(L);
  1268. lua_pushboolean(L, 0);
  1269. lua_pushstring(L, msg);
  1270. return 3;
  1271. }
  1272. else {
  1273. lua_pushinteger(L, 1);
  1274. return 2;
  1275. }
  1276. }
  1277. #include "rotable2.h"
  1278. static const rotable_Reg_t reg_json[] = {
  1279. { "encode", ROREG_FUNC(l_json_encode_safe)},
  1280. { "decode", ROREG_FUNC(l_json_decode_safe)},
  1281. // { "encode_sparse_array", json_cfg_encode_sparse_array },
  1282. // { "encode_max_depth", json_cfg_encode_max_depth },
  1283. // { "decode_max_depth", json_cfg_decode_max_depth },
  1284. // { "encode_number_precision", l_json_cfg_encode_number_precision , 0},
  1285. // { "encode_keep_buffer", json_cfg_encode_keep_buffer },
  1286. // { "encode_invalid_numbers", json_cfg_encode_invalid_numbers },
  1287. // { "decode_invalid_numbers", json_cfg_decode_invalid_numbers },
  1288. // { "new", lua_cjson_new },
  1289. { NULL, ROREG_INT(0)}
  1290. };
  1291. /* Return cjson module table */
  1292. static int lua_cjson_new(lua_State *l)
  1293. {
  1294. /* Initialise number conversions */
  1295. //fpconv_init();
  1296. /* cjson module table */
  1297. //lua_newtable(l);
  1298. /* Register functions with config data as upvalue */
  1299. //json_create_config(l);
  1300. //luaL_setfuncs(l, reg, 1);
  1301. /* Set cjson.null */
  1302. //lua_pushlightuserdata(l, NULL);
  1303. //lua_setfield(l, -2, "null");
  1304. // /* Set module name / version fields */
  1305. // lua_pushliteral(l, CJSON_MODNAME);
  1306. // lua_setfield(l, -2, "_NAME");
  1307. // lua_pushliteral(l, CJSON_VERSION);
  1308. // lua_setfield(l, -2, "_VERSION");
  1309. luat_newlib2(l, reg_json);
  1310. return 1;
  1311. }
  1312. // /* Return cjson.safe module table */
  1313. // static int lua_cjson_safe_new(lua_State *l)
  1314. // {
  1315. // const char *func[] = { "decode", "encode", NULL };
  1316. // int i;
  1317. // lua_cjson_new(l);
  1318. // /* Fix new() method */
  1319. // lua_pushcfunction(l, lua_cjson_safe_new);
  1320. // lua_setfield(l, -2, "new");
  1321. // for (i = 0; func[i]; i++) {
  1322. // lua_getfield(l, -1, func[i]);
  1323. // lua_pushcclosure(l, json_protect_conversion, 1);
  1324. // lua_setfield(l, -2, func[i]);
  1325. // }
  1326. // return 1;
  1327. // }
  1328. int luaopen_cjson(lua_State *l)
  1329. {
  1330. memcpy(float_fmt, "%.7g", strlen("%.7g") + 1);
  1331. lua_cjson_new(l);
  1332. // #ifdef ENABLE_CJSON_GLOBAL
  1333. // /* Register a global "cjson" table. */
  1334. // lua_pushvalue(l, -1);
  1335. // lua_setglobal(l, CJSON_MODNAME);
  1336. // #endif
  1337. /* Return cjson table */
  1338. return 1;
  1339. }
  1340. // int luaopen_cjson_safe(lua_State *l)
  1341. // {
  1342. // lua_cjson_safe_new(l);
  1343. // /* Return cjson.safe table */
  1344. // return 1;
  1345. // }
  1346. /* vi:ai et sw=4 ts=4:
  1347. */