lua_cjson.c 45 KB

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