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