Debian Codegraph @

plugins/cfpython/cjson.c

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 /*
2 * Copyright (C) 2006-2007 Dan Pascu.
3 * Author: Dan Pascu <[email protected]>
4 *
5 * Fast JSON encoder/decoder implementation for Python
6 * This file is under GPL licence
7 */
8
9 #include <cfpython.h>
10 #include <Python.h>
11 #include <stddef.h>
12 #include <stdio.h>
13 #include <ctype.h>
14 #include <math.h>
15
16 #if defined(IS_PY26)
17 # include <bytesobject.h>
18 #elif !defined(IS_PY3K)
19 /* Python versions 2.5 or older doesn't have bytesobject.h */
20 # define PyBytesObject PyStringObject
21
22 # define PyBytes_Check PyString_Check
23 # define PyBytes_AS_STRING PyString_AS_STRING
24 # define PyBytes_GET_SIZE PyString_GET_SIZE
25
26 # define PyBytes_FromStringAndSize PyString_FromStringAndSize
27 # define PyBytes_FromString PyString_FromString
28 # define PyBytes_Size PyString_Size
29 # define PyBytes_AsString PyString_AsString
30 # define PyBytes_Concat PyString_Concat
31 # define PyBytes_ConcatAndDel PyString_ConcatAndDel
32 # define _PyBytes_Resize _PyString_Resize
33 # define PyBytes_DecodeEscape PyString_DecodeEscape
34 # define _PyBytes_Join _PyString_Join
35 # define PyBytes_AsStringAndSize PyString_AsStringAndSize
36 #endif
37
38 typedef struct JSONData {
39 char *str; /* the actual json string */
40 char *end; /* pointer to the string end */
41 char *ptr; /* pointer to the current parsing position */
42 int all_unicode; /* make all output strings unicode if true */
43 } JSONData;
44
45 static PyObject *encode_object(PyObject *object);
46 static PyObject *encode_string(PyObject *object);
47 static PyObject *encode_unicode(PyObject *object);
48 static PyObject *encode_tuple(PyObject *object);
49 static PyObject *encode_list(PyObject *object);
50 static PyObject *encode_dict(PyObject *object);
51
52 static PyObject *decode_json(JSONData *jsondata);
53 static PyObject *decode_null(JSONData *jsondata);
54 static PyObject *decode_bool(JSONData *jsondata);
55 static PyObject *decode_string(JSONData *jsondata);
56 static PyObject *decode_inf(JSONData *jsondata);
57 static PyObject *decode_nan(JSONData *jsondata);
58 static PyObject *decode_number(JSONData *jsondata);
59 static PyObject *decode_array(JSONData *jsondata);
60 static PyObject *decode_object(JSONData *jsondata);
61
62 static PyObject *JSON_Error;
63 static PyObject *JSON_EncodeError;
64 static PyObject *JSON_DecodeError;
65
66 #if PY_VERSION_HEX < 0x02050000
67 typedef int Py_ssize_t;
68
69 #define PY_SSIZE_T_MAX INT_MAX
70 #define PY_SSIZE_T_MIN INT_MIN
71
72 #define SSIZE_T_F "%d"
73 #else
74 #define SSIZE_T_F "%zd"
75 #endif
76
77 #define True 1
78 #define False 0
79
80 #ifndef INFINITY
81 #define INFINITY HUGE_VAL
82 #endif
83
84 #ifndef NAN
85 #define NAN (HUGE_VAL-HUGE_VAL)
86 #endif
87
88 #ifndef Py_IS_NAN
89 #define Py_IS_NAN(X) ((X) != (X))
90 #endif
91
92 #define skipSpaces(d) while (*((d)->ptr) && isspace(*((d)->ptr))) (d)->ptr++
93
94 /* ------------------------------ Utility ----------------------------- */
95
96 #ifdef IS_PY3K
97 /** Same as PyObject_Str but return a UTF-8 encoded Bytes object instead. */
98 static PyObject* cjson_PyObject_Str(PyObject* obj) {
99 PyObject *tmp_str, *result;
100 tmp_str = PyObject_Str(obj);
101 if (!tmp_str)
102 return NULL;
103 result = PyUnicode_AsUTF8String(tmp_str);
104 Py_DECREF(tmp_str);
105 return result;
106 }
107 #else
108 # define cjson_PyObject_Str PyObject_Str
109 #endif
110
111 /* ------------------------------ Decoding ----------------------------- */
112
113 static void getRowAndCol(char *begin, char *current, int *row, int *col) {
114 *col = 1;
115 *row = 1;
116 while (current > begin) {
117 if (*current == '\n')
118 (*row)++;
119 if (*row < 2)
120 (*col)++;
121 current--;
122 }
123 }
124 static PyObject *decode_null(JSONData *jsondata) {
125 ptrdiff_t left;
126
127 left = jsondata->end-jsondata->ptr;
128
129 if (left >= 4 && strncmp(jsondata->ptr, "null", 4) == 0) {
130 jsondata->ptr += 4;
131 Py_INCREF(Py_None);
132 return Py_None;
133 } else {
134 int row, col;
135
136 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
137 PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s" "(row "SSIZE_T_F", col "SSIZE_T_F")", jsondata->ptr, (Py_ssize_t)row, (Py_ssize_t)col);
138 return NULL;
139 }
140 }
141
142 static PyObject *decode_bool(JSONData *jsondata) {
143 ptrdiff_t left;
144
145 left = jsondata->end-jsondata->ptr;
146
147 if (left >= 4 && strncmp(jsondata->ptr, "true", 4) == 0) {
148 jsondata->ptr += 4;
149 Py_INCREF(Py_True);
150 return Py_True;
151 } else if (left >= 5 && strncmp(jsondata->ptr, "false", 5) == 0) {
152 jsondata->ptr += 5;
153 Py_INCREF(Py_False);
154 return Py_False;
155 } else {
156 int row, col;
157
158 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
159 PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s" "(row "SSIZE_T_F", col "SSIZE_T_F")", jsondata->ptr, (Py_ssize_t)row, (Py_ssize_t)col);
160 return NULL;
161 }
162 }
163
164 static PyObject *decode_string(JSONData *jsondata) {
165 PyObject *object;
166 int c, escaping, has_unicode, string_escape;
167 Py_ssize_t len;
168 char *ptr;
169
170 /* look for the closing quote */
171 escaping = has_unicode = string_escape = False;
172 ptr = jsondata->ptr+1;
173 while (True) {
174 c = *ptr;
175 if (c == 0) {
176 int row, col;
177
178 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
179 PyErr_Format(JSON_DecodeError, "unterminated string starting at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
180 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
181 return NULL;
182 }
183 if (!escaping) {
184 if (c == '\\') {
185 escaping = True;
186 } else if (c == '"') {
187 break;
188 } else if (!isascii(c)) {
189 has_unicode = True;
190 }
191 } else {
192 switch (c) {
193 case 'u':
194 has_unicode = True;
195 break;
196 case '"':
197 case 'r':
198 case 'n':
199 case 't':
200 case 'b':
201 case 'f':
202 case '\\':
203 string_escape = True;
204 break;
205 }
206 escaping = False;
207 }
208 ptr++;
209 }
210
211 len = ptr-jsondata->ptr-1;
212
213 if (has_unicode || jsondata->all_unicode)
214 object = PyUnicode_DecodeUnicodeEscape(jsondata->ptr+1, len, NULL);
215 else if (string_escape)
216 object = PyBytes_DecodeEscape(jsondata->ptr+1, len, NULL, 0, NULL);
217 else
218 object = PyBytes_FromStringAndSize(jsondata->ptr+1, len);
219
220 if (object == NULL) {
221 PyObject *type, *value, *tb, *reason;
222
223 PyErr_Fetch(&type, &value, &tb);
224 if (type == NULL) {
225 int row, col;
226
227 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
228 PyErr_Format(JSON_DecodeError, "invalid string starting at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
229 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
230 } else {
231 if (PyErr_GivenExceptionMatches(type, PyExc_UnicodeDecodeError)) {
232 int row, col;
233
234 reason = PyObject_GetAttrString(value, "reason");
235 #ifdef IS_PY3K
236 /* If we are using Python3 we need to convert to bytes here. */
237 if (reason && PyUnicode_Check(reason)) {
238 PyObject * bytes_reason = PyUnicode_AsUTF8String(reason);
239 Py_DECREF(reason);
240 reason = bytes_reason;
241 }
242 #endif
243 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
244 PyErr_Format(JSON_DecodeError, "cannot decode string starting" " at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F"): %s",
245 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col,
246 reason ? PyBytes_AsString(reason) : "bad format");
247 Py_XDECREF(reason);
248 } else {
249 int row, col;
250
251 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
252 PyErr_Format(JSON_DecodeError, "invalid string starting at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
253 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
254 }
255 }
256 Py_XDECREF(type);
257 Py_XDECREF(value);
258 Py_XDECREF(tb);
259 } else {
260 jsondata->ptr = ptr+1;
261 }
262
263 return object;
264 }
265
266 static PyObject *decode_inf(JSONData *jsondata) {
267 PyObject *object;
268 ptrdiff_t left;
269
270 left = jsondata->end-jsondata->ptr;
271
272 if (left >= 8 && strncmp(jsondata->ptr, "Infinity", 8) == 0) {
273 jsondata->ptr += 8;
274 object = PyFloat_FromDouble(INFINITY);
275 return object;
276 } else if (left >= 9 && strncmp(jsondata->ptr, "+Infinity", 9) == 0) {
277 jsondata->ptr += 9;
278 object = PyFloat_FromDouble(INFINITY);
279 return object;
280 } else if (left >= 9 && strncmp(jsondata->ptr, "-Infinity", 9) == 0) {
281 jsondata->ptr += 9;
282 object = PyFloat_FromDouble(-INFINITY);
283 return object;
284 } else {
285 int row, col;
286
287 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
288 PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s (row "SSIZE_T_F", col "SSIZE_T_F")", jsondata->ptr, (Py_ssize_t)row, (Py_ssize_t)col);
289 return NULL;
290 }
291 }
292
293 static PyObject *decode_nan(JSONData *jsondata) {
294 PyObject *object;
295 ptrdiff_t left;
296
297 left = jsondata->end-jsondata->ptr;
298
299 if (left >= 3 && strncmp(jsondata->ptr, "NaN", 3) == 0) {
300 jsondata->ptr += 3;
301 object = PyFloat_FromDouble(NAN);
302 return object;
303 } else {
304 int row, col;
305 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
306 PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s(row "SSIZE_T_F", col "SSIZE_T_F")", jsondata->ptr, (Py_ssize_t)row, (Py_ssize_t)col);
307 return NULL;
308 }
309 }
310
311 static PyObject *decode_number(JSONData *jsondata) {
312 PyObject *object, *str;
313 int c, is_float, should_stop;
314 char *ptr;
315
316 /* check if we got a floating point number */
317 ptr = jsondata->ptr;
318 is_float = should_stop = False;
319 while (True) {
320 c = *ptr;
321 if (c == 0)
322 break;
323 switch (c) {
324 case '0':
325 case '1':
326 case '2':
327 case '3':
328 case '4':
329 case '5':
330 case '6':
331 case '7':
332 case '8':
333 case '9':
334 case '-':
335 case '+':
336 break;
337
338 case '.':
339 case 'e':
340 case 'E':
341 is_float = True;
342 break;
343
344 default:
345 should_stop = True;
346 }
347 if (should_stop) {
348 break;
349 }
350 ptr++;
351 }
352
353 str = PyBytes_FromStringAndSize(jsondata->ptr, ptr-jsondata->ptr);
354 if (str == NULL)
355 return NULL;
356
357 if (is_float) {
358 #ifdef IS_PY3K
359 object = PyFloat_FromString(str);
360 #else
361 object = PyFloat_FromString(str, NULL);
362 #endif
363 } else {
364 #ifdef IS_PY3K
365 object = PyLong_FromString(PyBytes_AS_STRING(str), NULL, 10);
366 #else
367 object = PyInt_FromString(PyBytes_AS_STRING(str), NULL, 10);
368 #endif
369 }
370
371 Py_DECREF(str);
372
373 if (object == NULL) {
374 int row, col;
375
376 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
377 PyErr_Format(JSON_DecodeError, "invalid number starting at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")", (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
378 } else {
379 jsondata->ptr = ptr;
380 }
381
382 return object;
383 }
384
385 static PyObject *decode_array(JSONData *jsondata) {
386 PyObject *object, *item;
387 int c, expect_item, items, result;
388 char *start;
389
390 object = PyList_New(0);
391
392 start = jsondata->ptr;
393 jsondata->ptr++;
394 expect_item = True;
395 items = 0;
396 while (True) {
397 skipSpaces(jsondata);
398 c = *jsondata->ptr;
399 if (c == 0) {
400 int row, col;
401
402 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
403 PyErr_Format(JSON_DecodeError, "unterminated array starting at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
404 (Py_ssize_t)(start-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
405 goto failure;
406 } else if (c == ']') {
407 if (expect_item && items > 0) {
408 int row, col;
409
410 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
411 PyErr_Format(JSON_DecodeError, "expecting array item at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
412 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
413 goto failure;
414 }
415 jsondata->ptr++;
416 break;
417 } else if (c == ',') {
418 if (expect_item) {
419 int row, col;
420
421 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
422 PyErr_Format(JSON_DecodeError, "expecting array item at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
423 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
424 goto failure;
425 }
426 expect_item = True;
427 jsondata->ptr++;
428 continue;
429 } else {
430 item = decode_json(jsondata);
431 if (item == NULL)
432 goto failure;
433 result = PyList_Append(object, item);
434 Py_DECREF(item);
435 if (result == -1)
436 goto failure;
437 expect_item = False;
438 items++;
439 }
440 }
441
442 return object;
443
444 failure:
445 Py_DECREF(object);
446 return NULL;
447 }
448
449 static PyObject *decode_object(JSONData *jsondata) {
450 PyObject *object, *key, *value;
451 int c, expect_key, items, result;
452 char *start;
453
454 object = PyDict_New();
455
456 expect_key = True;
457 items = 0;
458 start = jsondata->ptr;
459 jsondata->ptr++;
460
461 while (True) {
462 skipSpaces(jsondata);
463 c = *jsondata->ptr;
464 if (c == 0) {
465 int row, col;
466
467 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
468 PyErr_Format(JSON_DecodeError, "unterminated object starting at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
469 (Py_ssize_t)(start-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
470 goto failure;
471 } else if (c == '}') {
472 if (expect_key && items > 0) {
473 int row, col;
474
475 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
476 PyErr_Format(JSON_DecodeError, "expecting object property name at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
477 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
478 goto failure;
479 }
480 jsondata->ptr++;
481 break;
482 } else if (c == ',') {
483 if (expect_key) {
484 int row, col;
485
486 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
487 PyErr_Format(JSON_DecodeError, "expecting object property name at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
488 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
489 goto failure;
490 }
491 expect_key = True;
492 jsondata->ptr++;
493 continue;
494 } else {
495 if (c != '"') {
496 int row, col;
497
498 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
499 PyErr_Format(JSON_DecodeError, "expecting property name in object at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
500 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
501 goto failure;
502 }
503
504 key = decode_json(jsondata);
505 if (key == NULL)
506 goto failure;
507
508 skipSpaces(jsondata);
509 if (*jsondata->ptr != ':') {
510 int row, col;
511
512 getRowAndCol(jsondata->str, jsondata->ptr, &row, &col);
513 PyErr_Format(JSON_DecodeError, "missing colon after object property name at position "SSIZE_T_F"(row "SSIZE_T_F", col "SSIZE_T_F")",
514 (Py_ssize_t)(jsondata->ptr-jsondata->str), (Py_ssize_t)row, (Py_ssize_t)col);
515 Py_DECREF(key);
516 goto failure;
517 } else {
518 jsondata->ptr++;
519 }
520
521 value = decode_json(jsondata);
522 if (value == NULL) {
523 Py_DECREF(key);
524 goto failure;
525 }
526
527 result = PyDict_SetItem(object, key, value);
528 Py_DECREF(key);
529 Py_DECREF(value);
530 if (result == -1)
531 goto failure;
532 expect_key = False;
533 items++;
534 }
535 }
536
537 return object;
538
539 failure:
540 Py_DECREF(object);
541 return NULL;
542 }
543
544 static PyObject *decode_json(JSONData *jsondata) {
545 PyObject *object;
546
547 skipSpaces(jsondata);
548 switch (*jsondata->ptr) {
549 case 0:
550 PyErr_SetString(JSON_DecodeError, "empty JSON description");
551 return NULL;
552
553 case '{':
554 object = decode_object(jsondata);
555 break;
556
557 case '[':
558 object = decode_array(jsondata);
559 break;
560
561 case '"':
562 object = decode_string(jsondata);
563 break;
564
565 case 't':
566 case 'f':
567 object = decode_bool(jsondata);
568 break;
569
570 case 'n':
571 object = decode_null(jsondata);
572 break;
573
574 case 'N':
575 object = decode_nan(jsondata);
576 break;
577
578 case 'I':
579 object = decode_inf(jsondata);
580 break;
581
582 case '+':
583 case '-':
584 if (*(jsondata->ptr+1) == 'I') {
585 object = decode_inf(jsondata);
586 } else {
587 object = decode_number(jsondata);
588 }
589 break;
590
591 case '0':
592 case '1':
593 case '2':
594 case '3':
595 case '4':
596 case '5':
597 case '6':
598 case '7':
599 case '8':
600 case '9':
601 object = decode_number(jsondata);
602 break;
603
604 default:
605 PyErr_SetString(JSON_DecodeError, "cannot parse JSON description");
606 return NULL;
607 }
608
609 return object;
610 }
611
612 /* ------------------------------ Encoding ----------------------------- */
613
614 /*
615 * This function is an almost verbatim copy of PyString_Repr() from
616 * Python's stringobject.c with the following differences:
617 *
618 * - it always quotes the output using double quotes.
619 * - it also quotes \b and \f
620 * - it replaces any non ASCII character hh with \u00hh instead of \xhh
621 */
622 static PyObject *encode_string(PyObject *string) {
623 register PyBytesObject *op = (PyBytesObject *)string;
624 size_t newsize = 2+6*Py_SIZE(op);
625 PyObject *v;
626
627 if (Py_SIZE(op) > (PY_SSIZE_T_MAX-2)/6) {
628 PyErr_SetString(PyExc_OverflowError, "string is too large to make repr");
629 return NULL;
630 }
631 v = PyBytes_FromStringAndSize((char *)NULL, newsize);
632 if (v == NULL) {
633 return NULL;
634 } else {
635 register Py_ssize_t i;
636 register char c;
637 register char *p;
638 int quote;
639
640 quote = '"';
641
642 p = PyBytes_AS_STRING(v);
643 *p++ = quote;
644 for (i = 0; i < Py_SIZE(op); i++) {
645 /* There's at least enough room for a hex escape
646 and a closing quote. */
647 assert(newsize-(p-PyBytes_AS_STRING(v)) >= 7);
648 c = op->ob_sval[i];
649 if (c == quote || c == '\\')
650 *p++ = '\\', *p++ = c;
651 else if (c == '\t')
652 *p++ = '\\', *p++ = 't';
653 else if (c == '\n')
654 *p++ = '\\', *p++ = 'n';
655 else if (c == '\r')
656 *p++ = '\\', *p++ = 'r';
657 else if (c == '\f')
658 *p++ = '\\', *p++ = 'f';
659 else if (c == '\b')
660 *p++ = '\\', *p++ = 'b';
661 else if (c < ' ' || c >= 0x7f) {
662 /* For performance, we don't want to call
663 * PyOS_snprintf here (extra layers of
664 * function call). */
665 sprintf(p, "\\u%04x", c&0xff);
666 p += 6;
667 }
668 else
669 *p++ = c;
670 }
671 assert(newsize-(p-PyBytes_AS_STRING(v)) >= 1);
672 *p++ = quote;
673 *p = '\0';
674 _PyBytes_Resize(&v, (int) (p-PyBytes_AS_STRING(v)));
675 return v;
676 }
677 }
678
679 /*
680 * This function is an almost verbatim copy of unicodeescape_string() from
681 * Python's unicodeobject.c with the following differences:
682 *
683 * - it always quotes the output using double quotes.
684 * - it uses \u00hh instead of \xhh in output.
685 * - it also quotes \b and \f
686 */
687 #if defined(IS_PY26) || defined(IS_PY3K)
688 static PyObject *encode_unicode(PyObject *unicode) {
689 PyObject *repr;
•690 Py_ssize_t size, pos;
691 char *p;
692 static const char *hexdigit = "0123456789abcdef";
693 static const Py_ssize_t expandsize = 10;
694
•695 int kind = PyUnicode_KIND(unicode);
696 void *data = PyUnicode_DATA(unicode);
697 size = PyUnicode_GET_LENGTH(unicode);
698
699 if (size > (PY_SSIZE_T_MAX-2-1)/expandsize) {
700 PyErr_SetString(PyExc_OverflowError, "unicode object is too large to make repr");
701 return NULL;
702 }
703
704 repr = PyByteArray_FromStringAndSize(NULL,
705 2
706 + expandsize*size
707 + 1);
708 if (repr == NULL)
709 return NULL;
710
711 p = PyByteArray_AS_STRING(repr);
712
713 *p++ = '"';
•714 pos = 0;
715
•716 const Py_UCS4 quote = PyByteArray_AS_STRING(repr)[0];
717
718 while (pos < size) {
719 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
720 pos++;
721
722 /* Escape quotes */
•723 if ((ch == quote || ch == '\\')) {
724 *p++ = '\\';
725 *p++ = (char)ch;
726 continue;
727 }
•728
729 /* Map 21-bit characters to '\U00xxxxxx' */
730 else if (ch >= 0x10000) {
731 *p++ = '\\';
732 *p++ = 'U';
733 *p++ = hexdigit[(ch>>28)&0x0000000F];
734 *p++ = hexdigit[(ch>>24)&0x0000000F];
735 *p++ = hexdigit[(ch>>20)&0x0000000F];
736 *p++ = hexdigit[(ch>>16)&0x0000000F];
737 *p++ = hexdigit[(ch>>12)&0x0000000F];
738 *p++ = hexdigit[(ch>>8)&0x0000000F];
739 *p++ = hexdigit[(ch>>4)&0x0000000F];
740 *p++ = hexdigit[ch&0x0000000F];
741 continue;
742 }
743 /* Map 16-bit characters to '\uxxxx' */
744 if (ch >= 256) {
745 *p++ = '\\';
746 *p++ = 'u';
747 *p++ = hexdigit[(ch>>12)&0x000F];
748 *p++ = hexdigit[(ch>>8)&0x000F];
749 *p++ = hexdigit[(ch>>4)&0x000F];
750 *p++ = hexdigit[ch&0x000F];
751 /* Map special whitespace to '\t', \n', '\r', '\f', '\b' */
752 } else if (ch == '\t') {
753 *p++ = '\\';
754 *p++ = 't';
755 } else if (ch == '\n') {
756 *p++ = '\\';
757 *p++ = 'n';
758 } else if (ch == '\r') {
759 *p++ = '\\';
760 *p++ = 'r';
761 } else if (ch == '\f') {
762 *p++ = '\\';
763 *p++ = 'f';
764 } else if (ch == '\b') {
765 *p++ = '\\';
766 *p++ = 'b';
767 }
768
769 /* Map non-printable US ASCII to '\u00hh' */
770 else if (ch < ' ' || ch >= 0x7F) {
771 *p++ = '\\';
772 *p++ = 'u';
773 *p++ = '0';
774 *p++ = '0';
775 *p++ = hexdigit[(ch>>4)&0x000F];
776 *p++ = hexdigit[ch&0x000F];
777 }
778
779 /* Copy everything else as-is */
780 else
781 *p++ = (char)ch;
782 }
783
784 *p++ = PyByteArray_AS_STRING(repr)[0];
785
786 *p = '\0';
787 {
788 PyObject *result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(repr),
789 p - PyByteArray_AS_STRING(repr));
790 Py_DECREF(repr);
791 return result;
792 }
793 }
794 #else
795 static PyObject *encode_unicode(PyObject *unicode) {
796 PyObject *repr;
797 Py_UNICODE *s;
798 Py_ssize_t size;
799 char *p;
800 static const char *hexdigit = "0123456789abcdef";
801 #ifdef Py_UNICODE_WIDE
802 static const Py_ssize_t expandsize = 10;
803 #else
804 static const Py_ssize_t expandsize = 6;
805 #endif
806
807 s = PyUnicode_AS_UNICODE(unicode);
808 size = PyUnicode_GET_SIZE(unicode);
809
810 if (size > (PY_SSIZE_T_MAX-2-1)/expandsize) {
811 PyErr_SetString(PyExc_OverflowError, "unicode object is too large to make repr");
812 return NULL;
813 }
814
815 repr = PyString_FromStringAndSize(NULL, 2+expandsize*size+1);
816 if (repr == NULL)
817 return NULL;
818
819 p = PyString_AS_STRING(repr);
820
821 *p++ = '"';
822
823 while (size-- > 0) {
824 Py_UNICODE ch = *s++;
825
826 /* Escape quotes */
827 if ((ch == (Py_UNICODE)PyString_AS_STRING(repr)[0] || ch == '\\')) {
828 *p++ = '\\';
829 *p++ = (char)ch;
830 continue;
831 }
832 #ifdef Py_UNICODE_WIDE
833 /* Map 21-bit characters to '\U00xxxxxx' */
834 else if (ch >= 0x10000) {
835 int offset = p-PyString_AS_STRING(repr);
836
837 /* Resize the string if necessary */
838 if (offset+12 > PyString_GET_SIZE(repr)) {
839 if (_PyString_Resize(&repr, PyString_GET_SIZE(repr)+100))
840 return NULL;
841 p = PyString_AS_STRING(repr)+offset;
842 }
843
844 *p++ = '\\';
845 *p++ = 'U';
846 *p++ = hexdigit[(ch>>28)&0x0000000F];
847 *p++ = hexdigit[(ch>>24)&0x0000000F];
848 *p++ = hexdigit[(ch>>20)&0x0000000F];
849 *p++ = hexdigit[(ch>>16)&0x0000000F];
850 *p++ = hexdigit[(ch>>12)&0x0000000F];
851 *p++ = hexdigit[(ch>>8)&0x0000000F];
852 *p++ = hexdigit[(ch>>4)&0x0000000F];
853 *p++ = hexdigit[ch&0x0000000F];
854 continue;
855 }
856 #endif
857 /* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
858 else if (ch >= 0xD800 && ch < 0xDC00) {
859 Py_UNICODE ch2;
860 Py_UCS4 ucs;
861
862 ch2 = *s++;
863 size--;
864 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
865 ucs = (((ch&0x03FF)<<10)|(ch2&0x03FF))+0x00010000;
866 *p++ = '\\';
867 *p++ = 'U';
868 *p++ = hexdigit[(ucs>>28)&0x0000000F];
869 *p++ = hexdigit[(ucs>>24)&0x0000000F];
870 *p++ = hexdigit[(ucs>>20)&0x0000000F];
871 *p++ = hexdigit[(ucs>>16)&0x0000000F];
872 *p++ = hexdigit[(ucs>>12)&0x0000000F];
873 *p++ = hexdigit[(ucs>>8)&0x0000000F];
874 *p++ = hexdigit[(ucs>>4)&0x0000000F];
875 *p++ = hexdigit[ucs&0x0000000F];
876 continue;
877 }
878 /* Fall through: isolated surrogates are copied as-is */
879 s--;
880 size++;
881 /* Map 16-bit characters to '\uxxxx' */
882 } if (ch >= 256) {
883 *p++ = '\\';
884 *p++ = 'u';
885 *p++ = hexdigit[(ch>>12)&0x000F];
886 *p++ = hexdigit[(ch>>8)&0x000F];
887 *p++ = hexdigit[(ch>>4)&0x000F];
888 *p++ = hexdigit[ch&0x000F];
889 /* Map special whitespace to '\t', \n', '\r', '\f', '\b' */
890 } else if (ch == '\t') {
891 *p++ = '\\';
892 *p++ = 't';
893 } else if (ch == '\n') {
894 *p++ = '\\';
895 *p++ = 'n';
896 } else if (ch == '\r') {
897 *p++ = '\\';
898 *p++ = 'r';
899 } else if (ch == '\f') {
900 *p++ = '\\';
901 *p++ = 'f';
902 } else if (ch == '\b') {
903 *p++ = '\\';
904 *p++ = 'b';
905 }
906
907 /* Map non-printable US ASCII to '\u00hh' */
908 else if (ch < ' ' || ch >= 0x7F) {
909 *p++ = '\\';
910 *p++ = 'u';
911 *p++ = '0';
912 *p++ = '0';
913 *p++ = hexdigit[(ch>>4)&0x000F];
914 *p++ = hexdigit[ch&0x000F];
915 }
916
917 /* Copy everything else as-is */
918 else
919 *p++ = (char)ch;
920 }
921
922 *p++ = PyString_AS_STRING(repr)[0];
923
924 *p = '\0';
925 _PyString_Resize(&repr, p-PyString_AS_STRING(repr));
926 return repr;
927 }
928 #endif
929
930 /*
931 * This function is an almost verbatim copy of tuplerepr() from
932 * Python's tupleobject.c with the following differences:
933 *
934 * - it uses encode_object() to get the object's JSON reprezentation.
935 * - it uses [] as decorations isntead of () (to masquerade as a JSON array).
936 */
937
938 static PyObject *encode_tuple(PyObject *tuple) {
939 Py_ssize_t i, n;
940 PyObject *s, *temp;
941 PyObject *pieces, *result = NULL;
942 PyTupleObject *v = (PyTupleObject *)tuple;
943
944 n = Py_SIZE(v);
945 if (n == 0)
946 return PyBytes_FromString("[]");
947
948 pieces = PyTuple_New(n);
949 if (pieces == NULL)
950 return NULL;
951
952 /* Do repr() on each element. */
953 for (i = 0; i < n; ++i) {
954 s = encode_object(v->ob_item[i]);
955 if (s == NULL)
956 goto Done;
957 PyTuple_SET_ITEM(pieces, i, s);
958 }
959
960 /* Add "[]" decorations to the first and last items. */
961 assert(n > 0);
962 s = PyBytes_FromString("[");
963 if (s == NULL)
964 goto Done;
965 temp = PyTuple_GET_ITEM(pieces, 0);
966 PyBytes_ConcatAndDel(&s, temp);
967 PyTuple_SET_ITEM(pieces, 0, s);
968 if (s == NULL)
969 goto Done;
970
971 s = PyBytes_FromString("]");
972 if (s == NULL)
973 goto Done;
974 temp = PyTuple_GET_ITEM(pieces, n-1);
975 PyBytes_ConcatAndDel(&temp, s);
976 PyTuple_SET_ITEM(pieces, n-1, temp);
977 if (temp == NULL)
978 goto Done;
979
980 /* Paste them all together with ", " between. */
981 s = PyBytes_FromString(", ");
982 if (s == NULL)
983 goto Done;
984 result = _PyBytes_Join(s, pieces);
985 Py_DECREF(s);
986
987 Done:
988 Py_DECREF(pieces);
989 return result;
990 }
991
992 /*
993 * This function is an almost verbatim copy of list_repr() from
994 * Python's listobject.c with the following differences:
995 *
996 * - it uses encode_object() to get the object's JSON reprezentation.
997 * - it doesn't use the ellipsis to represent a list with references
998 * to itself, instead it raises an exception as such lists cannot be
999 * represented in JSON.
1000 */
1001 static PyObject *encode_list(PyObject *list) {
1002 Py_ssize_t i;
1003 PyObject *s, *temp;
1004 PyObject *pieces = NULL, *result = NULL;
1005 PyListObject *v = (PyListObject *)list;
1006
1007 i = Py_ReprEnter((PyObject *)v);
1008 if (i != 0) {
1009 if (i > 0) {
1010 PyErr_SetString(JSON_EncodeError, "a list with references to itself is not JSON encodable");
1011 }
1012 return NULL;
1013 }
1014
1015 if (Py_SIZE(v) == 0) {
1016 result = PyBytes_FromString("[]");
1017 goto Done;
1018 }
1019
1020 pieces = PyList_New(0);
1021 if (pieces == NULL)
1022 goto Done;
1023
1024 /* Do repr() on each element. Note that this may mutate the list,
1025 * so must refetch the list size on each iteration. */
1026 for (i = 0; i < Py_SIZE(v); ++i) {
1027 int status;
1028 s = encode_object(v->ob_item[i]);
1029 if (s == NULL)
1030 goto Done;
1031 status = PyList_Append(pieces, s);
1032 Py_DECREF(s); /* append created a new ref */
1033 if (status < 0)
1034 goto Done;
1035 }
1036
1037 /* Add "[]" decorations to the first and last items. */
1038 assert(PyList_GET_SIZE(pieces) > 0);
1039 s = PyBytes_FromString("[");
1040 if (s == NULL)
1041 goto Done;
1042 temp = PyList_GET_ITEM(pieces, 0);
1043 PyBytes_ConcatAndDel(&s, temp);
1044 PyList_SET_ITEM(pieces, 0, s);
1045 if (s == NULL)
1046 goto Done;
1047
1048 s = PyBytes_FromString("]");
1049 if (s == NULL)
1050 goto Done;
1051 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces)-1);
1052 PyBytes_ConcatAndDel(&temp, s);
1053 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces)-1, temp);
1054 if (temp == NULL)
1055 goto Done;
1056
1057 /* Paste them all together with ", " between. */
1058 s = PyBytes_FromString(", ");
1059 if (s == NULL)
1060 goto Done;
1061 result = _PyBytes_Join(s, pieces);
1062 Py_DECREF(s);
1063
1064 Done:
1065 Py_XDECREF(pieces);
1066 Py_ReprLeave((PyObject *)v);
1067 return result;
1068 }
1069
1070 /*
1071 * This function is an almost verbatim copy of dict_repr() from
1072 * Python's dictobject.c with the following differences:
1073 *
1074 * - it uses encode_object() to get the object's JSON reprezentation.
1075 * - only accept strings for keys.
1076 * - it doesn't use the ellipsis to represent a dictionary with references
1077 * to itself, instead it raises an exception as such dictionaries cannot
1078 * be represented in JSON.
1079 */
1080 static PyObject *encode_dict(PyObject *dict) {
1081 Py_ssize_t i;
1082 PyObject *s, *temp, *colon = NULL;
1083 PyObject *pieces = NULL, *result = NULL;
1084 PyObject *key, *value;
1085 PyDictObject *mp = (PyDictObject *)dict;
1086
1087 i = Py_ReprEnter((PyObject *)mp);
1088 if (i != 0) {
1089 if (i > 0) {
1090 PyErr_SetString(JSON_EncodeError, "a dict with references to "
1091 "itself is not JSON encodable");
1092 }
1093 return NULL;
1094 }
1095
1096 if (mp->ma_used == 0) {
1097 result = PyBytes_FromString("{}");
1098 goto Done;
1099 }
1100
1101 pieces = PyList_New(0);
1102 if (pieces == NULL)
1103 goto Done;
1104
1105 colon = PyBytes_FromString(": ");
1106 if (colon == NULL)
1107 goto Done;
1108
1109 /* Do repr() on each key+value pair, and insert ": " between them.
1110 * Note that repr may mutate the dict. */
1111 i = 0;
1112 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
1113 int status;
1114
1115 if (!PyBytes_Check(key) && !PyUnicode_Check(key)) {
1116 PyErr_SetString(JSON_EncodeError, "JSON encodable dictionaries must have string/unicode keys");
1117 goto Done;
1118 }
1119
1120 /* Prevent repr from deleting value during key format. */
1121 Py_INCREF(value);
1122 s = encode_object(key);
1123 PyBytes_Concat(&s, colon);
1124 PyBytes_ConcatAndDel(&s, encode_object(value));
1125 Py_DECREF(value);
1126 if (s == NULL)
1127 goto Done;
1128 status = PyList_Append(pieces, s);
1129 Py_DECREF(s); /* append created a new ref */
1130 if (status < 0)
1131 goto Done;
1132 }
1133
1134 /* Add "{}" decorations to the first and last items. */
1135 assert(PyList_GET_SIZE(pieces) > 0);
1136 s = PyBytes_FromString("{");
1137 if (s == NULL)
1138 goto Done;
1139 temp = PyList_GET_ITEM(pieces, 0);
1140 PyBytes_ConcatAndDel(&s, temp);
1141 PyList_SET_ITEM(pieces, 0, s);
1142 if (s == NULL)
1143 goto Done;
1144
1145 s = PyBytes_FromString("}");
1146 if (s == NULL)
1147 goto Done;
1148 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces)-1);
1149 PyBytes_ConcatAndDel(&temp, s);
1150 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces)-1, temp);
1151 if (temp == NULL)
1152 goto Done;
1153
1154 /* Paste them all together with ", " between. */
1155 s = PyBytes_FromString(", ");
1156 if (s == NULL)
1157 goto Done;
1158 result = _PyBytes_Join(s, pieces);
1159 Py_DECREF(s);
1160
1161 Done:
1162 Py_XDECREF(pieces);
1163 Py_XDECREF(colon);
1164 Py_ReprLeave((PyObject *)mp);
1165 return result;
1166 }
1167
1168 static PyObject *encode_object(PyObject *object) {
1169 if (object == Py_True) {
1170 return PyBytes_FromString("true");
1171 } else if (object == Py_False) {
1172 return PyBytes_FromString("false");
1173 } else if (object == Py_None) {
1174 return PyBytes_FromString("null");
1175 } else if (PyBytes_Check(object)) {
1176 return encode_string(object);
1177 } else if (PyUnicode_Check(object)) {
1178 return encode_unicode(object);
1179 } else if (PyFloat_Check(object)) {
1180 double val = PyFloat_AS_DOUBLE(object);
1181 if (Py_IS_NAN(val)) {
1182 return PyBytes_FromString("NaN");
1183 } else if (Py_IS_INFINITY(val)) {
1184 if (val > 0) {
1185 return PyBytes_FromString("Infinity");
1186 } else {
1187 return PyBytes_FromString("-Infinity");
1188 }
1189 } else {
1190 return cjson_PyObject_Str(object);
1191 }
1192 }
1193 #ifdef IS_PY3K
1194 else if (PyLong_Check(object)) {
1195 return cjson_PyObject_Str(object);
1196 }
1197 #else
1198 else if (PyInt_Check(object) || PyLong_Check(object)) {
1199 return cjson_PyObject_Str(object);
1200 }
1201 #endif
1202 else if (PyList_Check(object)) {
1203 return encode_list(object);
1204 } else if (PyTuple_Check(object)) {
1205 return encode_tuple(object);
1206 } else if (PyDict_Check(object)) { /* use PyMapping_Check(object) instead? -Dan */
1207 return encode_dict(object);
1208 } else {
1209 PyErr_SetString(JSON_EncodeError, "object is not JSON encodable");
1210 return NULL;
1211 }
1212 }
1213
1214 /* Encode object into its JSON representation */
1215
1216 static PyObject *JSON_encode(PyObject *self, PyObject *object) {
1217 return encode_object(object);
1218 }
1219
1220 /* Decode JSON representation into pyhton objects */
1221
1222 static PyObject *JSON_decode(PyObject *self, PyObject *args, PyObject *kwargs) {
1223 static char *kwlist[] = { "json", "all_unicode", NULL };
1224 #ifdef IS_PY3K
1225 int all_unicode = True; /* by default return unicode always */
1226 #else
1227 int all_unicode = False; /* by default return unicode only when needed */
1228 #endif
1229 PyObject *object, *string, *str;
1230 JSONData jsondata;
1231
1232 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:decode", kwlist, &string, &all_unicode))
1233 return NULL;
1234
1235 if (PyUnicode_Check(string)) {
1236 str = PyUnicode_AsRawUnicodeEscapeString(string);
1237 if (str == NULL) {
1238 return NULL;
1239 }
1240 } else {
1241 Py_INCREF(string);
1242 str = string;
1243 }
1244
1245 if (PyBytes_AsStringAndSize(str, &(jsondata.str), NULL) == -1) {
1246 Py_DECREF(str);
1247 return NULL; /* not a string object or it contains null bytes */
1248 }
1249
1250 jsondata.ptr = jsondata.str;
1251 jsondata.end = jsondata.str+strlen(jsondata.str);
1252 jsondata.all_unicode = all_unicode;
1253
1254 object = decode_json(&jsondata);
1255
1256 if (object != NULL) {
1257 skipSpaces(&jsondata);
1258 if (jsondata.ptr < jsondata.end) {
1259 PyErr_Format(JSON_DecodeError, "extra data after JSON description at position "SSIZE_T_F, (Py_ssize_t)(jsondata.ptr-jsondata.str));
1260 Py_DECREF(str);
1261 Py_DECREF(object);
1262 return NULL;
1263 }
1264 }
1265
1266 Py_DECREF(str);
1267
1268 return object;
1269 }
1270
1271 /* List of functions defined in the module */
1272
1273 static PyMethodDef cjson_methods[] = {
1274 { "encode", (PyCFunction)JSON_encode, METH_O,
1275 PyDoc_STR("encode(object) -> generate the JSON representation for object.") },
1276
1277 /* On Python 3.x we normally want Unicode. */
1278 { "decode", (PyCFunction)JSON_decode, METH_VARARGS|METH_KEYWORDS,
1279 #ifdef IS_PY3K
1280 PyDoc_STR("decode(string, all_unicode=True) -> parse the JSON representation into\n"
1281 "python objects. The optional argument `all_unicode', specifies how to\n"
1282 "convert the strings in the JSON representation into python objects.\n"
1283 "If it is False (default on Python 2.x), it will return strings/bytes\n"
1284 "everywhere possible and unicode objects only where necessary, else\n"
1285 "it will return unicode objects everywhere (this is slower, but default\n"
1286 "on Python 3.x).")
1287 #else
1288 PyDoc_STR("decode(string, all_unicode=False) -> parse the JSON representation into\n"
1289 "python objects. The optional argument `all_unicode', specifies how to\n"
1290 "convert the strings in the JSON representation into python objects.\n"
1291 "If it is False (default on Python 2.x), it will return strings/bytes\n"
1292 "everywhere possible and unicode objects only where necessary, else\n"
1293 "it will return unicode objects everywhere (this is slower, but default\n"
1294 "on Python 3.x).")
1295 #endif
1296 },
1297 { NULL, NULL, 0, NULL } /* sentinel */
1298 };
1299
1300 PyDoc_STRVAR(module_doc, "Fast JSON encoder/decoder module.");
1301
1302 #define MODULE_VERSION "1.0.5"
1303
1304 static void initcjson_shared(PyObject *m) {
1305 JSON_Error = PyErr_NewException("cjson.Error", NULL, NULL);
1306 if (JSON_Error == NULL)
1307 return;
1308 Py_INCREF(JSON_Error);
1309 PyModule_AddObject(m, "Error", JSON_Error);
1310
1311 JSON_EncodeError = PyErr_NewException("cjson.EncodeError", JSON_Error, NULL);
1312 if (JSON_EncodeError == NULL)
1313 return;
1314 Py_INCREF(JSON_EncodeError);
1315 PyModule_AddObject(m, "EncodeError", JSON_EncodeError);
1316
1317 JSON_DecodeError = PyErr_NewException("cjson.DecodeError", JSON_Error, NULL);
1318 if (JSON_DecodeError == NULL)
1319 return;
1320 Py_INCREF(JSON_DecodeError);
1321 PyModule_AddObject(m, "DecodeError", JSON_DecodeError);
1322
1323 /* Module version (the MODULE_VERSION macro is defined by setup.py) */
1324 PyModule_AddStringConstant(m, "__version__", MODULE_VERSION);
1325 }
1326
1327
1328 #ifdef IS_PY3K
1329 static PyModuleDef cjsonModule = {
1330 PyModuleDef_HEAD_INIT,
1331 "cjson", /* m_name */
1332 module_doc, /* m_doc */
1333 -1, /* m_size */
1334 cjson_methods, /* m_methods */
1335 NULL, /* m_reload */
1336 NULL, /* m_traverse */
1337 NULL, /* m_clear */
1338 NULL /* m_free */
1339 };
1340
1341 PyObject* PyInit_cjson(void)
1342 {
1343 PyObject *m;
1344
1345 m = PyModule_Create(&cjsonModule);
1346
1347 if (m == NULL)
1348 return NULL;
1349
1350 initcjson_shared(m);
1351
1352 return m;
1353 }
1354 #else
1355 /* Initialization function for the module (*must *be called initcjson) */
1356 PyMODINIT_FUNC initcjson(void) {
1357 PyObject *m;
1358
1359 m = Py_InitModule3("cjson", cjson_methods, module_doc);
1360
1361 if (m == NULL)
1362 return;
1363
1364 initcjson_shared(m);
1365 }
1366 #endif