lua_cjson.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. /* Lua CJSON - JSON support for Lua
  2. *
  3. * Copyright (c) 2010-2012 Mark Pulford <[email protected]>
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining
  6. * a copy of this software and associated documentation files (the
  7. * "Software"), to deal in the Software without restriction, including
  8. * without limitation the rights to use, copy, modify, merge, publish,
  9. * distribute, sublicense, and/or sell copies of the Software, and to
  10. * permit persons to whom the Software is furnished to do so, subject to
  11. * the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be
  14. * included in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. /* Caveats:
  25. * - JSON "null" values are represented as lightuserdata since Lua
  26. * tables cannot contain "nil". Compare with cjson.null.
  27. * - Invalid UTF-8 characters are not detected and will be passed
  28. * untouched. If required, UTF-8 error checking should be done
  29. * outside this library.
  30. * - Javascript comments are not part of the JSON spec, and are not
  31. * currently supported.
  32. *
  33. * Note: Decoding is slower than encoding. Lua spends significant
  34. * time (30%) managing tables when parsing JSON since it is
  35. * difficult to know object/array sizes ahead of time.
  36. */
  37. #include <assert.h>
  38. #include <string.h>
  39. #include <math.h>
  40. #include <limits.h>
  41. #include <lua.h>
  42. #include <lauxlib.h>
  43. #include "strbuf.h"
  44. #include "fpconv.h"
  45. #ifndef CJSON_MODNAME
  46. #define CJSON_MODNAME "cjson"
  47. #endif
  48. #ifndef CJSON_VERSION
  49. #define CJSON_VERSION "2.0devel"
  50. #endif
  51. /* Workaround for Solaris platforms missing isinf() */
  52. #if !defined(isinf) && (defined(USE_INTERNAL_ISINF) || defined(MISSING_ISINF))
  53. #define isinf(x) (!isnan(x) && isnan((x) - (x)))
  54. #endif
  55. #define DEFAULT_SPARSE_CONVERT 0
  56. #define DEFAULT_SPARSE_RATIO 2
  57. #define DEFAULT_SPARSE_SAFE 10
  58. #define DEFAULT_ENCODE_MAX_DEPTH 1000
  59. #define DEFAULT_DECODE_MAX_DEPTH 1000
  60. #define DEFAULT_ENCODE_INVALID_NUMBERS 0
  61. #define DEFAULT_DECODE_INVALID_NUMBERS 1
  62. #define DEFAULT_ENCODE_KEEP_BUFFER 1
  63. #define DEFAULT_ENCODE_NUMBER_PRECISION 14
  64. #ifdef DISABLE_INVALID_NUMBERS
  65. #undef DEFAULT_DECODE_INVALID_NUMBERS
  66. #define DEFAULT_DECODE_INVALID_NUMBERS 0
  67. #endif
  68. typedef enum {
  69. T_OBJ_BEGIN,
  70. T_OBJ_END,
  71. T_ARR_BEGIN,
  72. T_ARR_END,
  73. T_STRING,
  74. T_NUMBER,
  75. T_BOOLEAN,
  76. T_NULL,
  77. T_COLON,
  78. T_COMMA,
  79. T_END,
  80. T_WHITESPACE,
  81. T_ERROR,
  82. T_UNKNOWN
  83. } json_token_type_t;
  84. static const char *json_token_type_name[] = {
  85. "T_OBJ_BEGIN",
  86. "T_OBJ_END",
  87. "T_ARR_BEGIN",
  88. "T_ARR_END",
  89. "T_STRING",
  90. "T_NUMBER",
  91. "T_BOOLEAN",
  92. "T_NULL",
  93. "T_COLON",
  94. "T_COMMA",
  95. "T_END",
  96. "T_WHITESPACE",
  97. "T_ERROR",
  98. "T_UNKNOWN",
  99. NULL
  100. };
  101. typedef struct {
  102. json_token_type_t ch2token[256];
  103. char escape2char[256]; /* Decoding */
  104. /* encode_buf is only allocated and used when
  105. * encode_keep_buffer is set */
  106. strbuf_t encode_buf;
  107. int encode_sparse_convert;
  108. int encode_sparse_ratio;
  109. int encode_sparse_safe;
  110. int encode_max_depth;
  111. int encode_invalid_numbers; /* 2 => Encode as "null" */
  112. int encode_number_precision;
  113. int encode_keep_buffer;
  114. int decode_invalid_numbers;
  115. int decode_max_depth;
  116. } json_config_t;
  117. typedef struct {
  118. const char *data;
  119. const char *ptr;
  120. strbuf_t *tmp; /* Temporary storage for strings */
  121. json_config_t *cfg;
  122. int current_depth;
  123. } json_parse_t;
  124. typedef struct {
  125. json_token_type_t type;
  126. int index;
  127. union {
  128. const char *string;
  129. double number;
  130. int boolean;
  131. } value;
  132. int string_len;
  133. } json_token_t;
  134. static const char *char2escape[256] = {
  135. "\\u0000", "\\u0001", "\\u0002", "\\u0003",
  136. "\\u0004", "\\u0005", "\\u0006", "\\u0007",
  137. "\\b", "\\t", "\\n", "\\u000b",
  138. "\\f", "\\r", "\\u000e", "\\u000f",
  139. "\\u0010", "\\u0011", "\\u0012", "\\u0013",
  140. "\\u0014", "\\u0015", "\\u0016", "\\u0017",
  141. "\\u0018", "\\u0019", "\\u001a", "\\u001b",
  142. "\\u001c", "\\u001d", "\\u001e", "\\u001f",
  143. NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
  144. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\/",
  145. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  146. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  147. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  148. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  149. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  150. NULL, NULL, NULL, NULL, "\\\\", NULL, NULL, NULL,
  151. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  152. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  153. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  154. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\u007f",
  155. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  156. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  157. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  158. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  159. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  160. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  161. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  162. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  163. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  164. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  165. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  166. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  167. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  168. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  169. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  170. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  171. };
  172. /* ===== CONFIGURATION ===== */
  173. static json_config_t *json_fetch_config(lua_State *l)
  174. {
  175. json_config_t *cfg;
  176. cfg = lua_touserdata(l, lua_upvalueindex(1));
  177. if (!cfg)
  178. luaL_error(l, "BUG: Unable to fetch CJSON configuration");
  179. return cfg;
  180. }
  181. /* Ensure the correct number of arguments have been provided.
  182. * Pad with nil to allow other functions to simply check arg[i]
  183. * to find whether an argument was provided */
  184. static json_config_t *json_arg_init(lua_State *l, int args)
  185. {
  186. luaL_argcheck(l, lua_gettop(l) <= args, args + 1,
  187. "found too many arguments");
  188. while (lua_gettop(l) < args)
  189. lua_pushnil(l);
  190. return json_fetch_config(l);
  191. }
  192. /* Process integer options for configuration functions */
  193. static int json_integer_option(lua_State *l, int optindex, int *setting,
  194. int min, int max)
  195. {
  196. char errmsg[64];
  197. int value;
  198. if (!lua_isnil(l, optindex)) {
  199. value = luaL_checkinteger(l, optindex);
  200. snprintf(errmsg, sizeof(errmsg), "expected integer between %d and %d", min, max);
  201. luaL_argcheck(l, min <= value && value <= max, 1, errmsg);
  202. *setting = value;
  203. }
  204. lua_pushinteger(l, *setting);
  205. return 1;
  206. }
  207. /* Process enumerated arguments for a configuration function */
  208. static int json_enum_option(lua_State *l, int optindex, int *setting,
  209. const char **options, int bool_true)
  210. {
  211. static const char *bool_options[] = { "off", "on", NULL };
  212. if (!options) {
  213. options = bool_options;
  214. bool_true = 1;
  215. }
  216. if (!lua_isnil(l, optindex)) {
  217. if (bool_true && lua_isboolean(l, optindex))
  218. *setting = lua_toboolean(l, optindex) * bool_true;
  219. else
  220. *setting = luaL_checkoption(l, optindex, NULL, options);
  221. }
  222. if (bool_true && (*setting == 0 || *setting == bool_true))
  223. lua_pushboolean(l, *setting);
  224. else
  225. lua_pushstring(l, options[*setting]);
  226. return 1;
  227. }
  228. /* Configures handling of extremely sparse arrays:
  229. * convert: Convert extremely sparse arrays into objects? Otherwise error.
  230. * ratio: 0: always allow sparse; 1: never allow sparse; >1: use ratio
  231. * safe: Always use an array when the max index <= safe */
  232. static int json_cfg_encode_sparse_array(lua_State *l)
  233. {
  234. json_config_t *cfg = json_arg_init(l, 3);
  235. json_enum_option(l, 1, &cfg->encode_sparse_convert, NULL, 1);
  236. json_integer_option(l, 2, &cfg->encode_sparse_ratio, 0, INT_MAX);
  237. json_integer_option(l, 3, &cfg->encode_sparse_safe, 0, INT_MAX);
  238. return 3;
  239. }
  240. /* Configures the maximum number of nested arrays/objects allowed when
  241. * encoding */
  242. static int json_cfg_encode_max_depth(lua_State *l)
  243. {
  244. json_config_t *cfg = json_arg_init(l, 1);
  245. return json_integer_option(l, 1, &cfg->encode_max_depth, 1, INT_MAX);
  246. }
  247. /* Configures the maximum number of nested arrays/objects allowed when
  248. * encoding */
  249. static int json_cfg_decode_max_depth(lua_State *l)
  250. {
  251. json_config_t *cfg = json_arg_init(l, 1);
  252. return json_integer_option(l, 1, &cfg->decode_max_depth, 1, INT_MAX);
  253. }
  254. /* Configures number precision when converting doubles to text */
  255. static int json_cfg_encode_number_precision(lua_State *l)
  256. {
  257. json_config_t *cfg = json_arg_init(l, 1);
  258. return json_integer_option(l, 1, &cfg->encode_number_precision, 1, 14);
  259. }
  260. /* Configures JSON encoding buffer persistence */
  261. static int json_cfg_encode_keep_buffer(lua_State *l)
  262. {
  263. json_config_t *cfg = json_arg_init(l, 1);
  264. int old_value;
  265. old_value = cfg->encode_keep_buffer;
  266. json_enum_option(l, 1, &cfg->encode_keep_buffer, NULL, 1);
  267. /* Init / free the buffer if the setting has changed */
  268. if (old_value ^ cfg->encode_keep_buffer) {
  269. if (cfg->encode_keep_buffer)
  270. strbuf_init(&cfg->encode_buf, 0);
  271. else
  272. strbuf_free(&cfg->encode_buf);
  273. }
  274. return 1;
  275. }
  276. #if defined(DISABLE_INVALID_NUMBERS) && !defined(USE_INTERNAL_FPCONV)
  277. void json_verify_invalid_number_setting(lua_State *l, int *setting)
  278. {
  279. if (*setting == 1) {
  280. *setting = 0;
  281. luaL_error(l, "Infinity, NaN, and/or hexadecimal numbers are not supported.");
  282. }
  283. }
  284. #else
  285. #define json_verify_invalid_number_setting(l, s) do { } while(0)
  286. #endif
  287. static int json_cfg_encode_invalid_numbers(lua_State *l)
  288. {
  289. static const char *options[] = { "off", "on", "null", NULL };
  290. json_config_t *cfg = json_arg_init(l, 1);
  291. json_enum_option(l, 1, &cfg->encode_invalid_numbers, options, 1);
  292. json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
  293. return 1;
  294. }
  295. static int json_cfg_decode_invalid_numbers(lua_State *l)
  296. {
  297. json_config_t *cfg = json_arg_init(l, 1);
  298. json_enum_option(l, 1, &cfg->decode_invalid_numbers, NULL, 1);
  299. json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
  300. return 1;
  301. }
  302. static int json_destroy_config(lua_State *l)
  303. {
  304. json_config_t *cfg;
  305. cfg = lua_touserdata(l, 1);
  306. if (cfg)
  307. strbuf_free(&cfg->encode_buf);
  308. cfg = NULL;
  309. return 0;
  310. }
  311. static void json_create_config(lua_State *l)
  312. {
  313. json_config_t *cfg;
  314. int i;
  315. cfg = lua_newuserdata(l, sizeof(*cfg));
  316. /* Create GC method to clean up strbuf */
  317. lua_newtable(l);
  318. lua_pushcfunction(l, json_destroy_config);
  319. lua_setfield(l, -2, "__gc");
  320. lua_setmetatable(l, -2);
  321. cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
  322. cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
  323. cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
  324. cfg->encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH;
  325. cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
  326. cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
  327. cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
  328. cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
  329. cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;
  330. #if DEFAULT_ENCODE_KEEP_BUFFER > 0
  331. strbuf_init(&cfg->encode_buf, 0);
  332. #endif
  333. /* Decoding init */
  334. /* Tag all characters as an error */
  335. for (i = 0; i < 256; i++)
  336. cfg->ch2token[i] = T_ERROR;
  337. /* Set tokens that require no further processing */
  338. cfg->ch2token['{'] = T_OBJ_BEGIN;
  339. cfg->ch2token['}'] = T_OBJ_END;
  340. cfg->ch2token['['] = T_ARR_BEGIN;
  341. cfg->ch2token[']'] = T_ARR_END;
  342. cfg->ch2token[','] = T_COMMA;
  343. cfg->ch2token[':'] = T_COLON;
  344. cfg->ch2token['\0'] = T_END;
  345. cfg->ch2token[' '] = T_WHITESPACE;
  346. cfg->ch2token['\t'] = T_WHITESPACE;
  347. cfg->ch2token['\n'] = T_WHITESPACE;
  348. cfg->ch2token['\r'] = T_WHITESPACE;
  349. /* Update characters that require further processing */
  350. cfg->ch2token['f'] = T_UNKNOWN; /* false? */
  351. cfg->ch2token['i'] = T_UNKNOWN; /* inf, ininity? */
  352. cfg->ch2token['I'] = T_UNKNOWN;
  353. cfg->ch2token['n'] = T_UNKNOWN; /* null, nan? */
  354. cfg->ch2token['N'] = T_UNKNOWN;
  355. cfg->ch2token['t'] = T_UNKNOWN; /* true? */
  356. cfg->ch2token['"'] = T_UNKNOWN; /* string? */
  357. cfg->ch2token['+'] = T_UNKNOWN; /* number? */
  358. cfg->ch2token['-'] = T_UNKNOWN;
  359. for (i = 0; i < 10; i++)
  360. cfg->ch2token['0' + i] = T_UNKNOWN;
  361. /* Lookup table for parsing escape characters */
  362. for (i = 0; i < 256; i++)
  363. cfg->escape2char[i] = 0; /* String error */
  364. cfg->escape2char['"'] = '"';
  365. cfg->escape2char['\\'] = '\\';
  366. cfg->escape2char['/'] = '/';
  367. cfg->escape2char['b'] = '\b';
  368. cfg->escape2char['t'] = '\t';
  369. cfg->escape2char['n'] = '\n';
  370. cfg->escape2char['f'] = '\f';
  371. cfg->escape2char['r'] = '\r';
  372. cfg->escape2char['u'] = 'u'; /* Unicode parsing required */
  373. }
  374. /* ===== ENCODING ===== */
  375. static void json_encode_exception(lua_State *l, json_config_t *cfg, strbuf_t *json, int lindex,
  376. const char *reason)
  377. {
  378. if (!cfg->encode_keep_buffer)
  379. strbuf_free(json);
  380. luaL_error(l, "Cannot serialise %s: %s",
  381. lua_typename(l, lua_type(l, lindex)), reason);
  382. }
  383. /* json_append_string args:
  384. * - lua_State
  385. * - JSON strbuf
  386. * - String (Lua stack index)
  387. *
  388. * Returns nothing. Doesn't remove string from Lua stack */
  389. static void json_append_string(lua_State *l, strbuf_t *json, int lindex)
  390. {
  391. const char *escstr;
  392. int i;
  393. const char *str;
  394. size_t len;
  395. str = lua_tolstring(l, lindex, &len);
  396. /* Worst case is len * 6 (all unicode escapes).
  397. * This buffer is reused constantly for small strings
  398. * If there are any excess pages, they won't be hit anyway.
  399. * This gains ~5% speedup. */
  400. strbuf_ensure_empty_length(json, len * 6 + 2);
  401. strbuf_append_char_unsafe(json, '\"');
  402. for (i = 0; i < len; i++) {
  403. escstr = char2escape[(unsigned char)str[i]];
  404. if (escstr)
  405. strbuf_append_string(json, escstr);
  406. else
  407. strbuf_append_char_unsafe(json, str[i]);
  408. }
  409. strbuf_append_char_unsafe(json, '\"');
  410. }
  411. /* Find the size of the array on the top of the Lua stack
  412. * -1 object (not a pure array)
  413. * >=0 elements in array
  414. */
  415. static int lua_array_length(lua_State *l, json_config_t *cfg, strbuf_t *json)
  416. {
  417. double k;
  418. int max;
  419. int items;
  420. max = 0;
  421. items = 0;
  422. lua_pushnil(l);
  423. /* table, startkey */
  424. while (lua_next(l, -2) != 0) {
  425. /* table, key, value */
  426. if (lua_type(l, -2) == LUA_TNUMBER &&
  427. (k = lua_tonumber(l, -2))) {
  428. /* Integer >= 1 ? */
  429. if (floor(k) == k && k >= 1) {
  430. if (k > max)
  431. max = k;
  432. items++;
  433. lua_pop(l, 1);
  434. continue;
  435. }
  436. }
  437. /* Must not be an array (non integer key) */
  438. lua_pop(l, 2);
  439. return -1;
  440. }
  441. /* Encode excessively sparse arrays as objects (if enabled) */
  442. if (cfg->encode_sparse_ratio > 0 &&
  443. max > items * cfg->encode_sparse_ratio &&
  444. max > cfg->encode_sparse_safe) {
  445. if (!cfg->encode_sparse_convert)
  446. json_encode_exception(l, cfg, json, -1, "excessively sparse array");
  447. return -1;
  448. }
  449. return max;
  450. }
  451. static void json_check_encode_depth(lua_State *l, json_config_t *cfg,
  452. int current_depth, strbuf_t *json)
  453. {
  454. /* Ensure there are enough slots free to traverse a table (key,
  455. * value) and push a string for a potential error message.
  456. *
  457. * Unlike "decode", the key and value are still on the stack when
  458. * lua_checkstack() is called. Hence an extra slot for luaL_error()
  459. * below is required just in case the next check to lua_checkstack()
  460. * fails.
  461. *
  462. * While this won't cause a crash due to the EXTRA_STACK reserve
  463. * slots, it would still be an improper use of the API. */
  464. if (current_depth <= cfg->encode_max_depth && lua_checkstack(l, 3))
  465. return;
  466. if (!cfg->encode_keep_buffer)
  467. strbuf_free(json);
  468. luaL_error(l, "Cannot serialise, excessive nesting (%d)",
  469. current_depth);
  470. }
  471. static void json_append_data(lua_State *l, json_config_t *cfg,
  472. int current_depth, strbuf_t *json);
  473. /* json_append_array args:
  474. * - lua_State
  475. * - JSON strbuf
  476. * - Size of passwd Lua array (top of stack) */
  477. static void json_append_array(lua_State *l, json_config_t *cfg, int current_depth,
  478. strbuf_t *json, int array_length)
  479. {
  480. int comma, i;
  481. strbuf_append_char(json, '[');
  482. comma = 0;
  483. for (i = 1; i <= array_length; i++) {
  484. if (comma)
  485. strbuf_append_char(json, ',');
  486. else
  487. comma = 1;
  488. lua_rawgeti(l, -1, i);
  489. json_append_data(l, cfg, current_depth, json);
  490. lua_pop(l, 1);
  491. }
  492. strbuf_append_char(json, ']');
  493. }
  494. static void json_append_number(lua_State *l, json_config_t *cfg,
  495. strbuf_t *json, int lindex)
  496. {
  497. double num = lua_tonumber(l, lindex);
  498. int len;
  499. if (cfg->encode_invalid_numbers == 0) {
  500. /* Prevent encoding invalid numbers */
  501. if (isinf(num) || isnan(num))
  502. json_encode_exception(l, cfg, json, lindex, "must not be NaN or Inf");
  503. } else if (cfg->encode_invalid_numbers == 1) {
  504. /* Encode invalid numbers, but handle "nan" separately
  505. * since some platforms may encode as "-nan". */
  506. if (isnan(num)) {
  507. strbuf_append_mem(json, "nan", 3);
  508. return;
  509. }
  510. } else {
  511. /* Encode invalid numbers as "null" */
  512. if (isinf(num) || isnan(num)) {
  513. strbuf_append_mem(json, "null", 4);
  514. return;
  515. }
  516. }
  517. strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE);
  518. len = fpconv_g_fmt(strbuf_empty_ptr(json), num, cfg->encode_number_precision);
  519. strbuf_extend_length(json, len);
  520. }
  521. static void json_append_object(lua_State *l, json_config_t *cfg,
  522. int current_depth, strbuf_t *json)
  523. {
  524. int comma, keytype;
  525. /* Object */
  526. strbuf_append_char(json, '{');
  527. lua_pushnil(l);
  528. /* table, startkey */
  529. comma = 0;
  530. while (lua_next(l, -2) != 0) {
  531. if (comma)
  532. strbuf_append_char(json, ',');
  533. else
  534. comma = 1;
  535. /* table, key, value */
  536. keytype = lua_type(l, -2);
  537. if (keytype == LUA_TNUMBER) {
  538. strbuf_append_char(json, '"');
  539. json_append_number(l, cfg, json, -2);
  540. strbuf_append_mem(json, "\":", 2);
  541. } else if (keytype == LUA_TSTRING) {
  542. json_append_string(l, json, -2);
  543. strbuf_append_char(json, ':');
  544. } else {
  545. json_encode_exception(l, cfg, json, -2,
  546. "table key must be a number or string");
  547. /* never returns */
  548. }
  549. /* table, key, value */
  550. json_append_data(l, cfg, current_depth, json);
  551. lua_pop(l, 1);
  552. /* table, key */
  553. }
  554. strbuf_append_char(json, '}');
  555. }
  556. /* Serialise Lua data into JSON string. */
  557. static void json_append_data(lua_State *l, json_config_t *cfg,
  558. int current_depth, strbuf_t *json)
  559. {
  560. int len;
  561. switch (lua_type(l, -1)) {
  562. case LUA_TSTRING:
  563. json_append_string(l, json, -1);
  564. break;
  565. case LUA_TNUMBER:
  566. json_append_number(l, cfg, json, -1);
  567. break;
  568. case LUA_TBOOLEAN:
  569. if (lua_toboolean(l, -1))
  570. strbuf_append_mem(json, "true", 4);
  571. else
  572. strbuf_append_mem(json, "false", 5);
  573. break;
  574. case LUA_TTABLE:
  575. current_depth++;
  576. json_check_encode_depth(l, cfg, current_depth, json);
  577. len = lua_array_length(l, cfg, json);
  578. if (len > 0)
  579. json_append_array(l, cfg, current_depth, json, len);
  580. else
  581. json_append_object(l, cfg, current_depth, json);
  582. break;
  583. case LUA_TNIL:
  584. strbuf_append_mem(json, "null", 4);
  585. break;
  586. case LUA_TLIGHTUSERDATA:
  587. if (lua_touserdata(l, -1) == NULL) {
  588. strbuf_append_mem(json, "null", 4);
  589. break;
  590. }
  591. default:
  592. /* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD,
  593. * and LUA_TLIGHTUSERDATA) cannot be serialised */
  594. json_encode_exception(l, cfg, json, -1, "type not supported");
  595. /* never returns */
  596. }
  597. }
  598. static int json_encode(lua_State *l)
  599. {
  600. json_config_t *cfg = json_fetch_config(l);
  601. strbuf_t local_encode_buf;
  602. strbuf_t *encode_buf;
  603. char *json;
  604. int len;
  605. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  606. if (!cfg->encode_keep_buffer) {
  607. /* Use private buffer */
  608. encode_buf = &local_encode_buf;
  609. strbuf_init(encode_buf, 0);
  610. } else {
  611. /* Reuse existing buffer */
  612. encode_buf = &cfg->encode_buf;
  613. strbuf_reset(encode_buf);
  614. }
  615. json_append_data(l, cfg, 0, encode_buf);
  616. json = strbuf_string(encode_buf, &len);
  617. lua_pushlstring(l, json, len);
  618. if (!cfg->encode_keep_buffer)
  619. strbuf_free(encode_buf);
  620. return 1;
  621. }
  622. /* ===== DECODING ===== */
  623. static void json_process_value(lua_State *l, json_parse_t *json,
  624. json_token_t *token);
  625. static int hexdigit2int(char hex)
  626. {
  627. if ('0' <= hex && hex <= '9')
  628. return hex - '0';
  629. /* Force lowercase */
  630. hex |= 0x20;
  631. if ('a' <= hex && hex <= 'f')
  632. return 10 + hex - 'a';
  633. return -1;
  634. }
  635. static int decode_hex4(const char *hex)
  636. {
  637. int digit[4];
  638. int i;
  639. /* Convert ASCII hex digit to numeric digit
  640. * Note: this returns an error for invalid hex digits, including
  641. * NULL */
  642. for (i = 0; i < 4; i++) {
  643. digit[i] = hexdigit2int(hex[i]);
  644. if (digit[i] < 0) {
  645. return -1;
  646. }
  647. }
  648. return (digit[0] << 12) +
  649. (digit[1] << 8) +
  650. (digit[2] << 4) +
  651. digit[3];
  652. }
  653. /* Converts a Unicode codepoint to UTF-8.
  654. * Returns UTF-8 string length, and up to 4 bytes in *utf8 */
  655. static int codepoint_to_utf8(char *utf8, int codepoint)
  656. {
  657. /* 0xxxxxxx */
  658. if (codepoint <= 0x7F) {
  659. utf8[0] = codepoint;
  660. return 1;
  661. }
  662. /* 110xxxxx 10xxxxxx */
  663. if (codepoint <= 0x7FF) {
  664. utf8[0] = (codepoint >> 6) | 0xC0;
  665. utf8[1] = (codepoint & 0x3F) | 0x80;
  666. return 2;
  667. }
  668. /* 1110xxxx 10xxxxxx 10xxxxxx */
  669. if (codepoint <= 0xFFFF) {
  670. utf8[0] = (codepoint >> 12) | 0xE0;
  671. utf8[1] = ((codepoint >> 6) & 0x3F) | 0x80;
  672. utf8[2] = (codepoint & 0x3F) | 0x80;
  673. return 3;
  674. }
  675. /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
  676. if (codepoint <= 0x1FFFFF) {
  677. utf8[0] = (codepoint >> 18) | 0xF0;
  678. utf8[1] = ((codepoint >> 12) & 0x3F) | 0x80;
  679. utf8[2] = ((codepoint >> 6) & 0x3F) | 0x80;
  680. utf8[3] = (codepoint & 0x3F) | 0x80;
  681. return 4;
  682. }
  683. return 0;
  684. }
  685. /* Called when index pointing to beginning of UTF-16 code escape: \uXXXX
  686. * \u is guaranteed to exist, but the remaining hex characters may be
  687. * missing.
  688. * Translate to UTF-8 and append to temporary token string.
  689. * Must advance index to the next character to be processed.
  690. * Returns: 0 success
  691. * -1 error
  692. */
  693. static int json_append_unicode_escape(json_parse_t *json)
  694. {
  695. char utf8[4]; /* Surrogate pairs require 4 UTF-8 bytes */
  696. int codepoint;
  697. int surrogate_low;
  698. int len;
  699. int escape_len = 6;
  700. /* Fetch UTF-16 code unit */
  701. codepoint = decode_hex4(json->ptr + 2);
  702. if (codepoint < 0)
  703. return -1;
  704. /* UTF-16 surrogate pairs take the following 2 byte form:
  705. * 11011 x yyyyyyyyyy
  706. * When x = 0: y is the high 10 bits of the codepoint
  707. * x = 1: y is the low 10 bits of the codepoint
  708. *
  709. * Check for a surrogate pair (high or low) */
  710. if ((codepoint & 0xF800) == 0xD800) {
  711. /* Error if the 1st surrogate is not high */
  712. if (codepoint & 0x400)
  713. return -1;
  714. /* Ensure the next code is a unicode escape */
  715. if (*(json->ptr + escape_len) != '\\' ||
  716. *(json->ptr + escape_len + 1) != 'u') {
  717. return -1;
  718. }
  719. /* Fetch the next codepoint */
  720. surrogate_low = decode_hex4(json->ptr + 2 + escape_len);
  721. if (surrogate_low < 0)
  722. return -1;
  723. /* Error if the 2nd code is not a low surrogate */
  724. if ((surrogate_low & 0xFC00) != 0xDC00)
  725. return -1;
  726. /* Calculate Unicode codepoint */
  727. codepoint = (codepoint & 0x3FF) << 10;
  728. surrogate_low &= 0x3FF;
  729. codepoint = (codepoint | surrogate_low) + 0x10000;
  730. escape_len = 12;
  731. }
  732. /* Convert codepoint to UTF-8 */
  733. len = codepoint_to_utf8(utf8, codepoint);
  734. if (!len)
  735. return -1;
  736. /* Append bytes and advance parse index */
  737. strbuf_append_mem_unsafe(json->tmp, utf8, len);
  738. json->ptr += escape_len;
  739. return 0;
  740. }
  741. static void json_set_token_error(json_token_t *token, json_parse_t *json,
  742. const char *errtype)
  743. {
  744. token->type = T_ERROR;
  745. token->index = json->ptr - json->data;
  746. token->value.string = errtype;
  747. }
  748. static void json_next_string_token(json_parse_t *json, json_token_t *token)
  749. {
  750. char *escape2char = json->cfg->escape2char;
  751. char ch;
  752. /* Caller must ensure a string is next */
  753. assert(*json->ptr == '"');
  754. /* Skip " */
  755. json->ptr++;
  756. /* json->tmp is the temporary strbuf used to accumulate the
  757. * decoded string value.
  758. * json->tmp is sized to handle JSON containing only a string value.
  759. */
  760. strbuf_reset(json->tmp);
  761. while ((ch = *json->ptr) != '"') {
  762. if (!ch) {
  763. /* Premature end of the string */
  764. json_set_token_error(token, json, "unexpected end of string");
  765. return;
  766. }
  767. /* Handle escapes */
  768. if (ch == '\\') {
  769. /* Fetch escape character */
  770. ch = *(json->ptr + 1);
  771. /* Translate escape code and append to tmp string */
  772. ch = escape2char[(unsigned char)ch];
  773. if (ch == 'u') {
  774. if (json_append_unicode_escape(json) == 0)
  775. continue;
  776. json_set_token_error(token, json,
  777. "invalid unicode escape code");
  778. return;
  779. }
  780. if (!ch) {
  781. json_set_token_error(token, json, "invalid escape code");
  782. return;
  783. }
  784. /* Skip '\' */
  785. json->ptr++;
  786. }
  787. /* Append normal character or translated single character
  788. * Unicode escapes are handled above */
  789. strbuf_append_char_unsafe(json->tmp, ch);
  790. json->ptr++;
  791. }
  792. json->ptr++; /* Eat final quote (") */
  793. strbuf_ensure_null(json->tmp);
  794. token->type = T_STRING;
  795. token->value.string = strbuf_string(json->tmp, &token->string_len);
  796. }
  797. /* JSON numbers should take the following form:
  798. * -?(0|[1-9]|[1-9][0-9]+)(.[0-9]+)?([eE][-+]?[0-9]+)?
  799. *
  800. * json_next_number_token() uses strtod() which allows other forms:
  801. * - numbers starting with '+'
  802. * - NaN, -NaN, infinity, -infinity
  803. * - hexadecimal numbers
  804. * - numbers with leading zeros
  805. *
  806. * json_is_invalid_number() detects "numbers" which may pass strtod()'s
  807. * error checking, but should not be allowed with strict JSON.
  808. *
  809. * json_is_invalid_number() may pass numbers which cause strtod()
  810. * to generate an error.
  811. */
  812. static int json_is_invalid_number(json_parse_t *json)
  813. {
  814. const char *p = json->ptr;
  815. /* Reject numbers starting with + */
  816. if (*p == '+')
  817. return 1;
  818. /* Skip minus sign if it exists */
  819. if (*p == '-')
  820. p++;
  821. /* Reject numbers starting with 0x, or leading zeros */
  822. if (*p == '0') {
  823. int ch2 = *(p + 1);
  824. if ((ch2 | 0x20) == 'x' || /* Hex */
  825. ('0' <= ch2 && ch2 <= '9')) /* Leading zero */
  826. return 1;
  827. return 0;
  828. } else if (*p <= '9') {
  829. return 0; /* Ordinary number */
  830. }
  831. /* Reject inf/nan */
  832. if (!strncasecmp(p, "inf", 3))
  833. return 1;
  834. if (!strncasecmp(p, "nan", 3))
  835. return 1;
  836. /* Pass all other numbers which may still be invalid, but
  837. * strtod() will catch them. */
  838. return 0;
  839. }
  840. static void json_next_number_token(json_parse_t *json, json_token_t *token)
  841. {
  842. char *endptr;
  843. token->type = T_NUMBER;
  844. token->value.number = fpconv_strtod(json->ptr, &endptr);
  845. if (json->ptr == endptr)
  846. json_set_token_error(token, json, "invalid number");
  847. else
  848. json->ptr = endptr; /* Skip the processed number */
  849. return;
  850. }
  851. /* Fills in the token struct.
  852. * T_STRING will return a pointer to the json_parse_t temporary string
  853. * T_ERROR will leave the json->ptr pointer at the error.
  854. */
  855. static void json_next_token(json_parse_t *json, json_token_t *token)
  856. {
  857. const json_token_type_t *ch2token = json->cfg->ch2token;
  858. int ch;
  859. /* Eat whitespace. */
  860. while (1) {
  861. ch = (unsigned char)*(json->ptr);
  862. token->type = ch2token[ch];
  863. if (token->type != T_WHITESPACE)
  864. break;
  865. json->ptr++;
  866. }
  867. /* Store location of new token. Required when throwing errors
  868. * for unexpected tokens (syntax errors). */
  869. token->index = json->ptr - json->data;
  870. /* Don't advance the pointer for an error or the end */
  871. if (token->type == T_ERROR) {
  872. json_set_token_error(token, json, "invalid token");
  873. return;
  874. }
  875. if (token->type == T_END) {
  876. return;
  877. }
  878. /* Found a known single character token, advance index and return */
  879. if (token->type != T_UNKNOWN) {
  880. json->ptr++;
  881. return;
  882. }
  883. /* Process characters which triggered T_UNKNOWN
  884. *
  885. * Must use strncmp() to match the front of the JSON string.
  886. * JSON identifier must be lowercase.
  887. * When strict_numbers if disabled, either case is allowed for
  888. * Infinity/NaN (since we are no longer following the spec..) */
  889. if (ch == '"') {
  890. json_next_string_token(json, token);
  891. return;
  892. } else if (ch == '-' || ('0' <= ch && ch <= '9')) {
  893. if (!json->cfg->decode_invalid_numbers && json_is_invalid_number(json)) {
  894. json_set_token_error(token, json, "invalid number");
  895. return;
  896. }
  897. json_next_number_token(json, token);
  898. return;
  899. } else if (!strncmp(json->ptr, "true", 4)) {
  900. token->type = T_BOOLEAN;
  901. token->value.boolean = 1;
  902. json->ptr += 4;
  903. return;
  904. } else if (!strncmp(json->ptr, "false", 5)) {
  905. token->type = T_BOOLEAN;
  906. token->value.boolean = 0;
  907. json->ptr += 5;
  908. return;
  909. } else if (!strncmp(json->ptr, "null", 4)) {
  910. token->type = T_NULL;
  911. json->ptr += 4;
  912. return;
  913. } else if (json->cfg->decode_invalid_numbers &&
  914. json_is_invalid_number(json)) {
  915. /* When decode_invalid_numbers is enabled, only attempt to process
  916. * numbers we know are invalid JSON (Inf, NaN, hex)
  917. * This is required to generate an appropriate token error,
  918. * otherwise all bad tokens will register as "invalid number"
  919. */
  920. json_next_number_token(json, token);
  921. return;
  922. }
  923. /* Token starts with t/f/n but isn't recognised above. */
  924. json_set_token_error(token, json, "invalid token");
  925. }
  926. /* This function does not return.
  927. * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED.
  928. * The only supported exception is the temporary parser string
  929. * json->tmp struct.
  930. * json and token should exist on the stack somewhere.
  931. * luaL_error() will long_jmp and release the stack */
  932. static void json_throw_parse_error(lua_State *l, json_parse_t *json,
  933. const char *exp, json_token_t *token)
  934. {
  935. const char *found;
  936. strbuf_free(json->tmp);
  937. if (token->type == T_ERROR)
  938. found = token->value.string;
  939. else
  940. found = json_token_type_name[token->type];
  941. /* Note: token->index is 0 based, display starting from 1 */
  942. luaL_error(l, "Expected %s but found %s at character %d",
  943. exp, found, token->index + 1);
  944. }
  945. static inline void json_decode_ascend(json_parse_t *json)
  946. {
  947. json->current_depth--;
  948. }
  949. static void json_decode_descend(lua_State *l, json_parse_t *json, int slots)
  950. {
  951. json->current_depth++;
  952. if (json->current_depth <= json->cfg->decode_max_depth &&
  953. lua_checkstack(l, slots)) {
  954. return;
  955. }
  956. strbuf_free(json->tmp);
  957. luaL_error(l, "Found too many nested data structures (%d) at character %d",
  958. json->current_depth, json->ptr - json->data);
  959. }
  960. static void json_parse_object_context(lua_State *l, json_parse_t *json)
  961. {
  962. json_token_t token;
  963. /* 3 slots required:
  964. * .., table, key, value */
  965. json_decode_descend(l, json, 3);
  966. lua_newtable(l);
  967. json_next_token(json, &token);
  968. /* Handle empty objects */
  969. if (token.type == T_OBJ_END) {
  970. json_decode_ascend(json);
  971. return;
  972. }
  973. while (1) {
  974. if (token.type != T_STRING)
  975. json_throw_parse_error(l, json, "object key string", &token);
  976. /* Push key */
  977. lua_pushlstring(l, token.value.string, token.string_len);
  978. json_next_token(json, &token);
  979. if (token.type != T_COLON)
  980. json_throw_parse_error(l, json, "colon", &token);
  981. /* Fetch value */
  982. json_next_token(json, &token);
  983. json_process_value(l, json, &token);
  984. /* Set key = value */
  985. lua_rawset(l, -3);
  986. json_next_token(json, &token);
  987. if (token.type == T_OBJ_END) {
  988. json_decode_ascend(json);
  989. return;
  990. }
  991. if (token.type != T_COMMA)
  992. json_throw_parse_error(l, json, "comma or object end", &token);
  993. json_next_token(json, &token);
  994. }
  995. }
  996. /* Handle the array context */
  997. static void json_parse_array_context(lua_State *l, json_parse_t *json)
  998. {
  999. json_token_t token;
  1000. int i;
  1001. /* 2 slots required:
  1002. * .., table, value */
  1003. json_decode_descend(l, json, 2);
  1004. lua_newtable(l);
  1005. json_next_token(json, &token);
  1006. /* Handle empty arrays */
  1007. if (token.type == T_ARR_END) {
  1008. json_decode_ascend(json);
  1009. return;
  1010. }
  1011. for (i = 1; ; i++) {
  1012. json_process_value(l, json, &token);
  1013. lua_rawseti(l, -2, i); /* arr[i] = value */
  1014. json_next_token(json, &token);
  1015. if (token.type == T_ARR_END) {
  1016. json_decode_ascend(json);
  1017. return;
  1018. }
  1019. if (token.type != T_COMMA)
  1020. json_throw_parse_error(l, json, "comma or array end", &token);
  1021. json_next_token(json, &token);
  1022. }
  1023. }
  1024. /* Handle the "value" context */
  1025. static void json_process_value(lua_State *l, json_parse_t *json,
  1026. json_token_t *token)
  1027. {
  1028. switch (token->type) {
  1029. case T_STRING:
  1030. lua_pushlstring(l, token->value.string, token->string_len);
  1031. break;;
  1032. case T_NUMBER:
  1033. lua_pushnumber(l, token->value.number);
  1034. break;;
  1035. case T_BOOLEAN:
  1036. lua_pushboolean(l, token->value.boolean);
  1037. break;;
  1038. case T_OBJ_BEGIN:
  1039. json_parse_object_context(l, json);
  1040. break;;
  1041. case T_ARR_BEGIN:
  1042. json_parse_array_context(l, json);
  1043. break;;
  1044. case T_NULL:
  1045. /* In Lua, setting "t[k] = nil" will delete k from the table.
  1046. * Hence a NULL pointer lightuserdata object is used instead */
  1047. lua_pushlightuserdata(l, NULL);
  1048. break;;
  1049. default:
  1050. json_throw_parse_error(l, json, "value", token);
  1051. }
  1052. }
  1053. static int json_decode(lua_State *l)
  1054. {
  1055. json_parse_t json;
  1056. json_token_t token;
  1057. size_t json_len;
  1058. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1059. json.cfg = json_fetch_config(l);
  1060. json.data = luaL_checklstring(l, 1, &json_len);
  1061. json.current_depth = 0;
  1062. json.ptr = json.data;
  1063. /* Detect Unicode other than UTF-8 (see RFC 4627, Sec 3)
  1064. *
  1065. * CJSON can support any simple data type, hence only the first
  1066. * character is guaranteed to be ASCII (at worst: '"'). This is
  1067. * still enough to detect whether the wrong encoding is in use. */
  1068. if (json_len >= 2 && (!json.data[0] || !json.data[1]))
  1069. luaL_error(l, "JSON parser does not support UTF-16 or UTF-32");
  1070. /* Ensure the temporary buffer can hold the entire string.
  1071. * This means we no longer need to do length checks since the decoded
  1072. * string must be smaller than the entire json string */
  1073. json.tmp = strbuf_new(json_len);
  1074. json_next_token(&json, &token);
  1075. json_process_value(l, &json, &token);
  1076. /* Ensure there is no more input left */
  1077. json_next_token(&json, &token);
  1078. if (token.type != T_END)
  1079. json_throw_parse_error(l, &json, "the end", &token);
  1080. strbuf_free(json.tmp);
  1081. return 1;
  1082. }
  1083. /* ===== INITIALISATION ===== */
  1084. #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
  1085. /* Compatibility for Lua 5.1.
  1086. *
  1087. * luaL_setfuncs() is used to create a module table where the functions have
  1088. * json_config_t as their first upvalue. Code borrowed from Lua 5.2 source. */
  1089. static void luaL_setfuncs (lua_State *l, const luaL_Reg *reg, int nup)
  1090. {
  1091. int i;
  1092. luaL_checkstack(l, nup, "too many upvalues");
  1093. for (; reg->name != NULL; reg++) { /* fill the table with given functions */
  1094. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  1095. lua_pushvalue(l, -nup);
  1096. lua_pushcclosure(l, reg->func, nup); /* closure with those upvalues */
  1097. lua_setfield(l, -(nup + 2), reg->name);
  1098. }
  1099. lua_pop(l, nup); /* remove upvalues */
  1100. }
  1101. #endif
  1102. static int lua_cjson_new(lua_State *l)
  1103. {
  1104. luaL_Reg reg[] = {
  1105. { "encode", json_encode },
  1106. { "decode", json_decode },
  1107. { "encode_sparse_array", json_cfg_encode_sparse_array },
  1108. { "encode_max_depth", json_cfg_encode_max_depth },
  1109. { "decode_max_depth", json_cfg_decode_max_depth },
  1110. { "encode_number_precision", json_cfg_encode_number_precision },
  1111. { "encode_keep_buffer", json_cfg_encode_keep_buffer },
  1112. { "encode_invalid_numbers", json_cfg_encode_invalid_numbers },
  1113. { "decode_invalid_numbers", json_cfg_decode_invalid_numbers },
  1114. { "new", lua_cjson_new },
  1115. { NULL, NULL }
  1116. };
  1117. /* Initialise number conversions */
  1118. fpconv_init();
  1119. /* cjson module table */
  1120. lua_newtable(l);
  1121. /* Register functions with config data as upvalue */
  1122. json_create_config(l);
  1123. luaL_setfuncs(l, reg, 1);
  1124. /* Set cjson.null */
  1125. lua_pushlightuserdata(l, NULL);
  1126. lua_setfield(l, -2, "null");
  1127. /* Set module name / version fields */
  1128. lua_pushliteral(l, CJSON_MODNAME);
  1129. lua_setfield(l, -2, "_NAME");
  1130. lua_pushliteral(l, CJSON_VERSION);
  1131. lua_setfield(l, -2, "_VERSION");
  1132. return 1;
  1133. }
  1134. int luaopen_cjson(lua_State *l)
  1135. {
  1136. lua_cjson_new(l);
  1137. #ifdef ENABLE_CJSON_GLOBAL
  1138. /* Register a global "cjson" table. */
  1139. lua_pushvalue(l, -1);
  1140. lua_setglobal(l, CJSON_MODNAME);
  1141. #endif
  1142. /* Return cjson table */
  1143. return 1;
  1144. }
  1145. /* vi:ai et sw=4 ts=4:
  1146. */