forked from rtyler/py-yajl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yajl.c
493 lines (434 loc) · 15.1 KB
/
yajl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
* Copyright 2009, R. Tyler Ballance <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of R. Tyler Ballance nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <Python.h>
#include "py_yajl.h"
static PyMethodDef yajldecoder_methods[] = {
{"decode", (PyCFunction)(py_yajldecoder_decode), METH_VARARGS, NULL},
{NULL}
};
static PyMethodDef yajlencoder_methods[] = {
{"encode", (PyCFunction)(py_yajlencoder_encode), METH_VARARGS, NULL},
{"default", (PyCFunction)(py_yajlencoder_default), METH_VARARGS, NULL},
{NULL}
};
static PyTypeObject YajlDecoderType = {
#ifdef IS_PYTHON3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
#endif
"yajl.YajlDecoder", /*tp_name*/
sizeof(_YajlDecoder), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)yajldecoder_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Yajl-based decoder", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
yajldecoder_methods, /* tp_methods */
NULL, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)(yajldecoder_init),/* tp_init */
0, /* tp_alloc */
};
static PyTypeObject YajlEncoderType = {
#ifdef IS_PYTHON3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
#endif
"yajl.YajlEncoder", /*tp_name*/
sizeof(_YajlEncoder), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)yajlencoder_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Yajl-based encoder", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
yajlencoder_methods, /* tp_methods */
NULL, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)(yajlencoder_init),/* tp_init */
0, /* tp_alloc */
};
static PyObject *py_loads(PYARGS)
{
PyObject *decoder = NULL;
PyObject *result = NULL;
PyObject *pybuffer = NULL;
char *buffer = NULL;
Py_ssize_t buflen = 0;
if (!PyArg_ParseTuple(args, "O", &pybuffer))
return NULL;
Py_INCREF(pybuffer);
if (PyUnicode_Check(pybuffer)) {
if (!(result = PyUnicode_AsUTF8String(pybuffer))) {
Py_DECREF(pybuffer);
return NULL;
}
Py_DECREF(pybuffer);
pybuffer = result;
result = NULL;
}
if (PyString_Check(pybuffer)) {
if (PyString_AsStringAndSize(pybuffer, &buffer, &buflen)) {
Py_DECREF(pybuffer);
return NULL;
}
} else {
/* really seems like this should be a TypeError, but
tests/unit.py:ErrorCasesTests.test_None disagrees */
Py_DECREF(pybuffer);
PyErr_SetString(PyExc_ValueError, "string or unicode expected");
return NULL;
}
decoder = PyObject_Call((PyObject *)(&YajlDecoderType), NULL, NULL);
if (decoder == NULL) {
return NULL;
}
result = _internal_decode(
(_YajlDecoder *)decoder, buffer, (unsigned int)buflen);
Py_DECREF(pybuffer);
Py_XDECREF(decoder);
return result;
}
static char *__config_gen_config(PyObject *indent, yajl_gen_config *config)
{
long indentLevel = -1;
char *spaces = NULL;
if (!indent)
return NULL;
if ((indent != Py_None) && (!PyLong_Check(indent))
#ifndef IS_PYTHON3
&& (!PyInt_Check(indent))
#endif
) {
PyErr_SetObject(PyExc_TypeError,
PyUnicode_FromString("`indent` must be int or None"));
return NULL;
}
if (indent != Py_None) {
indentLevel = PyLong_AsLong(indent);
if (indentLevel >= 0) {
config->beautify = 1;
if (indentLevel == 0) {
config->indentString = "";
}
else {
spaces = (char *)(malloc(sizeof(char) * (indentLevel + 1)));
memset((void *)(spaces), (int)' ', indentLevel);
spaces[indentLevel] = '\0';
config->indentString = spaces;
}
}
}
return spaces;
}
static PyObject *py_dumps(PYARGS)
{
PyObject *encoder = NULL;
PyObject *obj = NULL;
PyObject *result = NULL;
PyObject *indent = NULL;
yajl_gen_config config = { 0, NULL };
static char *kwlist[] = {"object", "indent", NULL};
char *spaces = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &obj, &indent)) {
return NULL;
}
spaces = __config_gen_config(indent, &config);
if (PyErr_Occurred()) {
return NULL;
}
encoder = PyObject_Call((PyObject *)(&YajlEncoderType), NULL, NULL);
if (encoder == NULL) {
return NULL;
}
result = _internal_encode((_YajlEncoder *)encoder, obj, config);
Py_XDECREF(encoder);
if (spaces) {
free(spaces);
}
return result;
}
static PyObject *__read = NULL;
static PyObject *_internal_stream_load(PyObject *args, unsigned int blocking)
{
PyObject *decoder = NULL;
PyObject *stream = NULL;
PyObject *buffer = NULL;
PyObject *result = NULL;
#ifdef IS_PYTHON3
PyObject *bufferstring = NULL;
#endif
if (!PyArg_ParseTuple(args, "O", &stream)) {
goto bad_type;
}
if (__read == NULL) {
__read = PyUnicode_FromString("read");
}
if (!PyObject_HasAttr(stream, __read)) {
goto bad_type;
}
buffer = PyObject_CallMethodObjArgs(stream, __read, NULL);
if (!buffer)
return NULL;
#ifdef IS_PYTHON3
bufferstring = PyUnicode_AsUTF8String(buffer);
if (!bufferstring)
return NULL;
#endif
decoder = PyObject_Call((PyObject *)(&YajlDecoderType), NULL, NULL);
if (decoder == NULL) {
return NULL;
}
#ifdef IS_PYTHON3
result = _internal_decode((_YajlDecoder *)decoder, PyBytes_AsString(bufferstring),
PyBytes_Size(bufferstring));
Py_XDECREF(bufferstring);
#else
result = _internal_decode((_YajlDecoder *)decoder, PyString_AsString(buffer),
PyString_Size(buffer));
#endif
Py_XDECREF(decoder);
Py_XDECREF(buffer);
return result;
bad_type:
PyErr_SetObject(PyExc_TypeError, PyUnicode_FromString("Must pass a single stream object"));
return NULL;
}
static PyObject *py_load(PYARGS)
{
return _internal_stream_load(args, 1);
}
static PyObject *py_iterload(PYARGS)
{
return _internal_stream_load(args, 0);
}
static PyObject *__write = NULL;
static PyObject *_internal_stream_dump(PyObject *object, PyObject *stream, unsigned int blocking,
yajl_gen_config config)
{
PyObject *encoder = NULL;
PyObject *buffer = NULL;
if (__write == NULL) {
__write = PyUnicode_FromString("write");
}
if (!PyObject_HasAttr(stream, __write)) {
goto bad_type;
}
encoder = PyObject_Call((PyObject *)(&YajlEncoderType), NULL, NULL);
if (encoder == NULL) {
return NULL;
}
buffer = _internal_encode((_YajlEncoder *)encoder, object, config);
PyObject_CallMethodObjArgs(stream, __write, buffer, NULL);
Py_XDECREF(encoder);
Py_XDECREF(buffer);
return Py_True;
bad_type:
PyErr_SetObject(PyExc_TypeError, PyUnicode_FromString("Must pass a stream object"));
return NULL;
}
static PyObject *py_dump(PYARGS)
{
PyObject *object = NULL;
PyObject *indent = NULL;
PyObject *stream = NULL;
PyObject *result = NULL;
yajl_gen_config config = { 0, NULL };
static char *kwlist[] = {"object", "stream", "indent", NULL};
char *spaces = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|O", kwlist, &object, &stream, &indent)) {
return NULL;
}
spaces = __config_gen_config(indent, &config);
if (PyErr_Occurred()) {
return NULL;
}
result = _internal_stream_dump(object, stream, 0, config);
if (spaces) {
free(spaces);
}
return result;
}
static PyObject *py_monkeypatch(PYARGS)
{
PyObject *sys = PyImport_ImportModule("sys");
PyObject *modules = PyObject_GetAttrString(sys, "modules");
PyObject *yajl = PyDict_GetItemString(modules, "yajl");
if (!yajl) {
return Py_False;
}
PyDict_SetItemString(modules, "json_old", PyDict_GetItemString(modules, "json"));
PyDict_SetItemString(modules, "json", yajl);
Py_XDECREF(sys);
Py_XDECREF(modules);
return Py_True;
}
static struct PyMethodDef yajl_methods[] = {
{"dumps", (PyCFunctionWithKeywords)(py_dumps), METH_VARARGS | METH_KEYWORDS,
"yajl.dumps(obj [, indent=None])\n\n\
Returns an encoded JSON string of the specified `obj`\n\
\n\
If `indent` is a non-negative integer, then JSON array elements \n\
and object members will be pretty-printed with that indent level. \n\
An indent level of 0 will only insert newlines. None (the default) \n\
selects the most compact representation.\n\
"},
{"loads", (PyCFunction)(py_loads), METH_VARARGS,
"yajl.loads(string)\n\n\
Returns a decoded object based on the given JSON `string`"},
{"load", (PyCFunction)(py_load), METH_VARARGS,
"yajl.load(fp)\n\n\
Returns a decoded object based on the JSON read from the `fp` stream-like\n\
object; *Note:* It is expected that `fp` supports the `read()` method"},
{"dump", (PyCFunctionWithKeywords)(py_dump), METH_VARARGS | METH_KEYWORDS,
"yajl.dump(obj, fp [, indent=None])\n\n\
Encodes the given `obj` and writes it to the `fp` stream-like object. \n\
*Note*: It is expected that `fp` supports the `write()` method\n\
\n\
If `indent` is a non-negative integer, then JSON array elements \n\
and object members will be pretty-printed with that indent level. \n\
An indent level of 0 will only insert newlines. None (the default) \n\
selects the most compact representation.\n\
"},
/*
{"iterload", (PyCFunction)(py_iterload), METH_VARARGS, NULL},
*/
{"monkeypatch", (PyCFunction)(py_monkeypatch), METH_NOARGS,
"yajl.monkeypatch()\n\n\
Monkey-patches the yajl module into sys.modules as \"json\"\n\
"},
{NULL}
};
#ifdef IS_PYTHON3
static struct PyModuleDef yajlmodule = {
PyModuleDef_HEAD_INIT,
"yajl",
#else
PyMODINIT_FUNC inityajl(void)
{
PyObject *module = Py_InitModule3("yajl", yajl_methods,
#endif
"Providing a pythonic interface to the yajl (Yet Another JSON Library) parser\n\n\
The interface is similar to that of simplejson or jsonlib providing a consistent syntax for JSON\n\
encoding and decoding. Unlike simplejson or jsonlib, yajl is **fast** :)\n\n\
The following benchmark was done on a dual core MacBook Pro with a fairly large (100K) JSON document:\n\
json.loads():\t\t21351.313ms\n\
simplejson.loads():\t1378.6492ms\n\
yajl.loads():\t\t502.4572ms\n\
\n\
json.dumps():\t\t7760.6348ms\n\
simplejson.dumps():\t930.9748ms\n\
yajl.dumps():\t\t681.0221ms"
#ifdef IS_PYTHON3
, -1, yajl_methods, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_yajl(void)
{
PyObject *module = PyModule_Create(&yajlmodule);
#else
);
#endif
PyObject *version = PyUnicode_FromString(MOD_VERSION);
PyModule_AddObject(module, "__version__", version);
YajlDecoderType.tp_new = PyType_GenericNew;
if (PyType_Ready(&YajlDecoderType) < 0) {
goto bad_exit;
}
Py_INCREF(&YajlDecoderType);
PyModule_AddObject(module, "Decoder", (PyObject *)(&YajlDecoderType));
YajlEncoderType.tp_new = PyType_GenericNew;
if (PyType_Ready(&YajlEncoderType) < 0) {
goto bad_exit;
}
Py_INCREF(&YajlEncoderType);
PyModule_AddObject(module, "Encoder", (PyObject *)(&YajlEncoderType));
#ifdef IS_PYTHON3
return module;
#endif
bad_exit:
#ifdef IS_PYTHON3
return NULL;
#else
return;
#endif
}