# HG changeset patch # User Fredrik Lundh # Date 1257696991 -3600 # Branch cjson_default_encoding # Node ID 3c9125630ade409b334d5047b34782bb8d664151 # Parent 9f3809fc04b43f2b75dd97ce9fb01442a039ea55 Added global setdefaultencoding override. diff -r 9f3809fc04b43f2b75dd97ce9fb01442a039ea55 -r 3c9125630ade409b334d5047b34782bb8d664151 cjson.c --- a/cjson.c Fri Nov 06 03:43:29 2009 +0100 +++ b/cjson.c Sun Nov 08 17:16:31 2009 +0100 @@ -49,6 +49,8 @@ static PyObject *JSON_EncodeError; static PyObject *JSON_DecodeError; +static PyObject *default_encoding_obj; +static char *default_encoding_str; #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; @@ -84,6 +86,7 @@ /* used as a replacement for invalid UTF-8 sequences */ #define UNICODE_REPLACEMENT_CHARACTER 0xfffd + /* ------------------------------ Decoding ----------------------------- */ static PyObject* @@ -1245,7 +1248,12 @@ JSON_encode(PyObject *self, PyObject *object) { JSONEncode encode; - const char *encoding = PyUnicode_GetDefaultEncoding(); + const char *encoding; + + encoding = default_encoding_str; + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + encode.encoding = OTHER; switch (*encoding) { case 'a': @@ -1271,7 +1279,7 @@ } -/* Decode JSON representation into pyhton objects */ +/* Decode JSON representation into Python objects */ static PyObject* JSON_decode(PyObject *self, PyObject *args, PyObject *kwargs) @@ -1324,6 +1332,29 @@ } +static PyObject* +JSON_setdefaultencoding(PyObject *self, PyObject *object) +{ + if (PyString_Check(object)) { + Py_INCREF(object); + Py_DECREF(default_encoding_obj); + default_encoding_obj = object; + default_encoding_str = PyString_AS_STRING(object); + } + else if (object == Py_None) { + Py_INCREF(Py_None); + Py_DECREF(default_encoding_obj); + default_encoding_obj = object; + default_encoding_str = NULL; + } else { + PyErr_SetString(PyExc_TypeError, "encoding must be string or None"); + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; +} + /* List of functions defined in the module */ static PyMethodDef cjson_methods[] = { @@ -1338,6 +1369,9 @@ "and unicode objects only where necessary, else it will return unicode\n" "objects everywhere (this is slower).")}, + {"setdefaultencoding", (PyCFunction)JSON_setdefaultencoding, METH_O, + PyDoc_STR("setdefaultencoding(encoding) -> set default encoding for 8-bit strings.")}, + {NULL, NULL} // sentinel }; @@ -1375,6 +1409,10 @@ Py_INCREF(JSON_DecodeError); PyModule_AddObject(m, "DecodeError", JSON_DecodeError); + Py_INCREF(Py_None); + default_encoding_obj = Py_None; + default_encoding_str = NULL; + // Module version (the MODULE_VERSION macro is defined by setup.py) PyModule_AddStringConstant(m, "__version__", STRINGIFY(MODULE_VERSION));