lua_cjson.c 46 KB

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