summaryrefslogtreecommitdiffstats
path: root/Modules
diff options
context:
space:
mode:
Diffstat (limited to 'Modules')
-rw-r--r--Modules/_bisectmodule.c302
-rw-r--r--Modules/_codecsmodule.c754
-rw-r--r--Modules/_collectionsmodule.c2248
-rw-r--r--Modules/_csv.c2220
-rw-r--r--Modules/_ctypes/_ctypes.c8246
-rw-r--r--Modules/_ctypes/_ctypes_test.c452
-rw-r--r--Modules/_ctypes/callbacks.c886
-rw-r--r--Modules/_ctypes/callproc.c2518
-rw-r--r--Modules/_ctypes/cfield.c2106
-rw-r--r--Modules/_ctypes/ctypes.h286
-rw-r--r--Modules/_ctypes/darwin/dlfcn_simple.c282
-rw-r--r--Modules/_ctypes/malloc_closure.c98
-rw-r--r--Modules/_ctypes/stgdict.c942
-rw-r--r--Modules/_curses_panel.c226
-rw-r--r--Modules/_dbmmodule.c618
-rw-r--r--Modules/_functoolsmodule.c598
-rw-r--r--Modules/_gdbmmodule.c70
-rw-r--r--Modules/_gestalt.c40
-rw-r--r--Modules/_heapqmodule.c890
-rw-r--r--Modules/_json.c36
-rw-r--r--Modules/_localemodule.c132
-rw-r--r--Modules/_lsprof.c1170
-rw-r--r--Modules/_math.c206
-rw-r--r--Modules/_multiprocessing/connection.h760
-rw-r--r--Modules/_multiprocessing/multiprocessing.c420
-rw-r--r--Modules/_multiprocessing/multiprocessing.h30
-rw-r--r--Modules/_multiprocessing/pipe_connection.c196
-rw-r--r--Modules/_multiprocessing/semaphore.c892
-rw-r--r--Modules/_multiprocessing/socket_connection.c258
-rw-r--r--Modules/_multiprocessing/win32_functions.c342
-rw-r--r--Modules/_randommodule.c714
-rw-r--r--Modules/_scproxy.c404
-rw-r--r--Modules/_sqlite/module.c32
-rw-r--r--Modules/_struct.c2524
-rw-r--r--Modules/_testcapimodule.c3346
-rw-r--r--Modules/_threadmodule.c1430
-rw-r--r--Modules/_tkinter.c4036
-rw-r--r--Modules/addrinfo.h106
-rw-r--r--Modules/arraymodule.c3846
-rw-r--r--Modules/audioop.c2510
-rw-r--r--Modules/binascii.c2286
-rw-r--r--Modules/bz2module.c3090
-rw-r--r--Modules/cjkcodecs/_codecs_cn.c634
-rw-r--r--Modules/cjkcodecs/_codecs_hk.c256
-rw-r--r--Modules/cjkcodecs/_codecs_iso2022.c1622
-rw-r--r--Modules/cjkcodecs/_codecs_jp.c1204
-rw-r--r--Modules/cjkcodecs/_codecs_kr.c602
-rw-r--r--Modules/cjkcodecs/_codecs_tw.c140
-rw-r--r--Modules/cjkcodecs/alg_jisx0201.h46
-rw-r--r--Modules/cjkcodecs/cjkcodecs.h578
-rw-r--r--Modules/cjkcodecs/emu_jisx0213_2000.h58
-rw-r--r--Modules/cjkcodecs/multibytecodec.c2870
-rw-r--r--Modules/cjkcodecs/multibytecodec.h132
-rw-r--r--Modules/cmathmodule.c1620
-rw-r--r--Modules/cryptmodule.c40
-rw-r--r--Modules/datetimemodule.c6878
-rw-r--r--Modules/errnomodule.c524
-rw-r--r--Modules/fcntlmodule.c720
-rw-r--r--Modules/fpectlmodule.c84
-rw-r--r--Modules/fpetestmodule.c34
-rw-r--r--Modules/gcmodule.c1722
-rw-r--r--Modules/getaddrinfo.c884
-rw-r--r--Modules/getbuildinfo.c26
-rw-r--r--Modules/getnameinfo.c254
-rw-r--r--Modules/getpath.c170
-rw-r--r--Modules/grpmodule.c46
-rw-r--r--Modules/itertoolsmodule.c5256
-rw-r--r--Modules/main.c1220
-rw-r--r--Modules/mathmodule.c2004
-rw-r--r--Modules/md5module.c72
-rw-r--r--Modules/mmapmodule.c2018
-rw-r--r--Modules/nismodule.c566
-rw-r--r--Modules/operator.c750
-rw-r--r--Modules/ossaudiodev.c26
-rw-r--r--Modules/parsermodule.c204
-rw-r--r--Modules/pwdmodule.c220
-rw-r--r--Modules/pyexpat.c362
-rw-r--r--Modules/python.c68
-rw-r--r--Modules/readline.c1040
-rw-r--r--Modules/resource.c388
-rw-r--r--Modules/rotatingtree.c160
-rw-r--r--Modules/selectmodule.c2486
-rw-r--r--Modules/sha1module.c78
-rw-r--r--Modules/sha256module.c126
-rw-r--r--Modules/sha512module.c146
-rw-r--r--Modules/signalmodule.c860
-rw-r--r--Modules/socketmodule.c6080
-rw-r--r--Modules/socketmodule.h84
-rw-r--r--Modules/spwdmodule.c192
-rw-r--r--Modules/symtablemodule.c140
-rw-r--r--Modules/syslogmodule.c424
-rw-r--r--Modules/termios.c904
-rw-r--r--Modules/testcapi_long.h348
-rw-r--r--Modules/timemodule.c1264
-rw-r--r--Modules/tkappinit.c192
-rw-r--r--Modules/unicodedata.c286
-rw-r--r--Modules/xxmodule.c520
-rw-r--r--Modules/xxsubtype.c410
-rw-r--r--Modules/zipimport.c1736
-rw-r--r--Modules/zlibmodule.c462
100 files changed, 52392 insertions, 52392 deletions
diff --git a/Modules/_bisectmodule.c b/Modules/_bisectmodule.c
index fe2e110..f65a583 100644
--- a/Modules/_bisectmodule.c
+++ b/Modules/_bisectmodule.c
@@ -8,51 +8,51 @@ Converted to C by Dmitry Vasiliev (dima at hlabs.spb.ru).
static Py_ssize_t
internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
- PyObject *litem;
- Py_ssize_t mid, res;
-
- if (lo < 0) {
- PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
- return -1;
- }
- if (hi == -1) {
- hi = PySequence_Size(list);
- if (hi < 0)
- return -1;
- }
- while (lo < hi) {
- mid = (lo + hi) / 2;
- litem = PySequence_GetItem(list, mid);
- if (litem == NULL)
- return -1;
- res = PyObject_RichCompareBool(item, litem, Py_LT);
- Py_DECREF(litem);
- if (res < 0)
- return -1;
- if (res)
- hi = mid;
- else
- lo = mid + 1;
- }
- return lo;
+ PyObject *litem;
+ Py_ssize_t mid, res;
+
+ if (lo < 0) {
+ PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
+ return -1;
+ }
+ if (hi == -1) {
+ hi = PySequence_Size(list);
+ if (hi < 0)
+ return -1;
+ }
+ while (lo < hi) {
+ mid = (lo + hi) / 2;
+ litem = PySequence_GetItem(list, mid);
+ if (litem == NULL)
+ return -1;
+ res = PyObject_RichCompareBool(item, litem, Py_LT);
+ Py_DECREF(litem);
+ if (res < 0)
+ return -1;
+ if (res)
+ hi = mid;
+ else
+ lo = mid + 1;
+ }
+ return lo;
}
static PyObject *
bisect_right(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *list, *item;
- Py_ssize_t lo = 0;
- Py_ssize_t hi = -1;
- Py_ssize_t index;
- static char *keywords[] = {"a", "x", "lo", "hi", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",
- keywords, &list, &item, &lo, &hi))
- return NULL;
- index = internal_bisect_right(list, item, lo, hi);
- if (index < 0)
- return NULL;
- return PyLong_FromSsize_t(index);
+ PyObject *list, *item;
+ Py_ssize_t lo = 0;
+ Py_ssize_t hi = -1;
+ Py_ssize_t index;
+ static char *keywords[] = {"a", "x", "lo", "hi", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",
+ keywords, &list, &item, &lo, &hi))
+ return NULL;
+ index = internal_bisect_right(list, item, lo, hi);
+ if (index < 0)
+ return NULL;
+ return PyLong_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_right_doc,
@@ -70,30 +70,30 @@ slice of a to be searched.\n");
static PyObject *
insort_right(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *list, *item, *result;
- Py_ssize_t lo = 0;
- Py_ssize_t hi = -1;
- Py_ssize_t index;
- static char *keywords[] = {"a", "x", "lo", "hi", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right",
- keywords, &list, &item, &lo, &hi))
- return NULL;
- index = internal_bisect_right(list, item, lo, hi);
- if (index < 0)
- return NULL;
- if (PyList_CheckExact(list)) {
- if (PyList_Insert(list, index, item) < 0)
- return NULL;
- } else {
- result = PyObject_CallMethod(list, "insert", "nO",
- index, item);
- if (result == NULL)
- return NULL;
- Py_DECREF(result);
- }
-
- Py_RETURN_NONE;
+ PyObject *list, *item, *result;
+ Py_ssize_t lo = 0;
+ Py_ssize_t hi = -1;
+ Py_ssize_t index;
+ static char *keywords[] = {"a", "x", "lo", "hi", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right",
+ keywords, &list, &item, &lo, &hi))
+ return NULL;
+ index = internal_bisect_right(list, item, lo, hi);
+ if (index < 0)
+ return NULL;
+ if (PyList_CheckExact(list)) {
+ if (PyList_Insert(list, index, item) < 0)
+ return NULL;
+ } else {
+ result = PyObject_CallMethod(list, "insert", "nO",
+ index, item);
+ if (result == NULL)
+ return NULL;
+ Py_DECREF(result);
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_right_doc,
@@ -109,51 +109,51 @@ slice of a to be searched.\n");
static Py_ssize_t
internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
- PyObject *litem;
- Py_ssize_t mid, res;
-
- if (lo < 0) {
- PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
- return -1;
- }
- if (hi == -1) {
- hi = PySequence_Size(list);
- if (hi < 0)
- return -1;
- }
- while (lo < hi) {
- mid = (lo + hi) / 2;
- litem = PySequence_GetItem(list, mid);
- if (litem == NULL)
- return -1;
- res = PyObject_RichCompareBool(litem, item, Py_LT);
- Py_DECREF(litem);
- if (res < 0)
- return -1;
- if (res)
- lo = mid + 1;
- else
- hi = mid;
- }
- return lo;
+ PyObject *litem;
+ Py_ssize_t mid, res;
+
+ if (lo < 0) {
+ PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
+ return -1;
+ }
+ if (hi == -1) {
+ hi = PySequence_Size(list);
+ if (hi < 0)
+ return -1;
+ }
+ while (lo < hi) {
+ mid = (lo + hi) / 2;
+ litem = PySequence_GetItem(list, mid);
+ if (litem == NULL)
+ return -1;
+ res = PyObject_RichCompareBool(litem, item, Py_LT);
+ Py_DECREF(litem);
+ if (res < 0)
+ return -1;
+ if (res)
+ lo = mid + 1;
+ else
+ hi = mid;
+ }
+ return lo;
}
static PyObject *
bisect_left(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *list, *item;
- Py_ssize_t lo = 0;
- Py_ssize_t hi = -1;
- Py_ssize_t index;
- static char *keywords[] = {"a", "x", "lo", "hi", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left",
- keywords, &list, &item, &lo, &hi))
- return NULL;
- index = internal_bisect_left(list, item, lo, hi);
- if (index < 0)
- return NULL;
- return PyLong_FromSsize_t(index);
+ PyObject *list, *item;
+ Py_ssize_t lo = 0;
+ Py_ssize_t hi = -1;
+ Py_ssize_t index;
+ static char *keywords[] = {"a", "x", "lo", "hi", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left",
+ keywords, &list, &item, &lo, &hi))
+ return NULL;
+ index = internal_bisect_left(list, item, lo, hi);
+ if (index < 0)
+ return NULL;
+ return PyLong_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_left_doc,
@@ -171,30 +171,30 @@ slice of a to be searched.\n");
static PyObject *
insort_left(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *list, *item, *result;
- Py_ssize_t lo = 0;
- Py_ssize_t hi = -1;
- Py_ssize_t index;
- static char *keywords[] = {"a", "x", "lo", "hi", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left",
- keywords, &list, &item, &lo, &hi))
- return NULL;
- index = internal_bisect_left(list, item, lo, hi);
- if (index < 0)
- return NULL;
- if (PyList_CheckExact(list)) {
- if (PyList_Insert(list, index, item) < 0)
- return NULL;
- } else {
- result = PyObject_CallMethod(list, "insert", "iO",
- index, item);
- if (result == NULL)
- return NULL;
- Py_DECREF(result);
- }
-
- Py_RETURN_NONE;
+ PyObject *list, *item, *result;
+ Py_ssize_t lo = 0;
+ Py_ssize_t hi = -1;
+ Py_ssize_t index;
+ static char *keywords[] = {"a", "x", "lo", "hi", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left",
+ keywords, &list, &item, &lo, &hi))
+ return NULL;
+ index = internal_bisect_left(list, item, lo, hi);
+ if (index < 0)
+ return NULL;
+ if (PyList_CheckExact(list)) {
+ if (PyList_Insert(list, index, item) < 0)
+ return NULL;
+ } else {
+ result = PyObject_CallMethod(list, "insert", "iO",
+ index, item);
+ if (result == NULL)
+ return NULL;
+ Py_DECREF(result);
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_left_doc,
@@ -211,19 +211,19 @@ PyDoc_STRVAR(bisect_doc, "Alias for bisect_right().\n");
PyDoc_STRVAR(insort_doc, "Alias for insort_right().\n");
static PyMethodDef bisect_methods[] = {
- {"bisect_right", (PyCFunction)bisect_right,
- METH_VARARGS|METH_KEYWORDS, bisect_right_doc},
- {"bisect", (PyCFunction)bisect_right,
- METH_VARARGS|METH_KEYWORDS, bisect_doc},
- {"insort_right", (PyCFunction)insort_right,
- METH_VARARGS|METH_KEYWORDS, insort_right_doc},
- {"insort", (PyCFunction)insort_right,
- METH_VARARGS|METH_KEYWORDS, insort_doc},
- {"bisect_left", (PyCFunction)bisect_left,
- METH_VARARGS|METH_KEYWORDS, bisect_left_doc},
- {"insort_left", (PyCFunction)insort_left,
- METH_VARARGS|METH_KEYWORDS, insort_left_doc},
- {NULL, NULL} /* sentinel */
+ {"bisect_right", (PyCFunction)bisect_right,
+ METH_VARARGS|METH_KEYWORDS, bisect_right_doc},
+ {"bisect", (PyCFunction)bisect_right,
+ METH_VARARGS|METH_KEYWORDS, bisect_doc},
+ {"insort_right", (PyCFunction)insort_right,
+ METH_VARARGS|METH_KEYWORDS, insort_right_doc},
+ {"insort", (PyCFunction)insort_right,
+ METH_VARARGS|METH_KEYWORDS, insort_doc},
+ {"bisect_left", (PyCFunction)bisect_left,
+ METH_VARARGS|METH_KEYWORDS, bisect_left_doc},
+ {"insort_left", (PyCFunction)insort_left,
+ METH_VARARGS|METH_KEYWORDS, insort_left_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@@ -236,19 +236,19 @@ common approach.\n");
static struct PyModuleDef _bisectmodule = {
- PyModuleDef_HEAD_INIT,
- "_bisect",
- module_doc,
- -1,
- bisect_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_bisect",
+ module_doc,
+ -1,
+ bisect_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__bisect(void)
{
- return PyModule_Create(&_bisectmodule);
+ return PyModule_Create(&_bisectmodule);
}
diff --git a/Modules/_codecsmodule.c b/Modules/_codecsmodule.c
index 041e0ae..d0d870c 100644
--- a/Modules/_codecsmodule.c
+++ b/Modules/_codecsmodule.c
@@ -15,7 +15,7 @@
The builtin Unicode codecs use the following interface:
<encoding>_encode(Unicode_object[,errors='strict']) ->
- (string object, bytes consumed)
+ (string object, bytes consumed)
<encoding>_decode(char_buffer_obj[,errors='strict']) ->
(Unicode object, bytes consumed)
@@ -95,7 +95,7 @@ codec_encode(PyObject *self, PyObject *args)
return NULL;
if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
/* Encode via the codec registry */
return PyCodec_Encode(v, encoding, errors);
@@ -122,7 +122,7 @@ codec_decode(PyObject *self, PyObject *args)
return NULL;
if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
/* Decode via the codec registry */
return PyCodec_Decode(v, encoding, errors);
@@ -132,7 +132,7 @@ codec_decode(PyObject *self, PyObject *args)
static
PyObject *codec_tuple(PyObject *unicode,
- Py_ssize_t len)
+ Py_ssize_t len)
{
PyObject *v;
if (unicode == NULL)
@@ -145,86 +145,86 @@ PyObject *codec_tuple(PyObject *unicode,
/* --- String codecs ------------------------------------------------------ */
static PyObject *
escape_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
const char *errors = NULL;
const char *data;
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "s#|z:escape_decode",
- &data, &size, &errors))
- return NULL;
+ &data, &size, &errors))
+ return NULL;
return codec_tuple(PyBytes_DecodeEscape(data, size, errors, 0, NULL),
- size);
+ size);
}
static PyObject *
escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- static const char *hexdigits = "0123456789abcdef";
- PyObject *str;
- Py_ssize_t size;
- Py_ssize_t newsize;
- const char *errors = NULL;
- PyObject *v;
-
- if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
- &PyBytes_Type, &str, &errors))
- return NULL;
-
- size = PyBytes_GET_SIZE(str);
- newsize = 4*size;
- if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) {
- PyErr_SetString(PyExc_OverflowError,
- "string is too large to encode");
- return NULL;
- }
- v = PyBytes_FromStringAndSize(NULL, newsize);
-
- if (v == NULL) {
- return NULL;
- }
- else {
- register Py_ssize_t i;
- register char c;
- register char *p = PyBytes_AS_STRING(v);
-
- for (i = 0; i < size; i++) {
- /* There's at least enough room for a hex escape */
- assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4);
- c = PyBytes_AS_STRING(str)[i];
- if (c == '\'' || c == '\\')
- *p++ = '\\', *p++ = c;
- else if (c == '\t')
- *p++ = '\\', *p++ = 't';
- else if (c == '\n')
- *p++ = '\\', *p++ = 'n';
- else if (c == '\r')
- *p++ = '\\', *p++ = 'r';
- else if (c < ' ' || c >= 0x7f) {
- *p++ = '\\';
- *p++ = 'x';
- *p++ = hexdigits[(c & 0xf0) >> 4];
- *p++ = hexdigits[c & 0xf];
- }
- else
- *p++ = c;
- }
- *p = '\0';
- if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) {
- return NULL;
- }
- }
-
- return codec_tuple(v, size);
+ static const char *hexdigits = "0123456789abcdef";
+ PyObject *str;
+ Py_ssize_t size;
+ Py_ssize_t newsize;
+ const char *errors = NULL;
+ PyObject *v;
+
+ if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
+ &PyBytes_Type, &str, &errors))
+ return NULL;
+
+ size = PyBytes_GET_SIZE(str);
+ newsize = 4*size;
+ if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) {
+ PyErr_SetString(PyExc_OverflowError,
+ "string is too large to encode");
+ return NULL;
+ }
+ v = PyBytes_FromStringAndSize(NULL, newsize);
+
+ if (v == NULL) {
+ return NULL;
+ }
+ else {
+ register Py_ssize_t i;
+ register char c;
+ register char *p = PyBytes_AS_STRING(v);
+
+ for (i = 0; i < size; i++) {
+ /* There's at least enough room for a hex escape */
+ assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4);
+ c = PyBytes_AS_STRING(str)[i];
+ if (c == '\'' || c == '\\')
+ *p++ = '\\', *p++ = c;
+ else if (c == '\t')
+ *p++ = '\\', *p++ = 't';
+ else if (c == '\n')
+ *p++ = '\\', *p++ = 'n';
+ else if (c == '\r')
+ *p++ = '\\', *p++ = 'r';
+ else if (c < ' ' || c >= 0x7f) {
+ *p++ = '\\';
+ *p++ = 'x';
+ *p++ = hexdigits[(c & 0xf0) >> 4];
+ *p++ = hexdigits[c & 0xf];
+ }
+ else
+ *p++ = c;
+ }
+ *p = '\0';
+ if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) {
+ return NULL;
+ }
+ }
+
+ return codec_tuple(v, size);
}
/* --- Decoder ------------------------------------------------------------ */
static PyObject *
unicode_internal_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *obj;
const char *errors = NULL;
@@ -232,19 +232,19 @@ unicode_internal_decode(PyObject *self,
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "O|z:unicode_internal_decode",
- &obj, &errors))
- return NULL;
+ &obj, &errors))
+ return NULL;
if (PyUnicode_Check(obj)) {
- Py_INCREF(obj);
- return codec_tuple(obj, PyUnicode_GET_SIZE(obj));
+ Py_INCREF(obj);
+ return codec_tuple(obj, PyUnicode_GET_SIZE(obj));
}
else {
- if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
- return NULL;
+ if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
+ return NULL;
- return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors),
- size);
+ return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors),
+ size);
}
}
@@ -252,20 +252,20 @@ static PyObject *
utf_7_decode(PyObject *self,
PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int final = 0;
Py_ssize_t consumed;
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "y*|zi:utf_7_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len;
decoded = PyUnicode_DecodeUTF7Stateful(pbuf.buf, pbuf.len, errors,
- final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
return NULL;
return codec_tuple(decoded, consumed);
@@ -273,32 +273,32 @@ utf_7_decode(PyObject *self,
static PyObject *
utf_8_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int final = 0;
Py_ssize_t consumed;
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "y*|zi:utf_8_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len;
decoded = PyUnicode_DecodeUTF8Stateful(pbuf.buf, pbuf.len, errors,
- final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_16_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
int final = 0;
@@ -306,22 +306,22 @@ utf_16_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "y*|zi:utf_16_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_16_le_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = -1;
int final = 0;
@@ -329,23 +329,23 @@ utf_16_le_decode(PyObject *self,
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "y*|zi:utf_16_le_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_16_be_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 1;
int final = 0;
@@ -353,15 +353,15 @@ utf_16_be_decode(PyObject *self,
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "y*|zi:utf_16_be_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
@@ -375,9 +375,9 @@ utf_16_be_decode(PyObject *self,
static PyObject *
utf_16_ex_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
PyObject *unicode, *tuple;
@@ -385,14 +385,14 @@ utf_16_ex_decode(PyObject *self,
Py_ssize_t consumed;
if (!PyArg_ParseTuple(args, "y*|zii:utf_16_ex_decode",
- &pbuf, &errors, &byteorder, &final))
- return NULL;
+ &pbuf, &errors, &byteorder, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
unicode = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (unicode == NULL)
- return NULL;
+ return NULL;
tuple = Py_BuildValue("Oni", unicode, consumed, byteorder);
Py_DECREF(unicode);
return tuple;
@@ -400,9 +400,9 @@ utf_16_ex_decode(PyObject *self,
static PyObject *
utf_32_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
int final = 0;
@@ -410,22 +410,22 @@ utf_32_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "y*|zi:utf_32_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_32_le_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = -1;
int final = 0;
@@ -433,22 +433,22 @@ utf_32_le_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "y*|zi:utf_32_le_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_32_be_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 1;
int final = 0;
@@ -456,14 +456,14 @@ utf_32_be_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "y*|zi:utf_32_be_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
@@ -477,9 +477,9 @@ utf_32_be_decode(PyObject *self,
static PyObject *
utf_32_ex_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
PyObject *unicode, *tuple;
@@ -487,14 +487,14 @@ utf_32_ex_decode(PyObject *self,
Py_ssize_t consumed;
if (!PyArg_ParseTuple(args, "y*|zii:utf_32_ex_decode",
- &pbuf, &errors, &byteorder, &final))
- return NULL;
+ &pbuf, &errors, &byteorder, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
unicode = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (unicode == NULL)
- return NULL;
+ return NULL;
tuple = Py_BuildValue("Oni", unicode, consumed, byteorder);
Py_DECREF(unicode);
return tuple;
@@ -502,114 +502,114 @@ utf_32_ex_decode(PyObject *self,
static PyObject *
unicode_escape_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
- PyObject *unicode;
+ PyObject *unicode;
if (!PyArg_ParseTuple(args, "s*|z:unicode_escape_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
raw_unicode_escape_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
- PyObject *unicode;
+ PyObject *unicode;
if (!PyArg_ParseTuple(args, "s*|z:raw_unicode_escape_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
latin_1_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
- PyObject *unicode;
+ Py_buffer pbuf;
+ PyObject *unicode;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "y*|z:latin_1_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
ascii_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
- PyObject *unicode;
+ Py_buffer pbuf;
+ PyObject *unicode;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "y*|z:ascii_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
charmap_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
- PyObject *unicode;
+ Py_buffer pbuf;
+ PyObject *unicode;
const char *errors = NULL;
PyObject *mapping = NULL;
if (!PyArg_ParseTuple(args, "y*|zO:charmap_decode",
- &pbuf, &errors, &mapping))
- return NULL;
+ &pbuf, &errors, &mapping))
+ return NULL;
if (mapping == Py_None)
- mapping = NULL;
+ mapping = NULL;
- unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
static PyObject *
mbcs_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int final = 0;
Py_ssize_t consumed;
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "y*|zi:mbcs_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len;
decoded = PyUnicode_DecodeMBCSStateful(pbuf.buf, pbuf.len, errors,
- final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
@@ -619,7 +619,7 @@ mbcs_decode(PyObject *self,
static PyObject *
readbuffer_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
Py_buffer pdata;
const char *data;
@@ -628,8 +628,8 @@ readbuffer_encode(PyObject *self,
PyObject *result;
if (!PyArg_ParseTuple(args, "s*|z:readbuffer_encode",
- &pdata, &errors))
- return NULL;
+ &pdata, &errors))
+ return NULL;
data = pdata.buf;
size = pdata.len;
@@ -640,22 +640,22 @@ readbuffer_encode(PyObject *self,
static PyObject *
charbuffer_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
const char *data;
Py_ssize_t size;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "t#|z:charbuffer_encode",
- &data, &size, &errors))
- return NULL;
+ &data, &size, &errors))
+ return NULL;
return codec_tuple(PyBytes_FromStringAndSize(data, size), size);
}
static PyObject *
unicode_internal_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *obj;
const char *errors = NULL;
@@ -663,64 +663,64 @@ unicode_internal_encode(PyObject *self,
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "O|z:unicode_internal_encode",
- &obj, &errors))
- return NULL;
+ &obj, &errors))
+ return NULL;
if (PyUnicode_Check(obj)) {
- data = PyUnicode_AS_DATA(obj);
- size = PyUnicode_GET_DATA_SIZE(obj);
- return codec_tuple(PyBytes_FromStringAndSize(data, size),
- PyUnicode_GET_SIZE(obj));
+ data = PyUnicode_AS_DATA(obj);
+ size = PyUnicode_GET_DATA_SIZE(obj);
+ return codec_tuple(PyBytes_FromStringAndSize(data, size),
+ PyUnicode_GET_SIZE(obj));
}
else {
- if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
- return NULL;
- return codec_tuple(PyBytes_FromStringAndSize(data, size), size);
+ if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
+ return NULL;
+ return codec_tuple(PyBytes_FromStringAndSize(data, size), size);
}
}
static PyObject *
utf_7_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_7_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF7(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- 0,
- 0,
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ 0,
+ 0,
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_8_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_8_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -734,70 +734,70 @@ utf_8_encode(PyObject *self,
static PyObject *
utf_16_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
int byteorder = 0;
if (!PyArg_ParseTuple(args, "O|zi:utf_16_encode",
- &str, &errors, &byteorder))
- return NULL;
+ &str, &errors, &byteorder))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- byteorder),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ byteorder),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_16_le_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_16_le_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- -1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ -1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_16_be_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_16_be_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- +1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ +1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -811,186 +811,186 @@ utf_16_be_encode(PyObject *self,
static PyObject *
utf_32_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
int byteorder = 0;
if (!PyArg_ParseTuple(args, "O|zi:utf_32_encode",
- &str, &errors, &byteorder))
- return NULL;
+ &str, &errors, &byteorder))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- byteorder),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ byteorder),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_32_le_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_32_le_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- -1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ -1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_32_be_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_32_be_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- +1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ +1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
unicode_escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:unicode_escape_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str)),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str)),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
raw_unicode_escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:raw_unicode_escape_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeRawUnicodeEscape(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str)),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str)),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
latin_1_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:latin_1_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeLatin1(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
ascii_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:ascii_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeASCII(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
charmap_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
PyObject *mapping = NULL;
if (!PyArg_ParseTuple(args, "O|zO:charmap_encode",
- &str, &errors, &mapping))
- return NULL;
+ &str, &errors, &mapping))
+ return NULL;
if (mapping == Py_None)
- mapping = NULL;
+ mapping = NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeCharmap(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- mapping,
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ mapping,
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -1008,23 +1008,23 @@ charmap_build(PyObject *self, PyObject *args)
static PyObject *
mbcs_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:mbcs_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeMBCS(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -1048,8 +1048,8 @@ static PyObject *register_error(PyObject *self, PyObject *args)
PyObject *handler;
if (!PyArg_ParseTuple(args, "sO:register_error",
- &name, &handler))
- return NULL;
+ &name, &handler))
+ return NULL;
if (PyCodec_RegisterError(name, handler))
return NULL;
Py_RETURN_NONE;
@@ -1066,82 +1066,82 @@ static PyObject *lookup_error(PyObject *self, PyObject *args)
const char *name;
if (!PyArg_ParseTuple(args, "s:lookup_error",
- &name))
- return NULL;
+ &name))
+ return NULL;
return PyCodec_LookupError(name);
}
/* --- Module API --------------------------------------------------------- */
static PyMethodDef _codecs_functions[] = {
- {"register", codec_register, METH_O,
+ {"register", codec_register, METH_O,
register__doc__},
- {"lookup", codec_lookup, METH_VARARGS,
+ {"lookup", codec_lookup, METH_VARARGS,
lookup__doc__},
- {"encode", codec_encode, METH_VARARGS,
- encode__doc__},
- {"decode", codec_decode, METH_VARARGS,
- decode__doc__},
- {"escape_encode", escape_encode, METH_VARARGS},
- {"escape_decode", escape_decode, METH_VARARGS},
- {"utf_8_encode", utf_8_encode, METH_VARARGS},
- {"utf_8_decode", utf_8_decode, METH_VARARGS},
- {"utf_7_encode", utf_7_encode, METH_VARARGS},
- {"utf_7_decode", utf_7_decode, METH_VARARGS},
- {"utf_16_encode", utf_16_encode, METH_VARARGS},
- {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS},
- {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS},
- {"utf_16_decode", utf_16_decode, METH_VARARGS},
- {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS},
- {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS},
- {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS},
- {"utf_32_encode", utf_32_encode, METH_VARARGS},
- {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS},
- {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS},
- {"utf_32_decode", utf_32_decode, METH_VARARGS},
- {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS},
- {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS},
- {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS},
- {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS},
- {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS},
- {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS},
- {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS},
- {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS},
- {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS},
- {"latin_1_encode", latin_1_encode, METH_VARARGS},
- {"latin_1_decode", latin_1_decode, METH_VARARGS},
- {"ascii_encode", ascii_encode, METH_VARARGS},
- {"ascii_decode", ascii_decode, METH_VARARGS},
- {"charmap_encode", charmap_encode, METH_VARARGS},
- {"charmap_decode", charmap_decode, METH_VARARGS},
- {"charmap_build", charmap_build, METH_VARARGS},
- {"readbuffer_encode", readbuffer_encode, METH_VARARGS},
- {"charbuffer_encode", charbuffer_encode, METH_VARARGS},
+ {"encode", codec_encode, METH_VARARGS,
+ encode__doc__},
+ {"decode", codec_decode, METH_VARARGS,
+ decode__doc__},
+ {"escape_encode", escape_encode, METH_VARARGS},
+ {"escape_decode", escape_decode, METH_VARARGS},
+ {"utf_8_encode", utf_8_encode, METH_VARARGS},
+ {"utf_8_decode", utf_8_decode, METH_VARARGS},
+ {"utf_7_encode", utf_7_encode, METH_VARARGS},
+ {"utf_7_decode", utf_7_decode, METH_VARARGS},
+ {"utf_16_encode", utf_16_encode, METH_VARARGS},
+ {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS},
+ {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS},
+ {"utf_16_decode", utf_16_decode, METH_VARARGS},
+ {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS},
+ {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS},
+ {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS},
+ {"utf_32_encode", utf_32_encode, METH_VARARGS},
+ {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS},
+ {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS},
+ {"utf_32_decode", utf_32_decode, METH_VARARGS},
+ {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS},
+ {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS},
+ {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS},
+ {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS},
+ {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS},
+ {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS},
+ {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS},
+ {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS},
+ {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS},
+ {"latin_1_encode", latin_1_encode, METH_VARARGS},
+ {"latin_1_decode", latin_1_decode, METH_VARARGS},
+ {"ascii_encode", ascii_encode, METH_VARARGS},
+ {"ascii_decode", ascii_decode, METH_VARARGS},
+ {"charmap_encode", charmap_encode, METH_VARARGS},
+ {"charmap_decode", charmap_decode, METH_VARARGS},
+ {"charmap_build", charmap_build, METH_VARARGS},
+ {"readbuffer_encode", readbuffer_encode, METH_VARARGS},
+ {"charbuffer_encode", charbuffer_encode, METH_VARARGS},
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
- {"mbcs_encode", mbcs_encode, METH_VARARGS},
- {"mbcs_decode", mbcs_decode, METH_VARARGS},
+ {"mbcs_encode", mbcs_encode, METH_VARARGS},
+ {"mbcs_decode", mbcs_decode, METH_VARARGS},
#endif
- {"register_error", register_error, METH_VARARGS,
+ {"register_error", register_error, METH_VARARGS,
register_error__doc__},
- {"lookup_error", lookup_error, METH_VARARGS,
+ {"lookup_error", lookup_error, METH_VARARGS,
lookup_error__doc__},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef codecsmodule = {
- PyModuleDef_HEAD_INIT,
- "_codecs",
- NULL,
- -1,
- _codecs_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_codecs",
+ NULL,
+ -1,
+ _codecs_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__codecs(void)
{
- return PyModule_Create(&codecsmodule);
+ return PyModule_Create(&codecsmodule);
}
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
index fa0f004..1459d97 100644
--- a/Modules/_collectionsmodule.c
+++ b/Modules/_collectionsmodule.c
@@ -46,9 +46,9 @@
*/
typedef struct BLOCK {
- struct BLOCK *leftlink;
- struct BLOCK *rightlink;
- PyObject *data[BLOCKLEN];
+ struct BLOCK *leftlink;
+ struct BLOCK *rightlink;
+ PyObject *data[BLOCKLEN];
} block;
#define MAXFREEBLOCKS 10
@@ -57,71 +57,71 @@ static block *freeblocks[MAXFREEBLOCKS];
static block *
newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
- block *b;
- /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
- * refuse to allocate new blocks if the current len is dangerously
- * close. There is some extra margin to prevent spurious arithmetic
- * overflows at various places. The following check ensures that
- * the blocks allocated to the deque, in the worst case, can only
- * have PY_SSIZE_T_MAX-2 entries in total.
- */
- if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
- PyErr_SetString(PyExc_OverflowError,
- "cannot add more blocks to the deque");
- return NULL;
- }
- if (numfreeblocks) {
- numfreeblocks -= 1;
- b = freeblocks[numfreeblocks];
- } else {
- b = PyMem_Malloc(sizeof(block));
- if (b == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- }
- b->leftlink = leftlink;
- b->rightlink = rightlink;
- return b;
+ block *b;
+ /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
+ * refuse to allocate new blocks if the current len is dangerously
+ * close. There is some extra margin to prevent spurious arithmetic
+ * overflows at various places. The following check ensures that
+ * the blocks allocated to the deque, in the worst case, can only
+ * have PY_SSIZE_T_MAX-2 entries in total.
+ */
+ if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot add more blocks to the deque");
+ return NULL;
+ }
+ if (numfreeblocks) {
+ numfreeblocks -= 1;
+ b = freeblocks[numfreeblocks];
+ } else {
+ b = PyMem_Malloc(sizeof(block));
+ if (b == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ }
+ b->leftlink = leftlink;
+ b->rightlink = rightlink;
+ return b;
}
static void
freeblock(block *b)
{
- if (numfreeblocks < MAXFREEBLOCKS) {
- freeblocks[numfreeblocks] = b;
- numfreeblocks++;
- } else {
- PyMem_Free(b);
- }
+ if (numfreeblocks < MAXFREEBLOCKS) {
+ freeblocks[numfreeblocks] = b;
+ numfreeblocks++;
+ } else {
+ PyMem_Free(b);
+ }
}
typedef struct {
- PyObject_HEAD
- block *leftblock;
- block *rightblock;
- Py_ssize_t leftindex; /* in range(BLOCKLEN) */
- Py_ssize_t rightindex; /* in range(BLOCKLEN) */
- Py_ssize_t len;
- Py_ssize_t maxlen;
- long state; /* incremented whenever the indices move */
- PyObject *weakreflist; /* List of weak references */
+ PyObject_HEAD
+ block *leftblock;
+ block *rightblock;
+ Py_ssize_t leftindex; /* in range(BLOCKLEN) */
+ Py_ssize_t rightindex; /* in range(BLOCKLEN) */
+ Py_ssize_t len;
+ Py_ssize_t maxlen;
+ long state; /* incremented whenever the indices move */
+ PyObject *weakreflist; /* List of weak references */
} dequeobject;
/* The deque's size limit is d.maxlen. The limit can be zero or positive.
* If there is no limit, then d.maxlen == -1.
- *
+ *
* After an item is added to a deque, we check to see if the size has grown past
* the limit. If it has, we get the size back down to the limit by popping an
* item off of the opposite end. The methods that can trigger this are append(),
* appendleft(), extend(), and extendleft().
*/
-#define TRIM(d, popfunction) \
- if (d->maxlen != -1 && d->len > d->maxlen) { \
- PyObject *rv = popfunction(d, NULL); \
- assert(rv != NULL && d->len <= d->maxlen); \
- Py_DECREF(rv); \
+#define TRIM(d, popfunction) \
+ if (d->maxlen != -1 && d->len > d->maxlen) { \
+ PyObject *rv = popfunction(d, NULL); \
+ assert(rv != NULL && d->len <= d->maxlen); \
+ Py_DECREF(rv); \
}
static PyTypeObject deque_type;
@@ -129,65 +129,65 @@ static PyTypeObject deque_type;
static PyObject *
deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- dequeobject *deque;
- block *b;
-
- /* create dequeobject structure */
- deque = (dequeobject *)type->tp_alloc(type, 0);
- if (deque == NULL)
- return NULL;
-
- b = newblock(NULL, NULL, 0);
- if (b == NULL) {
- Py_DECREF(deque);
- return NULL;
- }
-
- assert(BLOCKLEN >= 2);
- deque->leftblock = b;
- deque->rightblock = b;
- deque->leftindex = CENTER + 1;
- deque->rightindex = CENTER;
- deque->len = 0;
- deque->state = 0;
- deque->weakreflist = NULL;
- deque->maxlen = -1;
-
- return (PyObject *)deque;
+ dequeobject *deque;
+ block *b;
+
+ /* create dequeobject structure */
+ deque = (dequeobject *)type->tp_alloc(type, 0);
+ if (deque == NULL)
+ return NULL;
+
+ b = newblock(NULL, NULL, 0);
+ if (b == NULL) {
+ Py_DECREF(deque);
+ return NULL;
+ }
+
+ assert(BLOCKLEN >= 2);
+ deque->leftblock = b;
+ deque->rightblock = b;
+ deque->leftindex = CENTER + 1;
+ deque->rightindex = CENTER;
+ deque->len = 0;
+ deque->state = 0;
+ deque->weakreflist = NULL;
+ deque->maxlen = -1;
+
+ return (PyObject *)deque;
}
static PyObject *
deque_pop(dequeobject *deque, PyObject *unused)
{
- PyObject *item;
- block *prevblock;
-
- if (deque->len == 0) {
- PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
- return NULL;
- }
- item = deque->rightblock->data[deque->rightindex];
- deque->rightindex--;
- deque->len--;
- deque->state++;
-
- if (deque->rightindex == -1) {
- if (deque->len == 0) {
- assert(deque->leftblock == deque->rightblock);
- assert(deque->leftindex == deque->rightindex+1);
- /* re-center instead of freeing a block */
- deque->leftindex = CENTER + 1;
- deque->rightindex = CENTER;
- } else {
- prevblock = deque->rightblock->leftlink;
- assert(deque->leftblock != deque->rightblock);
- freeblock(deque->rightblock);
- prevblock->rightlink = NULL;
- deque->rightblock = prevblock;
- deque->rightindex = BLOCKLEN - 1;
- }
- }
- return item;
+ PyObject *item;
+ block *prevblock;
+
+ if (deque->len == 0) {
+ PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
+ return NULL;
+ }
+ item = deque->rightblock->data[deque->rightindex];
+ deque->rightindex--;
+ deque->len--;
+ deque->state++;
+
+ if (deque->rightindex == -1) {
+ if (deque->len == 0) {
+ assert(deque->leftblock == deque->rightblock);
+ assert(deque->leftindex == deque->rightindex+1);
+ /* re-center instead of freeing a block */
+ deque->leftindex = CENTER + 1;
+ deque->rightindex = CENTER;
+ } else {
+ prevblock = deque->rightblock->leftlink;
+ assert(deque->leftblock != deque->rightblock);
+ freeblock(deque->rightblock);
+ prevblock->rightlink = NULL;
+ deque->rightblock = prevblock;
+ deque->rightindex = BLOCKLEN - 1;
+ }
+ }
+ return item;
}
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
@@ -195,37 +195,37 @@ PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
static PyObject *
deque_popleft(dequeobject *deque, PyObject *unused)
{
- PyObject *item;
- block *prevblock;
-
- if (deque->len == 0) {
- PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
- return NULL;
- }
- assert(deque->leftblock != NULL);
- item = deque->leftblock->data[deque->leftindex];
- deque->leftindex++;
- deque->len--;
- deque->state++;
-
- if (deque->leftindex == BLOCKLEN) {
- if (deque->len == 0) {
- assert(deque->leftblock == deque->rightblock);
- assert(deque->leftindex == deque->rightindex+1);
- /* re-center instead of freeing a block */
- deque->leftindex = CENTER + 1;
- deque->rightindex = CENTER;
- } else {
- assert(deque->leftblock != deque->rightblock);
- prevblock = deque->leftblock->rightlink;
- freeblock(deque->leftblock);
- assert(prevblock != NULL);
- prevblock->leftlink = NULL;
- deque->leftblock = prevblock;
- deque->leftindex = 0;
- }
- }
- return item;
+ PyObject *item;
+ block *prevblock;
+
+ if (deque->len == 0) {
+ PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
+ return NULL;
+ }
+ assert(deque->leftblock != NULL);
+ item = deque->leftblock->data[deque->leftindex];
+ deque->leftindex++;
+ deque->len--;
+ deque->state++;
+
+ if (deque->leftindex == BLOCKLEN) {
+ if (deque->len == 0) {
+ assert(deque->leftblock == deque->rightblock);
+ assert(deque->leftindex == deque->rightindex+1);
+ /* re-center instead of freeing a block */
+ deque->leftindex = CENTER + 1;
+ deque->rightindex = CENTER;
+ } else {
+ assert(deque->leftblock != deque->rightblock);
+ prevblock = deque->leftblock->rightlink;
+ freeblock(deque->leftblock);
+ assert(prevblock != NULL);
+ prevblock->leftlink = NULL;
+ deque->leftblock = prevblock;
+ deque->leftindex = 0;
+ }
+ }
+ return item;
}
PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
@@ -233,22 +233,22 @@ PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
static PyObject *
deque_append(dequeobject *deque, PyObject *item)
{
- deque->state++;
- if (deque->rightindex == BLOCKLEN-1) {
- block *b = newblock(deque->rightblock, NULL, deque->len);
- if (b == NULL)
- return NULL;
- assert(deque->rightblock->rightlink == NULL);
- deque->rightblock->rightlink = b;
- deque->rightblock = b;
- deque->rightindex = -1;
- }
- Py_INCREF(item);
- deque->len++;
- deque->rightindex++;
- deque->rightblock->data[deque->rightindex] = item;
- TRIM(deque, deque_popleft);
- Py_RETURN_NONE;
+ deque->state++;
+ if (deque->rightindex == BLOCKLEN-1) {
+ block *b = newblock(deque->rightblock, NULL, deque->len);
+ if (b == NULL)
+ return NULL;
+ assert(deque->rightblock->rightlink == NULL);
+ deque->rightblock->rightlink = b;
+ deque->rightblock = b;
+ deque->rightindex = -1;
+ }
+ Py_INCREF(item);
+ deque->len++;
+ deque->rightindex++;
+ deque->rightblock->data[deque->rightindex] = item;
+ TRIM(deque, deque_popleft);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
@@ -256,90 +256,90 @@ PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
static PyObject *
deque_appendleft(dequeobject *deque, PyObject *item)
{
- deque->state++;
- if (deque->leftindex == 0) {
- block *b = newblock(NULL, deque->leftblock, deque->len);
- if (b == NULL)
- return NULL;
- assert(deque->leftblock->leftlink == NULL);
- deque->leftblock->leftlink = b;
- deque->leftblock = b;
- deque->leftindex = BLOCKLEN;
- }
- Py_INCREF(item);
- deque->len++;
- deque->leftindex--;
- deque->leftblock->data[deque->leftindex] = item;
- TRIM(deque, deque_pop);
- Py_RETURN_NONE;
+ deque->state++;
+ if (deque->leftindex == 0) {
+ block *b = newblock(NULL, deque->leftblock, deque->len);
+ if (b == NULL)
+ return NULL;
+ assert(deque->leftblock->leftlink == NULL);
+ deque->leftblock->leftlink = b;
+ deque->leftblock = b;
+ deque->leftindex = BLOCKLEN;
+ }
+ Py_INCREF(item);
+ deque->len++;
+ deque->leftindex--;
+ deque->leftblock->data[deque->leftindex] = item;
+ TRIM(deque, deque_pop);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
-/* Run an iterator to exhaustion. Shortcut for
+/* Run an iterator to exhaustion. Shortcut for
the extend/extendleft methods when maxlen == 0. */
static PyObject*
consume_iterator(PyObject *it)
{
- PyObject *item;
-
- while ((item = PyIter_Next(it)) != NULL) {
- Py_DECREF(item);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
+ PyObject *item;
+
+ while ((item = PyIter_Next(it)) != NULL) {
+ Py_DECREF(item);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_NONE;
}
static PyObject *
deque_extend(dequeobject *deque, PyObject *iterable)
{
- PyObject *it, *item;
-
- /* Handle case where id(deque) == id(iterable) */
- if ((PyObject *)deque == iterable) {
- PyObject *result;
- PyObject *s = PySequence_List(iterable);
- if (s == NULL)
- return NULL;
- result = deque_extend(deque, s);
- Py_DECREF(s);
- return result;
- }
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- if (deque->maxlen == 0)
- return consume_iterator(it);
-
- while ((item = PyIter_Next(it)) != NULL) {
- deque->state++;
- if (deque->rightindex == BLOCKLEN-1) {
- block *b = newblock(deque->rightblock, NULL,
- deque->len);
- if (b == NULL) {
- Py_DECREF(item);
- Py_DECREF(it);
- return NULL;
- }
- assert(deque->rightblock->rightlink == NULL);
- deque->rightblock->rightlink = b;
- deque->rightblock = b;
- deque->rightindex = -1;
- }
- deque->len++;
- deque->rightindex++;
- deque->rightblock->data[deque->rightindex] = item;
- TRIM(deque, deque_popleft);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
+ PyObject *it, *item;
+
+ /* Handle case where id(deque) == id(iterable) */
+ if ((PyObject *)deque == iterable) {
+ PyObject *result;
+ PyObject *s = PySequence_List(iterable);
+ if (s == NULL)
+ return NULL;
+ result = deque_extend(deque, s);
+ Py_DECREF(s);
+ return result;
+ }
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ if (deque->maxlen == 0)
+ return consume_iterator(it);
+
+ while ((item = PyIter_Next(it)) != NULL) {
+ deque->state++;
+ if (deque->rightindex == BLOCKLEN-1) {
+ block *b = newblock(deque->rightblock, NULL,
+ deque->len);
+ if (b == NULL) {
+ Py_DECREF(item);
+ Py_DECREF(it);
+ return NULL;
+ }
+ assert(deque->rightblock->rightlink == NULL);
+ deque->rightblock->rightlink = b;
+ deque->rightblock = b;
+ deque->rightindex = -1;
+ }
+ deque->len++;
+ deque->rightindex++;
+ deque->rightblock->data[deque->rightindex] = item;
+ TRIM(deque, deque_popleft);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(extend_doc,
@@ -348,50 +348,50 @@ PyDoc_STRVAR(extend_doc,
static PyObject *
deque_extendleft(dequeobject *deque, PyObject *iterable)
{
- PyObject *it, *item;
-
- /* Handle case where id(deque) == id(iterable) */
- if ((PyObject *)deque == iterable) {
- PyObject *result;
- PyObject *s = PySequence_List(iterable);
- if (s == NULL)
- return NULL;
- result = deque_extendleft(deque, s);
- Py_DECREF(s);
- return result;
- }
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- if (deque->maxlen == 0)
- return consume_iterator(it);
-
- while ((item = PyIter_Next(it)) != NULL) {
- deque->state++;
- if (deque->leftindex == 0) {
- block *b = newblock(NULL, deque->leftblock,
- deque->len);
- if (b == NULL) {
- Py_DECREF(item);
- Py_DECREF(it);
- return NULL;
- }
- assert(deque->leftblock->leftlink == NULL);
- deque->leftblock->leftlink = b;
- deque->leftblock = b;
- deque->leftindex = BLOCKLEN;
- }
- deque->len++;
- deque->leftindex--;
- deque->leftblock->data[deque->leftindex] = item;
- TRIM(deque, deque_pop);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
+ PyObject *it, *item;
+
+ /* Handle case where id(deque) == id(iterable) */
+ if ((PyObject *)deque == iterable) {
+ PyObject *result;
+ PyObject *s = PySequence_List(iterable);
+ if (s == NULL)
+ return NULL;
+ result = deque_extendleft(deque, s);
+ Py_DECREF(s);
+ return result;
+ }
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ if (deque->maxlen == 0)
+ return consume_iterator(it);
+
+ while ((item = PyIter_Next(it)) != NULL) {
+ deque->state++;
+ if (deque->leftindex == 0) {
+ block *b = newblock(NULL, deque->leftblock,
+ deque->len);
+ if (b == NULL) {
+ Py_DECREF(item);
+ Py_DECREF(it);
+ return NULL;
+ }
+ assert(deque->leftblock->leftlink == NULL);
+ deque->leftblock->leftlink = b;
+ deque->leftblock = b;
+ deque->leftindex = BLOCKLEN;
+ }
+ deque->len++;
+ deque->leftindex--;
+ deque->leftblock->data[deque->leftindex] = item;
+ TRIM(deque, deque_pop);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(extendleft_doc,
@@ -400,63 +400,63 @@ PyDoc_STRVAR(extendleft_doc,
static PyObject *
deque_inplace_concat(dequeobject *deque, PyObject *other)
{
- PyObject *result;
-
- result = deque_extend(deque, other);
- if (result == NULL)
- return result;
- Py_DECREF(result);
- Py_INCREF(deque);
- return (PyObject *)deque;
+ PyObject *result;
+
+ result = deque_extend(deque, other);
+ if (result == NULL)
+ return result;
+ Py_DECREF(result);
+ Py_INCREF(deque);
+ return (PyObject *)deque;
}
static int
_deque_rotate(dequeobject *deque, Py_ssize_t n)
{
- Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
- PyObject *item, *rv;
-
- if (len == 0)
- return 0;
- if (n > halflen || n < -halflen) {
- n %= len;
- if (n > halflen)
- n -= len;
- else if (n < -halflen)
- n += len;
- }
-
- for (i=0 ; i<n ; i++) {
- item = deque_pop(deque, NULL);
- assert (item != NULL);
- rv = deque_appendleft(deque, item);
- Py_DECREF(item);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- for (i=0 ; i>n ; i--) {
- item = deque_popleft(deque, NULL);
- assert (item != NULL);
- rv = deque_append(deque, item);
- Py_DECREF(item);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- return 0;
+ Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
+ PyObject *item, *rv;
+
+ if (len == 0)
+ return 0;
+ if (n > halflen || n < -halflen) {
+ n %= len;
+ if (n > halflen)
+ n -= len;
+ else if (n < -halflen)
+ n += len;
+ }
+
+ for (i=0 ; i<n ; i++) {
+ item = deque_pop(deque, NULL);
+ assert (item != NULL);
+ rv = deque_appendleft(deque, item);
+ Py_DECREF(item);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ for (i=0 ; i>n ; i--) {
+ item = deque_popleft(deque, NULL);
+ assert (item != NULL);
+ rv = deque_append(deque, item);
+ Py_DECREF(item);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ return 0;
}
static PyObject *
deque_rotate(dequeobject *deque, PyObject *args)
{
- Py_ssize_t n=1;
+ Py_ssize_t n=1;
- if (!PyArg_ParseTuple(args, "|n:rotate", &n))
- return NULL;
- if (_deque_rotate(deque, n) == 0)
- Py_RETURN_NONE;
- return NULL;
+ if (!PyArg_ParseTuple(args, "|n:rotate", &n))
+ return NULL;
+ if (_deque_rotate(deque, n) == 0)
+ Py_RETURN_NONE;
+ return NULL;
}
PyDoc_STRVAR(rotate_doc,
@@ -465,40 +465,40 @@ PyDoc_STRVAR(rotate_doc,
static PyObject *
deque_reverse(dequeobject *deque, PyObject *unused)
{
- block *leftblock = deque->leftblock;
- block *rightblock = deque->rightblock;
- Py_ssize_t leftindex = deque->leftindex;
- Py_ssize_t rightindex = deque->rightindex;
- Py_ssize_t n = (deque->len)/2;
- Py_ssize_t i;
- PyObject *tmp;
-
- for (i=0 ; i<n ; i++) {
- /* Validate that pointers haven't met in the middle */
- assert(leftblock != rightblock || leftindex < rightindex);
-
- /* Swap */
- tmp = leftblock->data[leftindex];
- leftblock->data[leftindex] = rightblock->data[rightindex];
- rightblock->data[rightindex] = tmp;
-
- /* Advance left block/index pair */
- leftindex++;
- if (leftindex == BLOCKLEN) {
- assert (leftblock->rightlink != NULL);
- leftblock = leftblock->rightlink;
- leftindex = 0;
- }
-
- /* Step backwards with the right block/index pair */
- rightindex--;
- if (rightindex == -1) {
- assert (rightblock->leftlink != NULL);
- rightblock = rightblock->leftlink;
- rightindex = BLOCKLEN - 1;
- }
- }
- Py_RETURN_NONE;
+ block *leftblock = deque->leftblock;
+ block *rightblock = deque->rightblock;
+ Py_ssize_t leftindex = deque->leftindex;
+ Py_ssize_t rightindex = deque->rightindex;
+ Py_ssize_t n = (deque->len)/2;
+ Py_ssize_t i;
+ PyObject *tmp;
+
+ for (i=0 ; i<n ; i++) {
+ /* Validate that pointers haven't met in the middle */
+ assert(leftblock != rightblock || leftindex < rightindex);
+
+ /* Swap */
+ tmp = leftblock->data[leftindex];
+ leftblock->data[leftindex] = rightblock->data[rightindex];
+ rightblock->data[rightindex] = tmp;
+
+ /* Advance left block/index pair */
+ leftindex++;
+ if (leftindex == BLOCKLEN) {
+ assert (leftblock->rightlink != NULL);
+ leftblock = leftblock->rightlink;
+ leftindex = 0;
+ }
+
+ /* Step backwards with the right block/index pair */
+ rightindex--;
+ if (rightindex == -1) {
+ assert (rightblock->leftlink != NULL);
+ rightblock = rightblock->leftlink;
+ rightindex = BLOCKLEN - 1;
+ }
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(reverse_doc,
@@ -507,38 +507,38 @@ PyDoc_STRVAR(reverse_doc,
static PyObject *
deque_count(dequeobject *deque, PyObject *v)
{
- block *leftblock = deque->leftblock;
- Py_ssize_t leftindex = deque->leftindex;
- Py_ssize_t n = (deque->len);
- Py_ssize_t i;
- Py_ssize_t count = 0;
- PyObject *item;
- long start_state = deque->state;
- int cmp;
-
- for (i=0 ; i<n ; i++) {
- item = leftblock->data[leftindex];
- cmp = PyObject_RichCompareBool(item, v, Py_EQ);
- if (cmp > 0)
- count++;
- else if (cmp < 0)
- return NULL;
-
- if (start_state != deque->state) {
- PyErr_SetString(PyExc_RuntimeError,
- "deque mutated during iteration");
- return NULL;
- }
-
- /* Advance left block/index pair */
- leftindex++;
- if (leftindex == BLOCKLEN) {
- assert (leftblock->rightlink != NULL);
- leftblock = leftblock->rightlink;
- leftindex = 0;
- }
- }
- return PyLong_FromSsize_t(count);
+ block *leftblock = deque->leftblock;
+ Py_ssize_t leftindex = deque->leftindex;
+ Py_ssize_t n = (deque->len);
+ Py_ssize_t i;
+ Py_ssize_t count = 0;
+ PyObject *item;
+ long start_state = deque->state;
+ int cmp;
+
+ for (i=0 ; i<n ; i++) {
+ item = leftblock->data[leftindex];
+ cmp = PyObject_RichCompareBool(item, v, Py_EQ);
+ if (cmp > 0)
+ count++;
+ else if (cmp < 0)
+ return NULL;
+
+ if (start_state != deque->state) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "deque mutated during iteration");
+ return NULL;
+ }
+
+ /* Advance left block/index pair */
+ leftindex++;
+ if (leftindex == BLOCKLEN) {
+ assert (leftblock->rightlink != NULL);
+ leftblock = leftblock->rightlink;
+ leftindex = 0;
+ }
+ }
+ return PyLong_FromSsize_t(count);
}
PyDoc_STRVAR(count_doc,
@@ -547,39 +547,39 @@ PyDoc_STRVAR(count_doc,
static Py_ssize_t
deque_len(dequeobject *deque)
{
- return deque->len;
+ return deque->len;
}
static PyObject *
deque_remove(dequeobject *deque, PyObject *value)
{
- Py_ssize_t i, n=deque->len;
-
- for (i=0 ; i<n ; i++) {
- PyObject *item = deque->leftblock->data[deque->leftindex];
- int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
-
- if (deque->len != n) {
- PyErr_SetString(PyExc_IndexError,
- "deque mutated during remove().");
- return NULL;
- }
- if (cmp > 0) {
- PyObject *tgt = deque_popleft(deque, NULL);
- assert (tgt != NULL);
- Py_DECREF(tgt);
- if (_deque_rotate(deque, i) == -1)
- return NULL;
- Py_RETURN_NONE;
- }
- else if (cmp < 0) {
- _deque_rotate(deque, i);
- return NULL;
- }
- _deque_rotate(deque, -1);
- }
- PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
- return NULL;
+ Py_ssize_t i, n=deque->len;
+
+ for (i=0 ; i<n ; i++) {
+ PyObject *item = deque->leftblock->data[deque->leftindex];
+ int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
+
+ if (deque->len != n) {
+ PyErr_SetString(PyExc_IndexError,
+ "deque mutated during remove().");
+ return NULL;
+ }
+ if (cmp > 0) {
+ PyObject *tgt = deque_popleft(deque, NULL);
+ assert (tgt != NULL);
+ Py_DECREF(tgt);
+ if (_deque_rotate(deque, i) == -1)
+ return NULL;
+ Py_RETURN_NONE;
+ }
+ else if (cmp < 0) {
+ _deque_rotate(deque, i);
+ return NULL;
+ }
+ _deque_rotate(deque, -1);
+ }
+ PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
+ return NULL;
}
PyDoc_STRVAR(remove_doc,
@@ -588,56 +588,56 @@ PyDoc_STRVAR(remove_doc,
static int
deque_clear(dequeobject *deque)
{
- PyObject *item;
-
- while (deque->len) {
- item = deque_pop(deque, NULL);
- assert (item != NULL);
- Py_DECREF(item);
- }
- assert(deque->leftblock == deque->rightblock &&
- deque->leftindex - 1 == deque->rightindex &&
- deque->len == 0);
- return 0;
+ PyObject *item;
+
+ while (deque->len) {
+ item = deque_pop(deque, NULL);
+ assert (item != NULL);
+ Py_DECREF(item);
+ }
+ assert(deque->leftblock == deque->rightblock &&
+ deque->leftindex - 1 == deque->rightindex &&
+ deque->len == 0);
+ return 0;
}
static PyObject *
deque_item(dequeobject *deque, Py_ssize_t i)
{
- block *b;
- PyObject *item;
- Py_ssize_t n, index=i;
-
- if (i < 0 || i >= deque->len) {
- PyErr_SetString(PyExc_IndexError,
- "deque index out of range");
- return NULL;
- }
-
- if (i == 0) {
- i = deque->leftindex;
- b = deque->leftblock;
- } else if (i == deque->len - 1) {
- i = deque->rightindex;
- b = deque->rightblock;
- } else {
- i += deque->leftindex;
- n = i / BLOCKLEN;
- i %= BLOCKLEN;
- if (index < (deque->len >> 1)) {
- b = deque->leftblock;
- while (n--)
- b = b->rightlink;
- } else {
- n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
- b = deque->rightblock;
- while (n--)
- b = b->leftlink;
- }
- }
- item = b->data[i];
- Py_INCREF(item);
- return item;
+ block *b;
+ PyObject *item;
+ Py_ssize_t n, index=i;
+
+ if (i < 0 || i >= deque->len) {
+ PyErr_SetString(PyExc_IndexError,
+ "deque index out of range");
+ return NULL;
+ }
+
+ if (i == 0) {
+ i = deque->leftindex;
+ b = deque->leftblock;
+ } else if (i == deque->len - 1) {
+ i = deque->rightindex;
+ b = deque->rightblock;
+ } else {
+ i += deque->leftindex;
+ n = i / BLOCKLEN;
+ i %= BLOCKLEN;
+ if (index < (deque->len >> 1)) {
+ b = deque->leftblock;
+ while (n--)
+ b = b->rightlink;
+ } else {
+ n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
+ b = deque->rightblock;
+ while (n--)
+ b = b->leftlink;
+ }
+ }
+ item = b->data[i];
+ Py_INCREF(item);
+ return item;
}
/* delitem() implemented in terms of rotate for simplicity and reasonable
@@ -650,62 +650,62 @@ deque_item(dequeobject *deque, Py_ssize_t i)
static int
deque_del_item(dequeobject *deque, Py_ssize_t i)
{
- PyObject *item;
+ PyObject *item;
- assert (i >= 0 && i < deque->len);
- if (_deque_rotate(deque, -i) == -1)
- return -1;
+ assert (i >= 0 && i < deque->len);
+ if (_deque_rotate(deque, -i) == -1)
+ return -1;
- item = deque_popleft(deque, NULL);
- assert (item != NULL);
- Py_DECREF(item);
+ item = deque_popleft(deque, NULL);
+ assert (item != NULL);
+ Py_DECREF(item);
- return _deque_rotate(deque, i);
+ return _deque_rotate(deque, i);
}
static int
deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
{
- PyObject *old_value;
- block *b;
- Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
-
- if (i < 0 || i >= len) {
- PyErr_SetString(PyExc_IndexError,
- "deque index out of range");
- return -1;
- }
- if (v == NULL)
- return deque_del_item(deque, i);
-
- i += deque->leftindex;
- n = i / BLOCKLEN;
- i %= BLOCKLEN;
- if (index <= halflen) {
- b = deque->leftblock;
- while (n--)
- b = b->rightlink;
- } else {
- n = (deque->leftindex + len - 1) / BLOCKLEN - n;
- b = deque->rightblock;
- while (n--)
- b = b->leftlink;
- }
- Py_INCREF(v);
- old_value = b->data[i];
- b->data[i] = v;
- Py_DECREF(old_value);
- return 0;
+ PyObject *old_value;
+ block *b;
+ Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
+
+ if (i < 0 || i >= len) {
+ PyErr_SetString(PyExc_IndexError,
+ "deque index out of range");
+ return -1;
+ }
+ if (v == NULL)
+ return deque_del_item(deque, i);
+
+ i += deque->leftindex;
+ n = i / BLOCKLEN;
+ i %= BLOCKLEN;
+ if (index <= halflen) {
+ b = deque->leftblock;
+ while (n--)
+ b = b->rightlink;
+ } else {
+ n = (deque->leftindex + len - 1) / BLOCKLEN - n;
+ b = deque->rightblock;
+ while (n--)
+ b = b->leftlink;
+ }
+ Py_INCREF(v);
+ old_value = b->data[i];
+ b->data[i] = v;
+ Py_DECREF(old_value);
+ return 0;
}
static PyObject *
deque_clearmethod(dequeobject *deque)
{
- int rv;
+ int rv;
- rv = deque_clear(deque);
- assert (rv != -1);
- Py_RETURN_NONE;
+ rv = deque_clear(deque);
+ assert (rv != -1);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
@@ -713,49 +713,49 @@ PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
static void
deque_dealloc(dequeobject *deque)
{
- PyObject_GC_UnTrack(deque);
- if (deque->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) deque);
- if (deque->leftblock != NULL) {
- deque_clear(deque);
- assert(deque->leftblock != NULL);
- freeblock(deque->leftblock);
- }
- deque->leftblock = NULL;
- deque->rightblock = NULL;
- Py_TYPE(deque)->tp_free(deque);
+ PyObject_GC_UnTrack(deque);
+ if (deque->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) deque);
+ if (deque->leftblock != NULL) {
+ deque_clear(deque);
+ assert(deque->leftblock != NULL);
+ freeblock(deque->leftblock);
+ }
+ deque->leftblock = NULL;
+ deque->rightblock = NULL;
+ Py_TYPE(deque)->tp_free(deque);
}
static int
deque_traverse(dequeobject *deque, visitproc visit, void *arg)
{
- block *b;
- PyObject *item;
- Py_ssize_t index;
- Py_ssize_t indexlo = deque->leftindex;
-
- for (b = deque->leftblock; b != NULL; b = b->rightlink) {
- const Py_ssize_t indexhi = b == deque->rightblock ?
- deque->rightindex :
- BLOCKLEN - 1;
-
- for (index = indexlo; index <= indexhi; ++index) {
- item = b->data[index];
- Py_VISIT(item);
- }
- indexlo = 0;
- }
- return 0;
+ block *b;
+ PyObject *item;
+ Py_ssize_t index;
+ Py_ssize_t indexlo = deque->leftindex;
+
+ for (b = deque->leftblock; b != NULL; b = b->rightlink) {
+ const Py_ssize_t indexhi = b == deque->rightblock ?
+ deque->rightindex :
+ BLOCKLEN - 1;
+
+ for (index = indexlo; index <= indexhi; ++index) {
+ item = b->data[index];
+ Py_VISIT(item);
+ }
+ indexlo = 0;
+ }
+ return 0;
}
static PyObject *
deque_copy(PyObject *deque)
{
- if (((dequeobject *)deque)->maxlen == -1)
- return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
- else
- return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
- deque, ((dequeobject *)deque)->maxlen, NULL);
+ if (((dequeobject *)deque)->maxlen == -1)
+ return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
+ else
+ return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
+ deque, ((dequeobject *)deque)->maxlen, NULL);
}
PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
@@ -763,30 +763,30 @@ PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
static PyObject *
deque_reduce(dequeobject *deque)
{
- PyObject *dict, *result, *aslist;
-
- dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
- if (dict == NULL)
- PyErr_Clear();
- aslist = PySequence_List((PyObject *)deque);
- if (aslist == NULL) {
- Py_XDECREF(dict);
- return NULL;
- }
- if (dict == NULL) {
- if (deque->maxlen == -1)
- result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
- else
- result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
- } else {
- if (deque->maxlen == -1)
- result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
- else
- result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
- }
- Py_XDECREF(dict);
- Py_DECREF(aslist);
- return result;
+ PyObject *dict, *result, *aslist;
+
+ dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
+ if (dict == NULL)
+ PyErr_Clear();
+ aslist = PySequence_List((PyObject *)deque);
+ if (aslist == NULL) {
+ Py_XDECREF(dict);
+ return NULL;
+ }
+ if (dict == NULL) {
+ if (deque->maxlen == -1)
+ result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
+ else
+ result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
+ } else {
+ if (deque->maxlen == -1)
+ result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
+ else
+ result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
+ }
+ Py_XDECREF(dict);
+ Py_DECREF(aslist);
+ return result;
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
@@ -794,166 +794,166 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyObject *
deque_repr(PyObject *deque)
{
- PyObject *aslist, *result;
- int i;
-
- i = Py_ReprEnter(deque);
- if (i != 0) {
- if (i < 0)
- return NULL;
- return PyUnicode_FromString("[...]");
- }
-
- aslist = PySequence_List(deque);
- if (aslist == NULL) {
- Py_ReprLeave(deque);
- return NULL;
- }
- if (((dequeobject *)deque)->maxlen != -1)
-
- result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
- aslist, ((dequeobject *)deque)->maxlen);
- else
- result = PyUnicode_FromFormat("deque(%R)", aslist);
- Py_DECREF(aslist);
- Py_ReprLeave(deque);
- return result;
+ PyObject *aslist, *result;
+ int i;
+
+ i = Py_ReprEnter(deque);
+ if (i != 0) {
+ if (i < 0)
+ return NULL;
+ return PyUnicode_FromString("[...]");
+ }
+
+ aslist = PySequence_List(deque);
+ if (aslist == NULL) {
+ Py_ReprLeave(deque);
+ return NULL;
+ }
+ if (((dequeobject *)deque)->maxlen != -1)
+
+ result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
+ aslist, ((dequeobject *)deque)->maxlen);
+ else
+ result = PyUnicode_FromFormat("deque(%R)", aslist);
+ Py_DECREF(aslist);
+ Py_ReprLeave(deque);
+ return result;
}
static PyObject *
deque_richcompare(PyObject *v, PyObject *w, int op)
{
- PyObject *it1=NULL, *it2=NULL, *x, *y;
- Py_ssize_t vs, ws;
- int b, cmp=-1;
-
- if (!PyObject_TypeCheck(v, &deque_type) ||
- !PyObject_TypeCheck(w, &deque_type)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- /* Shortcuts */
- vs = ((dequeobject *)v)->len;
- ws = ((dequeobject *)w)->len;
- if (op == Py_EQ) {
- if (v == w)
- Py_RETURN_TRUE;
- if (vs != ws)
- Py_RETURN_FALSE;
- }
- if (op == Py_NE) {
- if (v == w)
- Py_RETURN_FALSE;
- if (vs != ws)
- Py_RETURN_TRUE;
- }
-
- /* Search for the first index where items are different */
- it1 = PyObject_GetIter(v);
- if (it1 == NULL)
- goto done;
- it2 = PyObject_GetIter(w);
- if (it2 == NULL)
- goto done;
- for (;;) {
- x = PyIter_Next(it1);
- if (x == NULL && PyErr_Occurred())
- goto done;
- y = PyIter_Next(it2);
- if (x == NULL || y == NULL)
- break;
- b = PyObject_RichCompareBool(x, y, Py_EQ);
- if (b == 0) {
- cmp = PyObject_RichCompareBool(x, y, op);
- Py_DECREF(x);
- Py_DECREF(y);
- goto done;
- }
- Py_DECREF(x);
- Py_DECREF(y);
- if (b == -1)
- goto done;
- }
- /* We reached the end of one deque or both */
- Py_XDECREF(x);
- Py_XDECREF(y);
- if (PyErr_Occurred())
- goto done;
- switch (op) {
- case Py_LT: cmp = y != NULL; break; /* if w was longer */
- case Py_LE: cmp = x == NULL; break; /* if v was not longer */
- case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
- case Py_NE: cmp = x != y; break; /* if one deque continues */
- case Py_GT: cmp = x != NULL; break; /* if v was longer */
- case Py_GE: cmp = y == NULL; break; /* if w was not longer */
- }
+ PyObject *it1=NULL, *it2=NULL, *x, *y;
+ Py_ssize_t vs, ws;
+ int b, cmp=-1;
+
+ if (!PyObject_TypeCheck(v, &deque_type) ||
+ !PyObject_TypeCheck(w, &deque_type)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ /* Shortcuts */
+ vs = ((dequeobject *)v)->len;
+ ws = ((dequeobject *)w)->len;
+ if (op == Py_EQ) {
+ if (v == w)
+ Py_RETURN_TRUE;
+ if (vs != ws)
+ Py_RETURN_FALSE;
+ }
+ if (op == Py_NE) {
+ if (v == w)
+ Py_RETURN_FALSE;
+ if (vs != ws)
+ Py_RETURN_TRUE;
+ }
+
+ /* Search for the first index where items are different */
+ it1 = PyObject_GetIter(v);
+ if (it1 == NULL)
+ goto done;
+ it2 = PyObject_GetIter(w);
+ if (it2 == NULL)
+ goto done;
+ for (;;) {
+ x = PyIter_Next(it1);
+ if (x == NULL && PyErr_Occurred())
+ goto done;
+ y = PyIter_Next(it2);
+ if (x == NULL || y == NULL)
+ break;
+ b = PyObject_RichCompareBool(x, y, Py_EQ);
+ if (b == 0) {
+ cmp = PyObject_RichCompareBool(x, y, op);
+ Py_DECREF(x);
+ Py_DECREF(y);
+ goto done;
+ }
+ Py_DECREF(x);
+ Py_DECREF(y);
+ if (b == -1)
+ goto done;
+ }
+ /* We reached the end of one deque or both */
+ Py_XDECREF(x);
+ Py_XDECREF(y);
+ if (PyErr_Occurred())
+ goto done;
+ switch (op) {
+ case Py_LT: cmp = y != NULL; break; /* if w was longer */
+ case Py_LE: cmp = x == NULL; break; /* if v was not longer */
+ case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
+ case Py_NE: cmp = x != y; break; /* if one deque continues */
+ case Py_GT: cmp = x != NULL; break; /* if v was longer */
+ case Py_GE: cmp = y == NULL; break; /* if w was not longer */
+ }
done:
- Py_XDECREF(it1);
- Py_XDECREF(it2);
- if (cmp == 1)
- Py_RETURN_TRUE;
- if (cmp == 0)
- Py_RETURN_FALSE;
- return NULL;
+ Py_XDECREF(it1);
+ Py_XDECREF(it2);
+ if (cmp == 1)
+ Py_RETURN_TRUE;
+ if (cmp == 0)
+ Py_RETURN_FALSE;
+ return NULL;
}
static int
deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
{
- PyObject *iterable = NULL;
- PyObject *maxlenobj = NULL;
- Py_ssize_t maxlen = -1;
- char *kwlist[] = {"iterable", "maxlen", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
- return -1;
- if (maxlenobj != NULL && maxlenobj != Py_None) {
- maxlen = PyLong_AsSsize_t(maxlenobj);
- if (maxlen == -1 && PyErr_Occurred())
- return -1;
- if (maxlen < 0) {
- PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
- return -1;
- }
- }
- deque->maxlen = maxlen;
- deque_clear(deque);
- if (iterable != NULL) {
- PyObject *rv = deque_extend(deque, iterable);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- return 0;
+ PyObject *iterable = NULL;
+ PyObject *maxlenobj = NULL;
+ Py_ssize_t maxlen = -1;
+ char *kwlist[] = {"iterable", "maxlen", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
+ return -1;
+ if (maxlenobj != NULL && maxlenobj != Py_None) {
+ maxlen = PyLong_AsSsize_t(maxlenobj);
+ if (maxlen == -1 && PyErr_Occurred())
+ return -1;
+ if (maxlen < 0) {
+ PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
+ return -1;
+ }
+ }
+ deque->maxlen = maxlen;
+ deque_clear(deque);
+ if (iterable != NULL) {
+ PyObject *rv = deque_extend(deque, iterable);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ return 0;
}
static PyObject *
deque_get_maxlen(dequeobject *deque)
{
- if (deque->maxlen == -1)
- Py_RETURN_NONE;
- return PyLong_FromSsize_t(deque->maxlen);
+ if (deque->maxlen == -1)
+ Py_RETURN_NONE;
+ return PyLong_FromSsize_t(deque->maxlen);
}
static PyGetSetDef deque_getset[] = {
- {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
- "maximum size of a deque or None if unbounded"},
- {0}
+ {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
+ "maximum size of a deque or None if unbounded"},
+ {0}
};
static PySequenceMethods deque_as_sequence = {
- (lenfunc)deque_len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)deque_item, /* sq_item */
- 0, /* sq_slice */
- (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
- 0, /* sq_ass_slice */
- 0, /* sq_contains */
- (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ (lenfunc)deque_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ (ssizeargfunc)deque_item, /* sq_item */
+ 0, /* sq_slice */
+ (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ 0, /* sq_contains */
+ (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
@@ -962,38 +962,38 @@ static PySequenceMethods deque_as_sequence = {
static PyObject *deque_iter(dequeobject *deque);
static PyObject *deque_reviter(dequeobject *deque);
PyDoc_STRVAR(reversed_doc,
- "D.__reversed__() -- return a reverse iterator over the deque");
+ "D.__reversed__() -- return a reverse iterator over the deque");
static PyMethodDef deque_methods[] = {
- {"append", (PyCFunction)deque_append,
- METH_O, append_doc},
- {"appendleft", (PyCFunction)deque_appendleft,
- METH_O, appendleft_doc},
- {"clear", (PyCFunction)deque_clearmethod,
- METH_NOARGS, clear_doc},
- {"__copy__", (PyCFunction)deque_copy,
- METH_NOARGS, copy_doc},
- {"count", (PyCFunction)deque_count,
- METH_O, count_doc},
- {"extend", (PyCFunction)deque_extend,
- METH_O, extend_doc},
- {"extendleft", (PyCFunction)deque_extendleft,
- METH_O, extendleft_doc},
- {"pop", (PyCFunction)deque_pop,
- METH_NOARGS, pop_doc},
- {"popleft", (PyCFunction)deque_popleft,
- METH_NOARGS, popleft_doc},
- {"__reduce__", (PyCFunction)deque_reduce,
- METH_NOARGS, reduce_doc},
- {"remove", (PyCFunction)deque_remove,
- METH_O, remove_doc},
- {"__reversed__", (PyCFunction)deque_reviter,
- METH_NOARGS, reversed_doc},
- {"reverse", (PyCFunction)deque_reverse,
- METH_NOARGS, reverse_doc},
- {"rotate", (PyCFunction)deque_rotate,
- METH_VARARGS, rotate_doc},
- {NULL, NULL} /* sentinel */
+ {"append", (PyCFunction)deque_append,
+ METH_O, append_doc},
+ {"appendleft", (PyCFunction)deque_appendleft,
+ METH_O, appendleft_doc},
+ {"clear", (PyCFunction)deque_clearmethod,
+ METH_NOARGS, clear_doc},
+ {"__copy__", (PyCFunction)deque_copy,
+ METH_NOARGS, copy_doc},
+ {"count", (PyCFunction)deque_count,
+ METH_O, count_doc},
+ {"extend", (PyCFunction)deque_extend,
+ METH_O, extend_doc},
+ {"extendleft", (PyCFunction)deque_extendleft,
+ METH_O, extendleft_doc},
+ {"pop", (PyCFunction)deque_pop,
+ METH_NOARGS, pop_doc},
+ {"popleft", (PyCFunction)deque_popleft,
+ METH_NOARGS, popleft_doc},
+ {"__reduce__", (PyCFunction)deque_reduce,
+ METH_NOARGS, reduce_doc},
+ {"remove", (PyCFunction)deque_remove,
+ METH_O, remove_doc},
+ {"__reversed__", (PyCFunction)deque_reviter,
+ METH_NOARGS, reversed_doc},
+ {"reverse", (PyCFunction)deque_reverse,
+ METH_NOARGS, reverse_doc},
+ {"rotate", (PyCFunction)deque_rotate,
+ METH_VARARGS, rotate_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(deque_doc,
@@ -1002,58 +1002,58 @@ PyDoc_STRVAR(deque_doc,
Build an ordered collection accessible from endpoints only.");
static PyTypeObject deque_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "collections.deque", /* tp_name */
- sizeof(dequeobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)deque_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- deque_repr, /* tp_repr */
- 0, /* tp_as_number */
- &deque_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- /* tp_flags */
- deque_doc, /* tp_doc */
- (traverseproc)deque_traverse, /* tp_traverse */
- (inquiry)deque_clear, /* tp_clear */
- (richcmpfunc)deque_richcompare, /* tp_richcompare */
- offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
- (getiterfunc)deque_iter, /* tp_iter */
- 0, /* tp_iternext */
- deque_methods, /* tp_methods */
- 0, /* tp_members */
- deque_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)deque_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- deque_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "collections.deque", /* tp_name */
+ sizeof(dequeobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)deque_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ deque_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &deque_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ /* tp_flags */
+ deque_doc, /* tp_doc */
+ (traverseproc)deque_traverse, /* tp_traverse */
+ (inquiry)deque_clear, /* tp_clear */
+ (richcmpfunc)deque_richcompare, /* tp_richcompare */
+ offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
+ (getiterfunc)deque_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ deque_methods, /* tp_methods */
+ 0, /* tp_members */
+ deque_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)deque_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ deque_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/*********************** Deque Iterator **************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t index;
- block *b;
- dequeobject *deque;
- long state; /* state when the iterator is created */
- Py_ssize_t counter; /* number of items remaining for iteration */
+ PyObject_HEAD
+ Py_ssize_t index;
+ block *b;
+ dequeobject *deque;
+ long state; /* state when the iterator is created */
+ Py_ssize_t counter; /* number of items remaining for iteration */
} dequeiterobject;
static PyTypeObject dequeiter_type;
@@ -1061,107 +1061,107 @@ static PyTypeObject dequeiter_type;
static PyObject *
deque_iter(dequeobject *deque)
{
- dequeiterobject *it;
-
- it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
- if (it == NULL)
- return NULL;
- it->b = deque->leftblock;
- it->index = deque->leftindex;
- Py_INCREF(deque);
- it->deque = deque;
- it->state = deque->state;
- it->counter = deque->len;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ dequeiterobject *it;
+
+ it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
+ if (it == NULL)
+ return NULL;
+ it->b = deque->leftblock;
+ it->index = deque->leftindex;
+ Py_INCREF(deque);
+ it->deque = deque;
+ it->state = deque->state;
+ it->counter = deque->len;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static int
dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
{
- Py_VISIT(dio->deque);
- return 0;
+ Py_VISIT(dio->deque);
+ return 0;
}
static void
dequeiter_dealloc(dequeiterobject *dio)
{
- Py_XDECREF(dio->deque);
- PyObject_GC_Del(dio);
+ Py_XDECREF(dio->deque);
+ PyObject_GC_Del(dio);
}
static PyObject *
dequeiter_next(dequeiterobject *it)
{
- PyObject *item;
-
- if (it->deque->state != it->state) {
- it->counter = 0;
- PyErr_SetString(PyExc_RuntimeError,
- "deque mutated during iteration");
- return NULL;
- }
- if (it->counter == 0)
- return NULL;
- assert (!(it->b == it->deque->rightblock &&
- it->index > it->deque->rightindex));
-
- item = it->b->data[it->index];
- it->index++;
- it->counter--;
- if (it->index == BLOCKLEN && it->counter > 0) {
- assert (it->b->rightlink != NULL);
- it->b = it->b->rightlink;
- it->index = 0;
- }
- Py_INCREF(item);
- return item;
+ PyObject *item;
+
+ if (it->deque->state != it->state) {
+ it->counter = 0;
+ PyErr_SetString(PyExc_RuntimeError,
+ "deque mutated during iteration");
+ return NULL;
+ }
+ if (it->counter == 0)
+ return NULL;
+ assert (!(it->b == it->deque->rightblock &&
+ it->index > it->deque->rightindex));
+
+ item = it->b->data[it->index];
+ it->index++;
+ it->counter--;
+ if (it->index == BLOCKLEN && it->counter > 0) {
+ assert (it->b->rightlink != NULL);
+ it->b = it->b->rightlink;
+ it->index = 0;
+ }
+ Py_INCREF(item);
+ return item;
}
static PyObject *
dequeiter_len(dequeiterobject *it)
{
- return PyLong_FromLong(it->counter);
+ return PyLong_FromLong(it->counter);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef dequeiter_methods[] = {
- {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject dequeiter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "deque_iterator", /* tp_name */
- sizeof(dequeiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dequeiter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dequeiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dequeiter_next, /* tp_iternext */
- dequeiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "deque_iterator", /* tp_name */
+ sizeof(dequeiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dequeiter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dequeiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dequeiter_next, /* tp_iternext */
+ dequeiter_methods, /* tp_methods */
+ 0,
};
/*********************** Deque Reverse Iterator **************************/
@@ -1171,87 +1171,87 @@ static PyTypeObject dequereviter_type;
static PyObject *
deque_reviter(dequeobject *deque)
{
- dequeiterobject *it;
-
- it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
- if (it == NULL)
- return NULL;
- it->b = deque->rightblock;
- it->index = deque->rightindex;
- Py_INCREF(deque);
- it->deque = deque;
- it->state = deque->state;
- it->counter = deque->len;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ dequeiterobject *it;
+
+ it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
+ if (it == NULL)
+ return NULL;
+ it->b = deque->rightblock;
+ it->index = deque->rightindex;
+ Py_INCREF(deque);
+ it->deque = deque;
+ it->state = deque->state;
+ it->counter = deque->len;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static PyObject *
dequereviter_next(dequeiterobject *it)
{
- PyObject *item;
- if (it->counter == 0)
- return NULL;
-
- if (it->deque->state != it->state) {
- it->counter = 0;
- PyErr_SetString(PyExc_RuntimeError,
- "deque mutated during iteration");
- return NULL;
- }
- assert (!(it->b == it->deque->leftblock &&
- it->index < it->deque->leftindex));
-
- item = it->b->data[it->index];
- it->index--;
- it->counter--;
- if (it->index == -1 && it->counter > 0) {
- assert (it->b->leftlink != NULL);
- it->b = it->b->leftlink;
- it->index = BLOCKLEN - 1;
- }
- Py_INCREF(item);
- return item;
+ PyObject *item;
+ if (it->counter == 0)
+ return NULL;
+
+ if (it->deque->state != it->state) {
+ it->counter = 0;
+ PyErr_SetString(PyExc_RuntimeError,
+ "deque mutated during iteration");
+ return NULL;
+ }
+ assert (!(it->b == it->deque->leftblock &&
+ it->index < it->deque->leftindex));
+
+ item = it->b->data[it->index];
+ it->index--;
+ it->counter--;
+ if (it->index == -1 && it->counter > 0) {
+ assert (it->b->leftlink != NULL);
+ it->b = it->b->leftlink;
+ it->index = BLOCKLEN - 1;
+ }
+ Py_INCREF(item);
+ return item;
}
static PyTypeObject dequereviter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "deque_reverse_iterator", /* tp_name */
- sizeof(dequeiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dequeiter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dequeiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dequereviter_next, /* tp_iternext */
- dequeiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "deque_reverse_iterator", /* tp_name */
+ sizeof(dequeiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dequeiter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dequeiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dequereviter_next, /* tp_iternext */
+ dequeiter_methods, /* tp_methods */
+ 0,
};
/* defaultdict type *********************************************************/
typedef struct {
- PyDictObject dict;
- PyObject *default_factory;
+ PyDictObject dict;
+ PyObject *default_factory;
} defdictobject;
static PyTypeObject defdict_type; /* Forward */
@@ -1266,25 +1266,25 @@ PyDoc_STRVAR(defdict_missing_doc,
static PyObject *
defdict_missing(defdictobject *dd, PyObject *key)
{
- PyObject *factory = dd->default_factory;
- PyObject *value;
- if (factory == NULL || factory == Py_None) {
- /* XXX Call dict.__missing__(key) */
- PyObject *tup;
- tup = PyTuple_Pack(1, key);
- if (!tup) return NULL;
- PyErr_SetObject(PyExc_KeyError, tup);
- Py_DECREF(tup);
- return NULL;
- }
- value = PyEval_CallObject(factory, NULL);
- if (value == NULL)
- return value;
- if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
- Py_DECREF(value);
- return NULL;
- }
- return value;
+ PyObject *factory = dd->default_factory;
+ PyObject *value;
+ if (factory == NULL || factory == Py_None) {
+ /* XXX Call dict.__missing__(key) */
+ PyObject *tup;
+ tup = PyTuple_Pack(1, key);
+ if (!tup) return NULL;
+ PyErr_SetObject(PyExc_KeyError, tup);
+ Py_DECREF(tup);
+ return NULL;
+ }
+ value = PyEval_CallObject(factory, NULL);
+ if (value == NULL)
+ return value;
+ if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
+ Py_DECREF(value);
+ return NULL;
+ }
+ return value;
}
PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
@@ -1292,175 +1292,175 @@ PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
static PyObject *
defdict_copy(defdictobject *dd)
{
- /* This calls the object's class. That only works for subclasses
- whose class constructor has the same signature. Subclasses that
- define a different constructor signature must override copy().
- */
-
- if (dd->default_factory == NULL)
- return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
- return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
- dd->default_factory, dd, NULL);
+ /* This calls the object's class. That only works for subclasses
+ whose class constructor has the same signature. Subclasses that
+ define a different constructor signature must override copy().
+ */
+
+ if (dd->default_factory == NULL)
+ return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
+ return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
+ dd->default_factory, dd, NULL);
}
static PyObject *
defdict_reduce(defdictobject *dd)
{
- /* __reduce__ must return a 5-tuple as follows:
-
- - factory function
- - tuple of args for the factory function
- - additional state (here None)
- - sequence iterator (here None)
- - dictionary iterator (yielding successive (key, value) pairs
-
- This API is used by pickle.py and copy.py.
-
- For this to be useful with pickle.py, the default_factory
- must be picklable; e.g., None, a built-in, or a global
- function in a module or package.
-
- Both shallow and deep copying are supported, but for deep
- copying, the default_factory must be deep-copyable; e.g. None,
- or a built-in (functions are not copyable at this time).
-
- This only works for subclasses as long as their constructor
- signature is compatible; the first argument must be the
- optional default_factory, defaulting to None.
- */
- PyObject *args;
- PyObject *items;
- PyObject *iter;
- PyObject *result;
- if (dd->default_factory == NULL || dd->default_factory == Py_None)
- args = PyTuple_New(0);
- else
- args = PyTuple_Pack(1, dd->default_factory);
- if (args == NULL)
- return NULL;
- items = PyObject_CallMethod((PyObject *)dd, "items", "()");
- if (items == NULL) {
- Py_DECREF(args);
- return NULL;
- }
- iter = PyObject_GetIter(items);
- if (iter == NULL) {
- Py_DECREF(items);
- Py_DECREF(args);
- return NULL;
- }
- result = PyTuple_Pack(5, Py_TYPE(dd), args,
- Py_None, Py_None, iter);
- Py_DECREF(iter);
- Py_DECREF(items);
- Py_DECREF(args);
- return result;
+ /* __reduce__ must return a 5-tuple as follows:
+
+ - factory function
+ - tuple of args for the factory function
+ - additional state (here None)
+ - sequence iterator (here None)
+ - dictionary iterator (yielding successive (key, value) pairs
+
+ This API is used by pickle.py and copy.py.
+
+ For this to be useful with pickle.py, the default_factory
+ must be picklable; e.g., None, a built-in, or a global
+ function in a module or package.
+
+ Both shallow and deep copying are supported, but for deep
+ copying, the default_factory must be deep-copyable; e.g. None,
+ or a built-in (functions are not copyable at this time).
+
+ This only works for subclasses as long as their constructor
+ signature is compatible; the first argument must be the
+ optional default_factory, defaulting to None.
+ */
+ PyObject *args;
+ PyObject *items;
+ PyObject *iter;
+ PyObject *result;
+ if (dd->default_factory == NULL || dd->default_factory == Py_None)
+ args = PyTuple_New(0);
+ else
+ args = PyTuple_Pack(1, dd->default_factory);
+ if (args == NULL)
+ return NULL;
+ items = PyObject_CallMethod((PyObject *)dd, "items", "()");
+ if (items == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ iter = PyObject_GetIter(items);
+ if (iter == NULL) {
+ Py_DECREF(items);
+ Py_DECREF(args);
+ return NULL;
+ }
+ result = PyTuple_Pack(5, Py_TYPE(dd), args,
+ Py_None, Py_None, iter);
+ Py_DECREF(iter);
+ Py_DECREF(items);
+ Py_DECREF(args);
+ return result;
}
static PyMethodDef defdict_methods[] = {
- {"__missing__", (PyCFunction)defdict_missing, METH_O,
- defdict_missing_doc},
- {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
- defdict_copy_doc},
- {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
- defdict_copy_doc},
- {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
- reduce_doc},
- {NULL}
+ {"__missing__", (PyCFunction)defdict_missing, METH_O,
+ defdict_missing_doc},
+ {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
+ defdict_copy_doc},
+ {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
+ defdict_copy_doc},
+ {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
+ reduce_doc},
+ {NULL}
};
static PyMemberDef defdict_members[] = {
- {"default_factory", T_OBJECT,
- offsetof(defdictobject, default_factory), 0,
- PyDoc_STR("Factory for default value called by __missing__().")},
- {NULL}
+ {"default_factory", T_OBJECT,
+ offsetof(defdictobject, default_factory), 0,
+ PyDoc_STR("Factory for default value called by __missing__().")},
+ {NULL}
};
static void
defdict_dealloc(defdictobject *dd)
{
- Py_CLEAR(dd->default_factory);
- PyDict_Type.tp_dealloc((PyObject *)dd);
+ Py_CLEAR(dd->default_factory);
+ PyDict_Type.tp_dealloc((PyObject *)dd);
}
static PyObject *
defdict_repr(defdictobject *dd)
{
- PyObject *baserepr;
- PyObject *defrepr;
- PyObject *result;
- baserepr = PyDict_Type.tp_repr((PyObject *)dd);
- if (baserepr == NULL)
- return NULL;
- if (dd->default_factory == NULL)
- defrepr = PyUnicode_FromString("None");
- else
- {
- int status = Py_ReprEnter(dd->default_factory);
- if (status != 0) {
- if (status < 0)
- return NULL;
- defrepr = PyUnicode_FromString("...");
- }
- else
- defrepr = PyObject_Repr(dd->default_factory);
- Py_ReprLeave(dd->default_factory);
- }
- if (defrepr == NULL) {
- Py_DECREF(baserepr);
- return NULL;
- }
- result = PyUnicode_FromFormat("defaultdict(%U, %U)",
- defrepr, baserepr);
- Py_DECREF(defrepr);
- Py_DECREF(baserepr);
- return result;
+ PyObject *baserepr;
+ PyObject *defrepr;
+ PyObject *result;
+ baserepr = PyDict_Type.tp_repr((PyObject *)dd);
+ if (baserepr == NULL)
+ return NULL;
+ if (dd->default_factory == NULL)
+ defrepr = PyUnicode_FromString("None");
+ else
+ {
+ int status = Py_ReprEnter(dd->default_factory);
+ if (status != 0) {
+ if (status < 0)
+ return NULL;
+ defrepr = PyUnicode_FromString("...");
+ }
+ else
+ defrepr = PyObject_Repr(dd->default_factory);
+ Py_ReprLeave(dd->default_factory);
+ }
+ if (defrepr == NULL) {
+ Py_DECREF(baserepr);
+ return NULL;
+ }
+ result = PyUnicode_FromFormat("defaultdict(%U, %U)",
+ defrepr, baserepr);
+ Py_DECREF(defrepr);
+ Py_DECREF(baserepr);
+ return result;
}
static int
defdict_traverse(PyObject *self, visitproc visit, void *arg)
{
- Py_VISIT(((defdictobject *)self)->default_factory);
- return PyDict_Type.tp_traverse(self, visit, arg);
+ Py_VISIT(((defdictobject *)self)->default_factory);
+ return PyDict_Type.tp_traverse(self, visit, arg);
}
static int
defdict_tp_clear(defdictobject *dd)
{
- Py_CLEAR(dd->default_factory);
- return PyDict_Type.tp_clear((PyObject *)dd);
+ Py_CLEAR(dd->default_factory);
+ return PyDict_Type.tp_clear((PyObject *)dd);
}
static int
defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- defdictobject *dd = (defdictobject *)self;
- PyObject *olddefault = dd->default_factory;
- PyObject *newdefault = NULL;
- PyObject *newargs;
- int result;
- if (args == NULL || !PyTuple_Check(args))
- newargs = PyTuple_New(0);
- else {
- Py_ssize_t n = PyTuple_GET_SIZE(args);
- if (n > 0) {
- newdefault = PyTuple_GET_ITEM(args, 0);
- if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be callable");
- return -1;
- }
- }
- newargs = PySequence_GetSlice(args, 1, n);
- }
- if (newargs == NULL)
- return -1;
- Py_XINCREF(newdefault);
- dd->default_factory = newdefault;
- result = PyDict_Type.tp_init(self, newargs, kwds);
- Py_DECREF(newargs);
- Py_XDECREF(olddefault);
- return result;
+ defdictobject *dd = (defdictobject *)self;
+ PyObject *olddefault = dd->default_factory;
+ PyObject *newdefault = NULL;
+ PyObject *newargs;
+ int result;
+ if (args == NULL || !PyTuple_Check(args))
+ newargs = PyTuple_New(0);
+ else {
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+ if (n > 0) {
+ newdefault = PyTuple_GET_ITEM(args, 0);
+ if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be callable");
+ return -1;
+ }
+ }
+ newargs = PySequence_GetSlice(args, 1, n);
+ }
+ if (newargs == NULL)
+ return -1;
+ Py_XINCREF(newdefault);
+ dd->default_factory = newdefault;
+ result = PyDict_Type.tp_init(self, newargs, kwds);
+ Py_DECREF(newargs);
+ Py_XDECREF(olddefault);
+ return result;
}
PyDoc_STRVAR(defdict_doc,
@@ -1475,47 +1475,47 @@ A defaultdict compares equal to a dict with the same items.\n\
#define DEFERRED_ADDRESS(ADDR) 0
static PyTypeObject defdict_type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "collections.defaultdict", /* tp_name */
- sizeof(defdictobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)defdict_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)defdict_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- /* tp_flags */
- defdict_doc, /* tp_doc */
- defdict_traverse, /* tp_traverse */
- (inquiry)defdict_tp_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset*/
- 0, /* tp_iter */
- 0, /* tp_iternext */
- defdict_methods, /* tp_methods */
- defdict_members, /* tp_members */
- 0, /* tp_getset */
- DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- defdict_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- 0, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "collections.defaultdict", /* tp_name */
+ sizeof(defdictobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)defdict_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)defdict_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ /* tp_flags */
+ defdict_doc, /* tp_doc */
+ defdict_traverse, /* tp_traverse */
+ (inquiry)defdict_tp_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset*/
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ defdict_methods, /* tp_methods */
+ defdict_members, /* tp_members */
+ 0, /* tp_getset */
+ DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ defdict_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ 0, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* module level code ********************************************************/
@@ -1528,42 +1528,42 @@ PyDoc_STRVAR(module_doc,
static struct PyModuleDef _collectionsmodule = {
- PyModuleDef_HEAD_INIT,
- "_collections",
- module_doc,
- -1,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_collections",
+ module_doc,
+ -1,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__collections(void)
{
- PyObject *m;
+ PyObject *m;
- m = PyModule_Create(&_collectionsmodule);
- if (m == NULL)
- return NULL;
+ m = PyModule_Create(&_collectionsmodule);
+ if (m == NULL)
+ return NULL;
- if (PyType_Ready(&deque_type) < 0)
- return NULL;
- Py_INCREF(&deque_type);
- PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
+ if (PyType_Ready(&deque_type) < 0)
+ return NULL;
+ Py_INCREF(&deque_type);
+ PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
- defdict_type.tp_base = &PyDict_Type;
- if (PyType_Ready(&defdict_type) < 0)
- return NULL;
- Py_INCREF(&defdict_type);
- PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
+ defdict_type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&defdict_type) < 0)
+ return NULL;
+ Py_INCREF(&defdict_type);
+ PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
- if (PyType_Ready(&dequeiter_type) < 0)
- return NULL;
+ if (PyType_Ready(&dequeiter_type) < 0)
+ return NULL;
- if (PyType_Ready(&dequereviter_type) < 0)
- return NULL;
+ if (PyType_Ready(&dequereviter_type) < 0)
+ return NULL;
- return m;
+ return m;
}
diff --git a/Modules/_csv.c b/Modules/_csv.c
index 1fbba41..26d4cf0 100644
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -18,65 +18,65 @@ module instead.
#include "structmember.h"
#define IS_BASESTRING(o) \
- PyUnicode_Check(o)
+ PyUnicode_Check(o)
-static PyObject *error_obj; /* CSV exception */
+static PyObject *error_obj; /* CSV exception */
static PyObject *dialects; /* Dialect registry */
-static long field_limit = 128 * 1024; /* max parsed field size */
+static long field_limit = 128 * 1024; /* max parsed field size */
typedef enum {
- START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
- IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
- EAT_CRNL
+ START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
+ IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
+ EAT_CRNL
} ParserState;
typedef enum {
- QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE
+ QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE
} QuoteStyle;
typedef struct {
- QuoteStyle style;
- char *name;
+ QuoteStyle style;
+ char *name;
} StyleDesc;
static StyleDesc quote_styles[] = {
- { QUOTE_MINIMAL, "QUOTE_MINIMAL" },
- { QUOTE_ALL, "QUOTE_ALL" },
- { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" },
- { QUOTE_NONE, "QUOTE_NONE" },
- { 0 }
+ { QUOTE_MINIMAL, "QUOTE_MINIMAL" },
+ { QUOTE_ALL, "QUOTE_ALL" },
+ { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" },
+ { QUOTE_NONE, "QUOTE_NONE" },
+ { 0 }
};
typedef struct {
- PyObject_HEAD
+ PyObject_HEAD
- int doublequote; /* is " represented by ""? */
- Py_UNICODE delimiter; /* field separator */
- Py_UNICODE quotechar; /* quote character */
- Py_UNICODE escapechar; /* escape character */
- int skipinitialspace; /* ignore spaces following delimiter? */
- PyObject *lineterminator; /* string to write between records */
- int quoting; /* style of quoting to write */
+ int doublequote; /* is " represented by ""? */
+ Py_UNICODE delimiter; /* field separator */
+ Py_UNICODE quotechar; /* quote character */
+ Py_UNICODE escapechar; /* escape character */
+ int skipinitialspace; /* ignore spaces following delimiter? */
+ PyObject *lineterminator; /* string to write between records */
+ int quoting; /* style of quoting to write */
- int strict; /* raise exception on bad CSV */
+ int strict; /* raise exception on bad CSV */
} DialectObj;
static PyTypeObject Dialect_Type;
typedef struct {
- PyObject_HEAD
+ PyObject_HEAD
- PyObject *input_iter; /* iterate over this for input lines */
+ PyObject *input_iter; /* iterate over this for input lines */
- DialectObj *dialect; /* parsing dialect */
+ DialectObj *dialect; /* parsing dialect */
- PyObject *fields; /* field list for current record */
- ParserState state; /* current CSV parse state */
- Py_UNICODE *field; /* build current field in here */
- int field_size; /* size of allocated buffer */
- Py_ssize_t field_len; /* length of current field */
- int numeric_field; /* treat field as numeric */
- unsigned long line_num; /* Source-file line number */
+ PyObject *fields; /* field list for current record */
+ ParserState state; /* current CSV parse state */
+ Py_UNICODE *field; /* build current field in here */
+ int field_size; /* size of allocated buffer */
+ Py_ssize_t field_len; /* length of current field */
+ int numeric_field; /* treat field as numeric */
+ unsigned long line_num; /* Source-file line number */
} ReaderObj;
static PyTypeObject Reader_Type;
@@ -84,16 +84,16 @@ static PyTypeObject Reader_Type;
#define ReaderObject_Check(v) (Py_TYPE(v) == &Reader_Type)
typedef struct {
- PyObject_HEAD
+ PyObject_HEAD
- PyObject *writeline; /* write output lines to this file */
+ PyObject *writeline; /* write output lines to this file */
- DialectObj *dialect; /* parsing dialect */
+ DialectObj *dialect; /* parsing dialect */
- Py_UNICODE *rec; /* buffer for parser.join */
- int rec_size; /* size of allocated record */
- Py_ssize_t rec_len; /* length of record */
- int num_fields; /* number of fields in record */
+ Py_UNICODE *rec; /* buffer for parser.join */
+ int rec_size; /* size of allocated record */
+ Py_ssize_t rec_len; /* length of record */
+ int num_fields; /* number of fields in record */
} WriterObj;
static PyTypeObject Writer_Type;
@@ -105,375 +105,375 @@ static PyTypeObject Writer_Type;
static PyObject *
get_dialect_from_registry(PyObject * name_obj)
{
- PyObject *dialect_obj;
-
- dialect_obj = PyDict_GetItem(dialects, name_obj);
- if (dialect_obj == NULL) {
- if (!PyErr_Occurred())
- PyErr_Format(error_obj, "unknown dialect");
- }
- else
- Py_INCREF(dialect_obj);
- return dialect_obj;
+ PyObject *dialect_obj;
+
+ dialect_obj = PyDict_GetItem(dialects, name_obj);
+ if (dialect_obj == NULL) {
+ if (!PyErr_Occurred())
+ PyErr_Format(error_obj, "unknown dialect");
+ }
+ else
+ Py_INCREF(dialect_obj);
+ return dialect_obj;
}
static PyObject *
get_string(PyObject *str)
{
- Py_XINCREF(str);
- return str;
+ Py_XINCREF(str);
+ return str;
}
static PyObject *
get_nullchar_as_None(Py_UNICODE c)
{
- if (c == '\0') {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1);
+ if (c == '\0') {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1);
}
static PyObject *
Dialect_get_lineterminator(DialectObj *self)
{
- return get_string(self->lineterminator);
+ return get_string(self->lineterminator);
}
static PyObject *
Dialect_get_delimiter(DialectObj *self)
{
- return get_nullchar_as_None(self->delimiter);
+ return get_nullchar_as_None(self->delimiter);
}
static PyObject *
Dialect_get_escapechar(DialectObj *self)
{
- return get_nullchar_as_None(self->escapechar);
+ return get_nullchar_as_None(self->escapechar);
}
static PyObject *
Dialect_get_quotechar(DialectObj *self)
{
- return get_nullchar_as_None(self->quotechar);
+ return get_nullchar_as_None(self->quotechar);
}
static PyObject *
Dialect_get_quoting(DialectObj *self)
{
- return PyLong_FromLong(self->quoting);
+ return PyLong_FromLong(self->quoting);
}
static int
_set_bool(const char *name, int *target, PyObject *src, int dflt)
{
- if (src == NULL)
- *target = dflt;
- else
- *target = PyObject_IsTrue(src);
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else
+ *target = PyObject_IsTrue(src);
+ return 0;
}
static int
_set_int(const char *name, int *target, PyObject *src, int dflt)
{
- if (src == NULL)
- *target = dflt;
- else {
- long value;
- if (!PyLong_CheckExact(src)) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an integer", name);
- return -1;
- }
- value = PyLong_AsLong(src);
- if (value == -1 && PyErr_Occurred())
- return -1;
+ if (src == NULL)
+ *target = dflt;
+ else {
+ long value;
+ if (!PyLong_CheckExact(src)) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an integer", name);
+ return -1;
+ }
+ value = PyLong_AsLong(src);
+ if (value == -1 && PyErr_Occurred())
+ return -1;
#if SIZEOF_LONG > SIZEOF_INT
- if (value > INT_MAX || value < INT_MIN) {
- PyErr_Format(PyExc_ValueError,
- "integer out of range for \"%s\"", name);
- return -1;
- }
+ if (value > INT_MAX || value < INT_MIN) {
+ PyErr_Format(PyExc_ValueError,
+ "integer out of range for \"%s\"", name);
+ return -1;
+ }
#endif
- *target = (int)value;
- }
- return 0;
+ *target = (int)value;
+ }
+ return 0;
}
static int
_set_char(const char *name, Py_UNICODE *target, PyObject *src, Py_UNICODE dflt)
{
- if (src == NULL)
- *target = dflt;
- else {
- *target = '\0';
- if (src != Py_None) {
- Py_UNICODE *buf;
- Py_ssize_t len;
- buf = PyUnicode_AsUnicode(src);
- len = PyUnicode_GetSize(src);
- if (buf == NULL || len > 1) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an 1-character string",
- name);
- return -1;
- }
- if (len > 0)
- *target = buf[0];
- }
- }
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else {
+ *target = '\0';
+ if (src != Py_None) {
+ Py_UNICODE *buf;
+ Py_ssize_t len;
+ buf = PyUnicode_AsUnicode(src);
+ len = PyUnicode_GetSize(src);
+ if (buf == NULL || len > 1) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an 1-character string",
+ name);
+ return -1;
+ }
+ if (len > 0)
+ *target = buf[0];
+ }
+ }
+ return 0;
}
static int
_set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
{
- if (src == NULL)
- *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL);
- else {
- if (src == Py_None)
- *target = NULL;
- else if (!IS_BASESTRING(src)) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be a string", name);
- return -1;
- }
- else {
- Py_XDECREF(*target);
- Py_INCREF(src);
- *target = src;
- }
- }
- return 0;
+ if (src == NULL)
+ *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL);
+ else {
+ if (src == Py_None)
+ *target = NULL;
+ else if (!IS_BASESTRING(src)) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be a string", name);
+ return -1;
+ }
+ else {
+ Py_XDECREF(*target);
+ Py_INCREF(src);
+ *target = src;
+ }
+ }
+ return 0;
}
static int
dialect_check_quoting(int quoting)
{
- StyleDesc *qs = quote_styles;
-
- for (qs = quote_styles; qs->name; qs++) {
- if (qs->style == quoting)
- return 0;
- }
- PyErr_Format(PyExc_TypeError, "bad \"quoting\" value");
- return -1;
+ StyleDesc *qs = quote_styles;
+
+ for (qs = quote_styles; qs->name; qs++) {
+ if (qs->style == quoting)
+ return 0;
+ }
+ PyErr_Format(PyExc_TypeError, "bad \"quoting\" value");
+ return -1;
}
#define D_OFF(x) offsetof(DialectObj, x)
static struct PyMemberDef Dialect_memberlist[] = {
- { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY },
- { "doublequote", T_INT, D_OFF(doublequote), READONLY },
- { "strict", T_INT, D_OFF(strict), READONLY },
- { NULL }
+ { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY },
+ { "doublequote", T_INT, D_OFF(doublequote), READONLY },
+ { "strict", T_INT, D_OFF(strict), READONLY },
+ { NULL }
};
static PyGetSetDef Dialect_getsetlist[] = {
- { "delimiter", (getter)Dialect_get_delimiter},
- { "escapechar", (getter)Dialect_get_escapechar},
- { "lineterminator", (getter)Dialect_get_lineterminator},
- { "quotechar", (getter)Dialect_get_quotechar},
- { "quoting", (getter)Dialect_get_quoting},
- {NULL},
+ { "delimiter", (getter)Dialect_get_delimiter},
+ { "escapechar", (getter)Dialect_get_escapechar},
+ { "lineterminator", (getter)Dialect_get_lineterminator},
+ { "quotechar", (getter)Dialect_get_quotechar},
+ { "quoting", (getter)Dialect_get_quoting},
+ {NULL},
};
static void
Dialect_dealloc(DialectObj *self)
{
- Py_XDECREF(self->lineterminator);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_XDECREF(self->lineterminator);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static char *dialect_kws[] = {
- "dialect",
- "delimiter",
- "doublequote",
- "escapechar",
- "lineterminator",
- "quotechar",
- "quoting",
- "skipinitialspace",
- "strict",
- NULL
+ "dialect",
+ "delimiter",
+ "doublequote",
+ "escapechar",
+ "lineterminator",
+ "quotechar",
+ "quoting",
+ "skipinitialspace",
+ "strict",
+ NULL
};
static PyObject *
dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
- DialectObj *self;
- PyObject *ret = NULL;
- PyObject *dialect = NULL;
- PyObject *delimiter = NULL;
- PyObject *doublequote = NULL;
- PyObject *escapechar = NULL;
- PyObject *lineterminator = NULL;
- PyObject *quotechar = NULL;
- PyObject *quoting = NULL;
- PyObject *skipinitialspace = NULL;
- PyObject *strict = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs,
- "|OOOOOOOOO", dialect_kws,
- &dialect,
- &delimiter,
- &doublequote,
- &escapechar,
- &lineterminator,
- &quotechar,
- &quoting,
- &skipinitialspace,
- &strict))
- return NULL;
-
- if (dialect != NULL) {
- if (IS_BASESTRING(dialect)) {
- dialect = get_dialect_from_registry(dialect);
- if (dialect == NULL)
- return NULL;
- }
- else
- Py_INCREF(dialect);
- /* Can we reuse this instance? */
- if (PyObject_TypeCheck(dialect, &Dialect_Type) &&
- delimiter == 0 &&
- doublequote == 0 &&
- escapechar == 0 &&
- lineterminator == 0 &&
- quotechar == 0 &&
- quoting == 0 &&
- skipinitialspace == 0 &&
- strict == 0)
- return dialect;
- }
-
- self = (DialectObj *)type->tp_alloc(type, 0);
- if (self == NULL) {
- Py_XDECREF(dialect);
- return NULL;
- }
- self->lineterminator = NULL;
-
- Py_XINCREF(delimiter);
- Py_XINCREF(doublequote);
- Py_XINCREF(escapechar);
- Py_XINCREF(lineterminator);
- Py_XINCREF(quotechar);
- Py_XINCREF(quoting);
- Py_XINCREF(skipinitialspace);
- Py_XINCREF(strict);
- if (dialect != NULL) {
+ DialectObj *self;
+ PyObject *ret = NULL;
+ PyObject *dialect = NULL;
+ PyObject *delimiter = NULL;
+ PyObject *doublequote = NULL;
+ PyObject *escapechar = NULL;
+ PyObject *lineterminator = NULL;
+ PyObject *quotechar = NULL;
+ PyObject *quoting = NULL;
+ PyObject *skipinitialspace = NULL;
+ PyObject *strict = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs,
+ "|OOOOOOOOO", dialect_kws,
+ &dialect,
+ &delimiter,
+ &doublequote,
+ &escapechar,
+ &lineterminator,
+ &quotechar,
+ &quoting,
+ &skipinitialspace,
+ &strict))
+ return NULL;
+
+ if (dialect != NULL) {
+ if (IS_BASESTRING(dialect)) {
+ dialect = get_dialect_from_registry(dialect);
+ if (dialect == NULL)
+ return NULL;
+ }
+ else
+ Py_INCREF(dialect);
+ /* Can we reuse this instance? */
+ if (PyObject_TypeCheck(dialect, &Dialect_Type) &&
+ delimiter == 0 &&
+ doublequote == 0 &&
+ escapechar == 0 &&
+ lineterminator == 0 &&
+ quotechar == 0 &&
+ quoting == 0 &&
+ skipinitialspace == 0 &&
+ strict == 0)
+ return dialect;
+ }
+
+ self = (DialectObj *)type->tp_alloc(type, 0);
+ if (self == NULL) {
+ Py_XDECREF(dialect);
+ return NULL;
+ }
+ self->lineterminator = NULL;
+
+ Py_XINCREF(delimiter);
+ Py_XINCREF(doublequote);
+ Py_XINCREF(escapechar);
+ Py_XINCREF(lineterminator);
+ Py_XINCREF(quotechar);
+ Py_XINCREF(quoting);
+ Py_XINCREF(skipinitialspace);
+ Py_XINCREF(strict);
+ if (dialect != NULL) {
#define DIALECT_GETATTR(v, n) \
- if (v == NULL) \
- v = PyObject_GetAttrString(dialect, n)
- DIALECT_GETATTR(delimiter, "delimiter");
- DIALECT_GETATTR(doublequote, "doublequote");
- DIALECT_GETATTR(escapechar, "escapechar");
- DIALECT_GETATTR(lineterminator, "lineterminator");
- DIALECT_GETATTR(quotechar, "quotechar");
- DIALECT_GETATTR(quoting, "quoting");
- DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
- DIALECT_GETATTR(strict, "strict");
- PyErr_Clear();
- }
-
- /* check types and convert to C values */
+ if (v == NULL) \
+ v = PyObject_GetAttrString(dialect, n)
+ DIALECT_GETATTR(delimiter, "delimiter");
+ DIALECT_GETATTR(doublequote, "doublequote");
+ DIALECT_GETATTR(escapechar, "escapechar");
+ DIALECT_GETATTR(lineterminator, "lineterminator");
+ DIALECT_GETATTR(quotechar, "quotechar");
+ DIALECT_GETATTR(quoting, "quoting");
+ DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
+ DIALECT_GETATTR(strict, "strict");
+ PyErr_Clear();
+ }
+
+ /* check types and convert to C values */
#define DIASET(meth, name, target, src, dflt) \
- if (meth(name, target, src, dflt)) \
- goto err
- DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ',');
- DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1);
- DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0);
- DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n");
- DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"');
- DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL);
- DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0);
- DIASET(_set_bool, "strict", &self->strict, strict, 0);
-
- /* validate options */
- if (dialect_check_quoting(self->quoting))
- goto err;
- if (self->delimiter == 0) {
- PyErr_SetString(PyExc_TypeError, "delimiter must be set");
- goto err;
- }
- if (quotechar == Py_None && quoting == NULL)
- self->quoting = QUOTE_NONE;
- if (self->quoting != QUOTE_NONE && self->quotechar == 0) {
- PyErr_SetString(PyExc_TypeError,
- "quotechar must be set if quoting enabled");
- goto err;
- }
- if (self->lineterminator == 0) {
- PyErr_SetString(PyExc_TypeError, "lineterminator must be set");
- goto err;
- }
-
- ret = (PyObject *)self;
- Py_INCREF(self);
+ if (meth(name, target, src, dflt)) \
+ goto err
+ DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ',');
+ DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1);
+ DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0);
+ DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n");
+ DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"');
+ DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL);
+ DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0);
+ DIASET(_set_bool, "strict", &self->strict, strict, 0);
+
+ /* validate options */
+ if (dialect_check_quoting(self->quoting))
+ goto err;
+ if (self->delimiter == 0) {
+ PyErr_SetString(PyExc_TypeError, "delimiter must be set");
+ goto err;
+ }
+ if (quotechar == Py_None && quoting == NULL)
+ self->quoting = QUOTE_NONE;
+ if (self->quoting != QUOTE_NONE && self->quotechar == 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "quotechar must be set if quoting enabled");
+ goto err;
+ }
+ if (self->lineterminator == 0) {
+ PyErr_SetString(PyExc_TypeError, "lineterminator must be set");
+ goto err;
+ }
+
+ ret = (PyObject *)self;
+ Py_INCREF(self);
err:
- Py_XDECREF(self);
- Py_XDECREF(dialect);
- Py_XDECREF(delimiter);
- Py_XDECREF(doublequote);
- Py_XDECREF(escapechar);
- Py_XDECREF(lineterminator);
- Py_XDECREF(quotechar);
- Py_XDECREF(quoting);
- Py_XDECREF(skipinitialspace);
- Py_XDECREF(strict);
- return ret;
+ Py_XDECREF(self);
+ Py_XDECREF(dialect);
+ Py_XDECREF(delimiter);
+ Py_XDECREF(doublequote);
+ Py_XDECREF(escapechar);
+ Py_XDECREF(lineterminator);
+ Py_XDECREF(quotechar);
+ Py_XDECREF(quoting);
+ Py_XDECREF(skipinitialspace);
+ Py_XDECREF(strict);
+ return ret;
}
-PyDoc_STRVAR(Dialect_Type_doc,
+PyDoc_STRVAR(Dialect_Type_doc,
"CSV dialect\n"
"\n"
"The Dialect type records CSV parsing and generation options.\n");
static PyTypeObject Dialect_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_csv.Dialect", /* tp_name */
- sizeof(DialectObj), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)Dialect_dealloc, /* tp_dealloc */
- (printfunc)0, /* tp_print */
- (getattrfunc)0, /* tp_getattr */
- (setattrfunc)0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)0, /* tp_hash */
- (ternaryfunc)0, /* tp_call */
- (reprfunc)0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- Dialect_Type_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- Dialect_memberlist, /* tp_members */
- Dialect_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- dialect_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_csv.Dialect", /* tp_name */
+ sizeof(DialectObj), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)Dialect_dealloc, /* tp_dealloc */
+ (printfunc)0, /* tp_print */
+ (getattrfunc)0, /* tp_getattr */
+ (setattrfunc)0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)0, /* tp_hash */
+ (ternaryfunc)0, /* tp_call */
+ (reprfunc)0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ Dialect_Type_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ Dialect_memberlist, /* tp_members */
+ Dialect_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ dialect_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -483,15 +483,15 @@ static PyTypeObject Dialect_Type = {
static PyObject *
_call_dialect(PyObject *dialect_inst, PyObject *kwargs)
{
- PyObject *ctor_args;
- PyObject *dialect;
-
- ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst);
- if (ctor_args == NULL)
- return NULL;
- dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs);
- Py_DECREF(ctor_args);
- return dialect;
+ PyObject *ctor_args;
+ PyObject *dialect;
+
+ ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst);
+ if (ctor_args == NULL)
+ return NULL;
+ dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs);
+ Py_DECREF(ctor_args);
+ return dialect;
}
/*
@@ -500,339 +500,339 @@ _call_dialect(PyObject *dialect_inst, PyObject *kwargs)
static int
parse_save_field(ReaderObj *self)
{
- PyObject *field;
-
- field = PyUnicode_FromUnicode(self->field, self->field_len);
- if (field == NULL)
- return -1;
- self->field_len = 0;
- if (self->numeric_field) {
- PyObject *tmp;
-
- self->numeric_field = 0;
- tmp = PyNumber_Float(field);
- if (tmp == NULL) {
- Py_DECREF(field);
- return -1;
- }
- Py_DECREF(field);
- field = tmp;
- }
- PyList_Append(self->fields, field);
- Py_DECREF(field);
- return 0;
+ PyObject *field;
+
+ field = PyUnicode_FromUnicode(self->field, self->field_len);
+ if (field == NULL)
+ return -1;
+ self->field_len = 0;
+ if (self->numeric_field) {
+ PyObject *tmp;
+
+ self->numeric_field = 0;
+ tmp = PyNumber_Float(field);
+ if (tmp == NULL) {
+ Py_DECREF(field);
+ return -1;
+ }
+ Py_DECREF(field);
+ field = tmp;
+ }
+ PyList_Append(self->fields, field);
+ Py_DECREF(field);
+ return 0;
}
static int
parse_grow_buff(ReaderObj *self)
{
- if (self->field_size == 0) {
- self->field_size = 4096;
- if (self->field != NULL)
- PyMem_Free(self->field);
- self->field = PyMem_New(Py_UNICODE, self->field_size);
- }
- else {
- if (self->field_size > INT_MAX / 2) {
- PyErr_NoMemory();
- return 0;
- }
- self->field_size *= 2;
- self->field = PyMem_Resize(self->field, Py_UNICODE,
- self->field_size);
- }
- if (self->field == NULL) {
- PyErr_NoMemory();
- return 0;
- }
- return 1;
+ if (self->field_size == 0) {
+ self->field_size = 4096;
+ if (self->field != NULL)
+ PyMem_Free(self->field);
+ self->field = PyMem_New(Py_UNICODE, self->field_size);
+ }
+ else {
+ if (self->field_size > INT_MAX / 2) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ self->field_size *= 2;
+ self->field = PyMem_Resize(self->field, Py_UNICODE,
+ self->field_size);
+ }
+ if (self->field == NULL) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ return 1;
}
static int
parse_add_char(ReaderObj *self, Py_UNICODE c)
{
- if (self->field_len >= field_limit) {
- PyErr_Format(error_obj, "field larger than field limit (%ld)",
- field_limit);
- return -1;
- }
- if (self->field_len == self->field_size && !parse_grow_buff(self))
- return -1;
- self->field[self->field_len++] = c;
- return 0;
+ if (self->field_len >= field_limit) {
+ PyErr_Format(error_obj, "field larger than field limit (%ld)",
+ field_limit);
+ return -1;
+ }
+ if (self->field_len == self->field_size && !parse_grow_buff(self))
+ return -1;
+ self->field[self->field_len++] = c;
+ return 0;
}
static int
parse_process_char(ReaderObj *self, Py_UNICODE c)
{
- DialectObj *dialect = self->dialect;
-
- switch (self->state) {
- case START_RECORD:
- /* start of record */
- if (c == '\0')
- /* empty line - return [] */
- break;
- else if (c == '\n' || c == '\r') {
- self->state = EAT_CRNL;
- break;
- }
- /* normal character - handle as START_FIELD */
- self->state = START_FIELD;
- /* fallthru */
- case START_FIELD:
- /* expecting field */
- if (c == '\n' || c == '\r' || c == '\0') {
- /* save empty field - return [fields] */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
- }
- else if (c == dialect->quotechar &&
- dialect->quoting != QUOTE_NONE) {
- /* start quoted field */
- self->state = IN_QUOTED_FIELD;
- }
- else if (c == dialect->escapechar) {
- /* possible escaped character */
- self->state = ESCAPED_CHAR;
- }
- else if (c == ' ' && dialect->skipinitialspace)
- /* ignore space at start of field */
- ;
- else if (c == dialect->delimiter) {
- /* save empty field */
- if (parse_save_field(self) < 0)
- return -1;
- }
- else {
- /* begin new unquoted field */
- if (dialect->quoting == QUOTE_NONNUMERIC)
- self->numeric_field = 1;
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_FIELD;
- }
- break;
-
- case ESCAPED_CHAR:
- if (c == '\0')
- c = '\n';
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_FIELD;
- break;
-
- case IN_FIELD:
- /* in unquoted field */
- if (c == '\n' || c == '\r' || c == '\0') {
- /* end of line - return [fields] */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
- }
- else if (c == dialect->escapechar) {
- /* possible escaped character */
- self->state = ESCAPED_CHAR;
- }
- else if (c == dialect->delimiter) {
- /* save field - wait for new field */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = START_FIELD;
- }
- else {
- /* normal character - save in field */
- if (parse_add_char(self, c) < 0)
- return -1;
- }
- break;
-
- case IN_QUOTED_FIELD:
- /* in quoted field */
- if (c == '\0')
- ;
- else if (c == dialect->escapechar) {
- /* Possible escape character */
- self->state = ESCAPE_IN_QUOTED_FIELD;
- }
- else if (c == dialect->quotechar &&
- dialect->quoting != QUOTE_NONE) {
- if (dialect->doublequote) {
- /* doublequote; " represented by "" */
- self->state = QUOTE_IN_QUOTED_FIELD;
- }
- else {
- /* end of quote part of field */
- self->state = IN_FIELD;
- }
- }
- else {
- /* normal character - save in field */
- if (parse_add_char(self, c) < 0)
- return -1;
- }
- break;
-
- case ESCAPE_IN_QUOTED_FIELD:
- if (c == '\0')
- c = '\n';
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_QUOTED_FIELD;
- break;
-
- case QUOTE_IN_QUOTED_FIELD:
- /* doublequote - seen a quote in an quoted field */
- if (dialect->quoting != QUOTE_NONE &&
- c == dialect->quotechar) {
- /* save "" as " */
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_QUOTED_FIELD;
- }
- else if (c == dialect->delimiter) {
- /* save field - wait for new field */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = START_FIELD;
- }
- else if (c == '\n' || c == '\r' || c == '\0') {
- /* end of line - return [fields] */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
- }
- else if (!dialect->strict) {
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_FIELD;
- }
- else {
- /* illegal */
- PyErr_Format(error_obj, "'%c' expected after '%c'",
- dialect->delimiter,
- dialect->quotechar);
- return -1;
- }
- break;
-
- case EAT_CRNL:
- if (c == '\n' || c == '\r')
- ;
- else if (c == '\0')
- self->state = START_RECORD;
- else {
- PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?");
- return -1;
- }
- break;
-
- }
- return 0;
+ DialectObj *dialect = self->dialect;
+
+ switch (self->state) {
+ case START_RECORD:
+ /* start of record */
+ if (c == '\0')
+ /* empty line - return [] */
+ break;
+ else if (c == '\n' || c == '\r') {
+ self->state = EAT_CRNL;
+ break;
+ }
+ /* normal character - handle as START_FIELD */
+ self->state = START_FIELD;
+ /* fallthru */
+ case START_FIELD:
+ /* expecting field */
+ if (c == '\n' || c == '\r' || c == '\0') {
+ /* save empty field - return [fields] */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
+ }
+ else if (c == dialect->quotechar &&
+ dialect->quoting != QUOTE_NONE) {
+ /* start quoted field */
+ self->state = IN_QUOTED_FIELD;
+ }
+ else if (c == dialect->escapechar) {
+ /* possible escaped character */
+ self->state = ESCAPED_CHAR;
+ }
+ else if (c == ' ' && dialect->skipinitialspace)
+ /* ignore space at start of field */
+ ;
+ else if (c == dialect->delimiter) {
+ /* save empty field */
+ if (parse_save_field(self) < 0)
+ return -1;
+ }
+ else {
+ /* begin new unquoted field */
+ if (dialect->quoting == QUOTE_NONNUMERIC)
+ self->numeric_field = 1;
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_FIELD;
+ }
+ break;
+
+ case ESCAPED_CHAR:
+ if (c == '\0')
+ c = '\n';
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_FIELD;
+ break;
+
+ case IN_FIELD:
+ /* in unquoted field */
+ if (c == '\n' || c == '\r' || c == '\0') {
+ /* end of line - return [fields] */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
+ }
+ else if (c == dialect->escapechar) {
+ /* possible escaped character */
+ self->state = ESCAPED_CHAR;
+ }
+ else if (c == dialect->delimiter) {
+ /* save field - wait for new field */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = START_FIELD;
+ }
+ else {
+ /* normal character - save in field */
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ }
+ break;
+
+ case IN_QUOTED_FIELD:
+ /* in quoted field */
+ if (c == '\0')
+ ;
+ else if (c == dialect->escapechar) {
+ /* Possible escape character */
+ self->state = ESCAPE_IN_QUOTED_FIELD;
+ }
+ else if (c == dialect->quotechar &&
+ dialect->quoting != QUOTE_NONE) {
+ if (dialect->doublequote) {
+ /* doublequote; " represented by "" */
+ self->state = QUOTE_IN_QUOTED_FIELD;
+ }
+ else {
+ /* end of quote part of field */
+ self->state = IN_FIELD;
+ }
+ }
+ else {
+ /* normal character - save in field */
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ }
+ break;
+
+ case ESCAPE_IN_QUOTED_FIELD:
+ if (c == '\0')
+ c = '\n';
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_QUOTED_FIELD;
+ break;
+
+ case QUOTE_IN_QUOTED_FIELD:
+ /* doublequote - seen a quote in an quoted field */
+ if (dialect->quoting != QUOTE_NONE &&
+ c == dialect->quotechar) {
+ /* save "" as " */
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_QUOTED_FIELD;
+ }
+ else if (c == dialect->delimiter) {
+ /* save field - wait for new field */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = START_FIELD;
+ }
+ else if (c == '\n' || c == '\r' || c == '\0') {
+ /* end of line - return [fields] */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
+ }
+ else if (!dialect->strict) {
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_FIELD;
+ }
+ else {
+ /* illegal */
+ PyErr_Format(error_obj, "'%c' expected after '%c'",
+ dialect->delimiter,
+ dialect->quotechar);
+ return -1;
+ }
+ break;
+
+ case EAT_CRNL:
+ if (c == '\n' || c == '\r')
+ ;
+ else if (c == '\0')
+ self->state = START_RECORD;
+ else {
+ PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?");
+ return -1;
+ }
+ break;
+
+ }
+ return 0;
}
static int
parse_reset(ReaderObj *self)
{
- Py_XDECREF(self->fields);
- self->fields = PyList_New(0);
- if (self->fields == NULL)
- return -1;
- self->field_len = 0;
- self->state = START_RECORD;
- self->numeric_field = 0;
- return 0;
+ Py_XDECREF(self->fields);
+ self->fields = PyList_New(0);
+ if (self->fields == NULL)
+ return -1;
+ self->field_len = 0;
+ self->state = START_RECORD;
+ self->numeric_field = 0;
+ return 0;
}
static PyObject *
Reader_iternext(ReaderObj *self)
{
- PyObject *lineobj;
- PyObject *fields = NULL;
- Py_UNICODE *line, c;
- Py_ssize_t linelen;
-
- if (parse_reset(self) < 0)
- return NULL;
- do {
- lineobj = PyIter_Next(self->input_iter);
- if (lineobj == NULL) {
- /* End of input OR exception */
- if (!PyErr_Occurred() && self->field_len != 0)
- PyErr_Format(error_obj,
- "newline inside string");
- return NULL;
- }
- if (!PyUnicode_Check(lineobj)) {
- PyErr_Format(error_obj,
- "iterator should return strings, "
- "not %.200s "
- "(did you open the file in text mode?)",
- lineobj->ob_type->tp_name
- );
- Py_DECREF(lineobj);
- return NULL;
- }
- ++self->line_num;
- line = PyUnicode_AsUnicode(lineobj);
- linelen = PyUnicode_GetSize(lineobj);
- if (line == NULL || linelen < 0) {
- Py_DECREF(lineobj);
- return NULL;
- }
- while (linelen--) {
- c = *line++;
- if (c == '\0') {
- Py_DECREF(lineobj);
- PyErr_Format(error_obj,
- "line contains NULL byte");
- goto err;
- }
- if (parse_process_char(self, c) < 0) {
- Py_DECREF(lineobj);
- goto err;
- }
- }
+ PyObject *lineobj;
+ PyObject *fields = NULL;
+ Py_UNICODE *line, c;
+ Py_ssize_t linelen;
+
+ if (parse_reset(self) < 0)
+ return NULL;
+ do {
+ lineobj = PyIter_Next(self->input_iter);
+ if (lineobj == NULL) {
+ /* End of input OR exception */
+ if (!PyErr_Occurred() && self->field_len != 0)
+ PyErr_Format(error_obj,
+ "newline inside string");
+ return NULL;
+ }
+ if (!PyUnicode_Check(lineobj)) {
+ PyErr_Format(error_obj,
+ "iterator should return strings, "
+ "not %.200s "
+ "(did you open the file in text mode?)",
+ lineobj->ob_type->tp_name
+ );
+ Py_DECREF(lineobj);
+ return NULL;
+ }
+ ++self->line_num;
+ line = PyUnicode_AsUnicode(lineobj);
+ linelen = PyUnicode_GetSize(lineobj);
+ if (line == NULL || linelen < 0) {
+ Py_DECREF(lineobj);
+ return NULL;
+ }
+ while (linelen--) {
+ c = *line++;
+ if (c == '\0') {
Py_DECREF(lineobj);
- if (parse_process_char(self, 0) < 0)
- goto err;
- } while (self->state != START_RECORD);
+ PyErr_Format(error_obj,
+ "line contains NULL byte");
+ goto err;
+ }
+ if (parse_process_char(self, c) < 0) {
+ Py_DECREF(lineobj);
+ goto err;
+ }
+ }
+ Py_DECREF(lineobj);
+ if (parse_process_char(self, 0) < 0)
+ goto err;
+ } while (self->state != START_RECORD);
- fields = self->fields;
- self->fields = NULL;
+ fields = self->fields;
+ self->fields = NULL;
err:
- return fields;
+ return fields;
}
static void
Reader_dealloc(ReaderObj *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->dialect);
- Py_XDECREF(self->input_iter);
- Py_XDECREF(self->fields);
- if (self->field != NULL)
- PyMem_Free(self->field);
- PyObject_GC_Del(self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->dialect);
+ Py_XDECREF(self->input_iter);
+ Py_XDECREF(self->fields);
+ if (self->field != NULL)
+ PyMem_Free(self->field);
+ PyObject_GC_Del(self);
}
static int
Reader_traverse(ReaderObj *self, visitproc visit, void *arg)
{
- Py_VISIT(self->dialect);
- Py_VISIT(self->input_iter);
- Py_VISIT(self->fields);
- return 0;
+ Py_VISIT(self->dialect);
+ Py_VISIT(self->input_iter);
+ Py_VISIT(self->fields);
+ return 0;
}
static int
Reader_clear(ReaderObj *self)
{
- Py_CLEAR(self->dialect);
- Py_CLEAR(self->input_iter);
- Py_CLEAR(self->fields);
- return 0;
+ Py_CLEAR(self->dialect);
+ Py_CLEAR(self->input_iter);
+ Py_CLEAR(self->fields);
+ return 0;
}
PyDoc_STRVAR(Reader_Type_doc,
@@ -843,93 +843,93 @@ PyDoc_STRVAR(Reader_Type_doc,
);
static struct PyMethodDef Reader_methods[] = {
- { NULL, NULL }
+ { NULL, NULL }
};
#define R_OFF(x) offsetof(ReaderObj, x)
static struct PyMemberDef Reader_memberlist[] = {
- { "dialect", T_OBJECT, R_OFF(dialect), READONLY },
- { "line_num", T_ULONG, R_OFF(line_num), READONLY },
- { NULL }
+ { "dialect", T_OBJECT, R_OFF(dialect), READONLY },
+ { "line_num", T_ULONG, R_OFF(line_num), READONLY },
+ { NULL }
};
static PyTypeObject Reader_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_csv.reader", /*tp_name*/
- sizeof(ReaderObj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)Reader_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- 0, /*tp_reserved*/
- (reprfunc)0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- (hashfunc)0, /*tp_hash*/
- (ternaryfunc)0, /*tp_call*/
- (reprfunc)0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- Reader_Type_doc, /*tp_doc*/
- (traverseproc)Reader_traverse, /*tp_traverse*/
- (inquiry)Reader_clear, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- PyObject_SelfIter, /*tp_iter*/
- (getiterfunc)Reader_iternext, /*tp_iternext*/
- Reader_methods, /*tp_methods*/
- Reader_memberlist, /*tp_members*/
- 0, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_csv.reader", /*tp_name*/
+ sizeof(ReaderObj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)Reader_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ (reprfunc)0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ (hashfunc)0, /*tp_hash*/
+ (ternaryfunc)0, /*tp_call*/
+ (reprfunc)0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ Reader_Type_doc, /*tp_doc*/
+ (traverseproc)Reader_traverse, /*tp_traverse*/
+ (inquiry)Reader_clear, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ PyObject_SelfIter, /*tp_iter*/
+ (getiterfunc)Reader_iternext, /*tp_iternext*/
+ Reader_methods, /*tp_methods*/
+ Reader_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
};
static PyObject *
csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
{
- PyObject * iterator, * dialect = NULL;
- ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type);
-
- if (!self)
- return NULL;
-
- self->dialect = NULL;
- self->fields = NULL;
- self->input_iter = NULL;
- self->field = NULL;
- self->field_size = 0;
- self->line_num = 0;
-
- if (parse_reset(self) < 0) {
- Py_DECREF(self);
- return NULL;
- }
-
- if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) {
- Py_DECREF(self);
- return NULL;
- }
- self->input_iter = PyObject_GetIter(iterator);
- if (self->input_iter == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "argument 1 must be an iterator");
- Py_DECREF(self);
- return NULL;
- }
- self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
- if (self->dialect == NULL) {
- Py_DECREF(self);
- return NULL;
- }
-
- PyObject_GC_Track(self);
- return (PyObject *)self;
+ PyObject * iterator, * dialect = NULL;
+ ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type);
+
+ if (!self)
+ return NULL;
+
+ self->dialect = NULL;
+ self->fields = NULL;
+ self->input_iter = NULL;
+ self->field = NULL;
+ self->field_size = 0;
+ self->line_num = 0;
+
+ if (parse_reset(self) < 0) {
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->input_iter = PyObject_GetIter(iterator);
+ if (self->input_iter == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument 1 must be an iterator");
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
+ if (self->dialect == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ PyObject_GC_Track(self);
+ return (PyObject *)self;
}
/*
@@ -939,8 +939,8 @@ csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
static void
join_reset(WriterObj *self)
{
- self->rec_len = 0;
- self->num_fields = 0;
+ self->rec_len = 0;
+ self->num_fields = 0;
}
#define MEM_INCR 32768
@@ -952,90 +952,90 @@ static int
join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty,
int *quoted, int copy_phase)
{
- DialectObj *dialect = self->dialect;
- int i;
- int rec_len;
- Py_UNICODE *lineterm;
+ DialectObj *dialect = self->dialect;
+ int i;
+ int rec_len;
+ Py_UNICODE *lineterm;
#define ADDCH(c) \
- do {\
- if (copy_phase) \
- self->rec[rec_len] = c;\
- rec_len++;\
- } while(0)
-
- lineterm = PyUnicode_AsUnicode(dialect->lineterminator);
- if (lineterm == NULL)
- return -1;
-
- rec_len = self->rec_len;
-
- /* If this is not the first field we need a field separator */
- if (self->num_fields > 0)
- ADDCH(dialect->delimiter);
-
- /* Handle preceding quote */
- if (copy_phase && *quoted)
- ADDCH(dialect->quotechar);
-
- /* Copy/count field data */
- /* If field is null just pass over */
- for (i = 0; field; i++) {
- Py_UNICODE c = field[i];
- int want_escape = 0;
-
- if (c == '\0')
- break;
-
- if (c == dialect->delimiter ||
- c == dialect->escapechar ||
- c == dialect->quotechar ||
- Py_UNICODE_strchr(lineterm, c)) {
- if (dialect->quoting == QUOTE_NONE)
- want_escape = 1;
- else {
- if (c == dialect->quotechar) {
- if (dialect->doublequote)
- ADDCH(dialect->quotechar);
- else
- want_escape = 1;
- }
- if (!want_escape)
- *quoted = 1;
- }
- if (want_escape) {
- if (!dialect->escapechar) {
- PyErr_Format(error_obj,
- "need to escape, but no escapechar set");
- return -1;
- }
- ADDCH(dialect->escapechar);
- }
- }
- /* Copy field character into record buffer.
- */
- ADDCH(c);
- }
-
- /* If field is empty check if it needs to be quoted.
- */
- if (i == 0 && quote_empty) {
- if (dialect->quoting == QUOTE_NONE) {
- PyErr_Format(error_obj,
- "single empty field record must be quoted");
- return -1;
- }
- else
- *quoted = 1;
- }
-
- if (*quoted) {
- if (copy_phase)
- ADDCH(dialect->quotechar);
- else
- rec_len += 2;
- }
- return rec_len;
+ do {\
+ if (copy_phase) \
+ self->rec[rec_len] = c;\
+ rec_len++;\
+ } while(0)
+
+ lineterm = PyUnicode_AsUnicode(dialect->lineterminator);
+ if (lineterm == NULL)
+ return -1;
+
+ rec_len = self->rec_len;
+
+ /* If this is not the first field we need a field separator */
+ if (self->num_fields > 0)
+ ADDCH(dialect->delimiter);
+
+ /* Handle preceding quote */
+ if (copy_phase && *quoted)
+ ADDCH(dialect->quotechar);
+
+ /* Copy/count field data */
+ /* If field is null just pass over */
+ for (i = 0; field; i++) {
+ Py_UNICODE c = field[i];
+ int want_escape = 0;
+
+ if (c == '\0')
+ break;
+
+ if (c == dialect->delimiter ||
+ c == dialect->escapechar ||
+ c == dialect->quotechar ||
+ Py_UNICODE_strchr(lineterm, c)) {
+ if (dialect->quoting == QUOTE_NONE)
+ want_escape = 1;
+ else {
+ if (c == dialect->quotechar) {
+ if (dialect->doublequote)
+ ADDCH(dialect->quotechar);
+ else
+ want_escape = 1;
+ }
+ if (!want_escape)
+ *quoted = 1;
+ }
+ if (want_escape) {
+ if (!dialect->escapechar) {
+ PyErr_Format(error_obj,
+ "need to escape, but no escapechar set");
+ return -1;
+ }
+ ADDCH(dialect->escapechar);
+ }
+ }
+ /* Copy field character into record buffer.
+ */
+ ADDCH(c);
+ }
+
+ /* If field is empty check if it needs to be quoted.
+ */
+ if (i == 0 && quote_empty) {
+ if (dialect->quoting == QUOTE_NONE) {
+ PyErr_Format(error_obj,
+ "single empty field record must be quoted");
+ return -1;
+ }
+ else
+ *quoted = 1;
+ }
+
+ if (*quoted) {
+ if (copy_phase)
+ ADDCH(dialect->quotechar);
+ else
+ rec_len += 2;
+ }
+ return rec_len;
#undef ADDCH
}
@@ -1043,76 +1043,76 @@ static int
join_check_rec_size(WriterObj *self, int rec_len)
{
- if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) {
- PyErr_NoMemory();
- return 0;
- }
-
- if (rec_len > self->rec_size) {
- if (self->rec_size == 0) {
- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
- if (self->rec != NULL)
- PyMem_Free(self->rec);
- self->rec = PyMem_New(Py_UNICODE, self->rec_size);
- }
- else {
- Py_UNICODE* old_rec = self->rec;
-
- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
- self->rec = PyMem_Resize(self->rec, Py_UNICODE,
- self->rec_size);
- if (self->rec == NULL)
- PyMem_Free(old_rec);
- }
- if (self->rec == NULL) {
- PyErr_NoMemory();
- return 0;
- }
- }
- return 1;
+ if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) {
+ PyErr_NoMemory();
+ return 0;
+ }
+
+ if (rec_len > self->rec_size) {
+ if (self->rec_size == 0) {
+ self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
+ if (self->rec != NULL)
+ PyMem_Free(self->rec);
+ self->rec = PyMem_New(Py_UNICODE, self->rec_size);
+ }
+ else {
+ Py_UNICODE* old_rec = self->rec;
+
+ self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
+ self->rec = PyMem_Resize(self->rec, Py_UNICODE,
+ self->rec_size);
+ if (self->rec == NULL)
+ PyMem_Free(old_rec);
+ }
+ if (self->rec == NULL) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ }
+ return 1;
}
static int
join_append(WriterObj *self, Py_UNICODE *field, int *quoted, int quote_empty)
{
- int rec_len;
+ int rec_len;
- rec_len = join_append_data(self, field, quote_empty, quoted, 0);
- if (rec_len < 0)
- return 0;
+ rec_len = join_append_data(self, field, quote_empty, quoted, 0);
+ if (rec_len < 0)
+ return 0;
- /* grow record buffer if necessary */
- if (!join_check_rec_size(self, rec_len))
- return 0;
+ /* grow record buffer if necessary */
+ if (!join_check_rec_size(self, rec_len))
+ return 0;
- self->rec_len = join_append_data(self, field, quote_empty, quoted, 1);
- self->num_fields++;
+ self->rec_len = join_append_data(self, field, quote_empty, quoted, 1);
+ self->num_fields++;
- return 1;
+ return 1;
}
static int
join_append_lineterminator(WriterObj *self)
{
- int terminator_len;
- Py_UNICODE *terminator;
+ int terminator_len;
+ Py_UNICODE *terminator;
- terminator_len = PyUnicode_GetSize(self->dialect->lineterminator);
- if (terminator_len == -1)
- return 0;
+ terminator_len = PyUnicode_GetSize(self->dialect->lineterminator);
+ if (terminator_len == -1)
+ return 0;
- /* grow record buffer if necessary */
- if (!join_check_rec_size(self, self->rec_len + terminator_len))
- return 0;
+ /* grow record buffer if necessary */
+ if (!join_check_rec_size(self, self->rec_len + terminator_len))
+ return 0;
- terminator = PyUnicode_AsUnicode(self->dialect->lineterminator);
- if (terminator == NULL)
- return 0;
- memmove(self->rec + self->rec_len, terminator,
- sizeof(Py_UNICODE)*terminator_len);
- self->rec_len += terminator_len;
+ terminator = PyUnicode_AsUnicode(self->dialect->lineterminator);
+ if (terminator == NULL)
+ return 0;
+ memmove(self->rec + self->rec_len, terminator,
+ sizeof(Py_UNICODE)*terminator_len);
+ self->rec_len += terminator_len;
- return 1;
+ return 1;
}
PyDoc_STRVAR(csv_writerow_doc,
@@ -1124,75 +1124,75 @@ PyDoc_STRVAR(csv_writerow_doc,
static PyObject *
csv_writerow(WriterObj *self, PyObject *seq)
{
- DialectObj *dialect = self->dialect;
- int len, i;
-
- if (!PySequence_Check(seq))
- return PyErr_Format(error_obj, "sequence expected");
-
- len = PySequence_Length(seq);
- if (len < 0)
- return NULL;
-
- /* Join all fields in internal buffer.
- */
- join_reset(self);
- for (i = 0; i < len; i++) {
- PyObject *field;
- int append_ok;
- int quoted;
-
- field = PySequence_GetItem(seq, i);
- if (field == NULL)
- return NULL;
-
- switch (dialect->quoting) {
- case QUOTE_NONNUMERIC:
- quoted = !PyNumber_Check(field);
- break;
- case QUOTE_ALL:
- quoted = 1;
- break;
- default:
- quoted = 0;
- break;
- }
-
- if (PyUnicode_Check(field)) {
- append_ok = join_append(self,
- PyUnicode_AS_UNICODE(field),
- &quoted, len == 1);
- Py_DECREF(field);
- }
- else if (field == Py_None) {
- append_ok = join_append(self, NULL,
+ DialectObj *dialect = self->dialect;
+ int len, i;
+
+ if (!PySequence_Check(seq))
+ return PyErr_Format(error_obj, "sequence expected");
+
+ len = PySequence_Length(seq);
+ if (len < 0)
+ return NULL;
+
+ /* Join all fields in internal buffer.
+ */
+ join_reset(self);
+ for (i = 0; i < len; i++) {
+ PyObject *field;
+ int append_ok;
+ int quoted;
+
+ field = PySequence_GetItem(seq, i);
+ if (field == NULL)
+ return NULL;
+
+ switch (dialect->quoting) {
+ case QUOTE_NONNUMERIC:
+ quoted = !PyNumber_Check(field);
+ break;
+ case QUOTE_ALL:
+ quoted = 1;
+ break;
+ default:
+ quoted = 0;
+ break;
+ }
+
+ if (PyUnicode_Check(field)) {
+ append_ok = join_append(self,
+ PyUnicode_AS_UNICODE(field),
&quoted, len == 1);
- Py_DECREF(field);
- }
- else {
- PyObject *str;
-
- str = PyObject_Str(field);
- Py_DECREF(field);
- if (str == NULL)
- return NULL;
- append_ok = join_append(self,
- PyUnicode_AS_UNICODE(str),
- &quoted, len == 1);
- Py_DECREF(str);
- }
- if (!append_ok)
- return NULL;
- }
-
- /* Add line terminator.
- */
- if (!join_append_lineterminator(self))
- return 0;
-
- return PyObject_CallFunction(self->writeline,
- "(u#)", self->rec,
- self->rec_len);
+ Py_DECREF(field);
+ }
+ else if (field == Py_None) {
+ append_ok = join_append(self, NULL,
+ &quoted, len == 1);
+ Py_DECREF(field);
+ }
+ else {
+ PyObject *str;
+
+ str = PyObject_Str(field);
+ Py_DECREF(field);
+ if (str == NULL)
+ return NULL;
+ append_ok = join_append(self,
+ PyUnicode_AS_UNICODE(str),
+ &quoted, len == 1);
+ Py_DECREF(str);
+ }
+ if (!append_ok)
+ return NULL;
+ }
+
+ /* Add line terminator.
+ */
+ if (!join_append_lineterminator(self))
+ return 0;
+
+ return PyObject_CallFunction(self->writeline,
+ "(u#)", self->rec,
+ self->rec_len);
}
PyDoc_STRVAR(csv_writerows_doc,
@@ -1204,72 +1204,72 @@ PyDoc_STRVAR(csv_writerows_doc,
static PyObject *
csv_writerows(WriterObj *self, PyObject *seqseq)
{
- PyObject *row_iter, *row_obj, *result;
-
- row_iter = PyObject_GetIter(seqseq);
- if (row_iter == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "writerows() argument must be iterable");
- return NULL;
- }
- while ((row_obj = PyIter_Next(row_iter))) {
- result = csv_writerow(self, row_obj);
- Py_DECREF(row_obj);
- if (!result) {
- Py_DECREF(row_iter);
- return NULL;
- }
- else
- Py_DECREF(result);
+ PyObject *row_iter, *row_obj, *result;
+
+ row_iter = PyObject_GetIter(seqseq);
+ if (row_iter == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "writerows() argument must be iterable");
+ return NULL;
+ }
+ while ((row_obj = PyIter_Next(row_iter))) {
+ result = csv_writerow(self, row_obj);
+ Py_DECREF(row_obj);
+ if (!result) {
+ Py_DECREF(row_iter);
+ return NULL;
}
- Py_DECREF(row_iter);
- if (PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ else
+ Py_DECREF(result);
+ }
+ Py_DECREF(row_iter);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef Writer_methods[] = {
- { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc},
- { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc},
- { NULL, NULL }
+ { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc},
+ { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc},
+ { NULL, NULL }
};
#define W_OFF(x) offsetof(WriterObj, x)
static struct PyMemberDef Writer_memberlist[] = {
- { "dialect", T_OBJECT, W_OFF(dialect), READONLY },
- { NULL }
+ { "dialect", T_OBJECT, W_OFF(dialect), READONLY },
+ { NULL }
};
static void
Writer_dealloc(WriterObj *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->dialect);
- Py_XDECREF(self->writeline);
- if (self->rec != NULL)
- PyMem_Free(self->rec);
- PyObject_GC_Del(self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->dialect);
+ Py_XDECREF(self->writeline);
+ if (self->rec != NULL)
+ PyMem_Free(self->rec);
+ PyObject_GC_Del(self);
}
static int
Writer_traverse(WriterObj *self, visitproc visit, void *arg)
{
- Py_VISIT(self->dialect);
- Py_VISIT(self->writeline);
- return 0;
+ Py_VISIT(self->dialect);
+ Py_VISIT(self->writeline);
+ return 0;
}
static int
Writer_clear(WriterObj *self)
{
- Py_CLEAR(self->dialect);
- Py_CLEAR(self->writeline);
- return 0;
+ Py_CLEAR(self->dialect);
+ Py_CLEAR(self->writeline);
+ return 0;
}
-PyDoc_STRVAR(Writer_Type_doc,
+PyDoc_STRVAR(Writer_Type_doc,
"CSV writer\n"
"\n"
"Writer objects are responsible for generating tabular data\n"
@@ -1277,75 +1277,75 @@ PyDoc_STRVAR(Writer_Type_doc,
);
static PyTypeObject Writer_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_csv.writer", /*tp_name*/
- sizeof(WriterObj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)Writer_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- 0, /*tp_reserved*/
- (reprfunc)0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- (hashfunc)0, /*tp_hash*/
- (ternaryfunc)0, /*tp_call*/
- (reprfunc)0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- Writer_Type_doc,
- (traverseproc)Writer_traverse, /*tp_traverse*/
- (inquiry)Writer_clear, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- (getiterfunc)0, /*tp_iter*/
- (getiterfunc)0, /*tp_iternext*/
- Writer_methods, /*tp_methods*/
- Writer_memberlist, /*tp_members*/
- 0, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_csv.writer", /*tp_name*/
+ sizeof(WriterObj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)Writer_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ (reprfunc)0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ (hashfunc)0, /*tp_hash*/
+ (ternaryfunc)0, /*tp_call*/
+ (reprfunc)0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ Writer_Type_doc,
+ (traverseproc)Writer_traverse, /*tp_traverse*/
+ (inquiry)Writer_clear, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ (getiterfunc)0, /*tp_iter*/
+ (getiterfunc)0, /*tp_iternext*/
+ Writer_methods, /*tp_methods*/
+ Writer_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
};
static PyObject *
csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
{
- PyObject * output_file, * dialect = NULL;
- WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type);
-
- if (!self)
- return NULL;
-
- self->dialect = NULL;
- self->writeline = NULL;
-
- self->rec = NULL;
- self->rec_size = 0;
- self->rec_len = 0;
- self->num_fields = 0;
-
- if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) {
- Py_DECREF(self);
- return NULL;
- }
- self->writeline = PyObject_GetAttrString(output_file, "write");
- if (self->writeline == NULL || !PyCallable_Check(self->writeline)) {
- PyErr_SetString(PyExc_TypeError,
- "argument 1 must have a \"write\" method");
- Py_DECREF(self);
- return NULL;
- }
- self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
- if (self->dialect == NULL) {
- Py_DECREF(self);
- return NULL;
- }
- PyObject_GC_Track(self);
- return (PyObject *)self;
+ PyObject * output_file, * dialect = NULL;
+ WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type);
+
+ if (!self)
+ return NULL;
+
+ self->dialect = NULL;
+ self->writeline = NULL;
+
+ self->rec = NULL;
+ self->rec_size = 0;
+ self->rec_len = 0;
+ self->num_fields = 0;
+
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->writeline = PyObject_GetAttrString(output_file, "write");
+ if (self->writeline == NULL || !PyCallable_Check(self->writeline)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument 1 must have a \"write\" method");
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
+ if (self->dialect == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ PyObject_GC_Track(self);
+ return (PyObject *)self;
}
/*
@@ -1354,70 +1354,70 @@ csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
static PyObject *
csv_list_dialects(PyObject *module, PyObject *args)
{
- return PyDict_Keys(dialects);
+ return PyDict_Keys(dialects);
}
static PyObject *
csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs)
{
- PyObject *name_obj, *dialect_obj = NULL;
- PyObject *dialect;
-
- if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj))
- return NULL;
- if (!IS_BASESTRING(name_obj)) {
- PyErr_SetString(PyExc_TypeError,
- "dialect name must be a string or unicode");
- return NULL;
- }
- dialect = _call_dialect(dialect_obj, kwargs);
- if (dialect == NULL)
- return NULL;
- if (PyDict_SetItem(dialects, name_obj, dialect) < 0) {
- Py_DECREF(dialect);
- return NULL;
- }
- Py_DECREF(dialect);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *name_obj, *dialect_obj = NULL;
+ PyObject *dialect;
+
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj))
+ return NULL;
+ if (!IS_BASESTRING(name_obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "dialect name must be a string or unicode");
+ return NULL;
+ }
+ dialect = _call_dialect(dialect_obj, kwargs);
+ if (dialect == NULL)
+ return NULL;
+ if (PyDict_SetItem(dialects, name_obj, dialect) < 0) {
+ Py_DECREF(dialect);
+ return NULL;
+ }
+ Py_DECREF(dialect);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
csv_unregister_dialect(PyObject *module, PyObject *name_obj)
{
- if (PyDict_DelItem(dialects, name_obj) < 0)
- return PyErr_Format(error_obj, "unknown dialect");
- Py_INCREF(Py_None);
- return Py_None;
+ if (PyDict_DelItem(dialects, name_obj) < 0)
+ return PyErr_Format(error_obj, "unknown dialect");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
csv_get_dialect(PyObject *module, PyObject *name_obj)
{
- return get_dialect_from_registry(name_obj);
+ return get_dialect_from_registry(name_obj);
}
static PyObject *
csv_field_size_limit(PyObject *module, PyObject *args)
{
- PyObject *new_limit = NULL;
- long old_limit = field_limit;
-
- if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
- return NULL;
- if (new_limit != NULL) {
- if (!PyLong_CheckExact(new_limit)) {
- PyErr_Format(PyExc_TypeError,
- "limit must be an integer");
- return NULL;
- }
- field_limit = PyLong_AsLong(new_limit);
- if (field_limit == -1 && PyErr_Occurred()) {
- field_limit = old_limit;
- return NULL;
- }
- }
- return PyLong_FromLong(old_limit);
+ PyObject *new_limit = NULL;
+ long old_limit = field_limit;
+
+ if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
+ return NULL;
+ if (new_limit != NULL) {
+ if (!PyLong_CheckExact(new_limit)) {
+ PyErr_Format(PyExc_TypeError,
+ "limit must be an integer");
+ return NULL;
+ }
+ field_limit = PyLong_AsLong(new_limit);
+ if (field_limit == -1 && PyErr_Occurred()) {
+ field_limit = old_limit;
+ return NULL;
+ }
+ }
+ return PyLong_FromLong(old_limit);
}
/*
@@ -1535,84 +1535,84 @@ PyDoc_STRVAR(csv_field_size_limit_doc,
"the old limit is returned");
static struct PyMethodDef csv_methods[] = {
- { "reader", (PyCFunction)csv_reader,
- METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
- { "writer", (PyCFunction)csv_writer,
- METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
- { "list_dialects", (PyCFunction)csv_list_dialects,
- METH_NOARGS, csv_list_dialects_doc},
- { "register_dialect", (PyCFunction)csv_register_dialect,
- METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
- { "unregister_dialect", (PyCFunction)csv_unregister_dialect,
- METH_O, csv_unregister_dialect_doc},
- { "get_dialect", (PyCFunction)csv_get_dialect,
- METH_O, csv_get_dialect_doc},
- { "field_size_limit", (PyCFunction)csv_field_size_limit,
- METH_VARARGS, csv_field_size_limit_doc},
- { NULL, NULL }
+ { "reader", (PyCFunction)csv_reader,
+ METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
+ { "writer", (PyCFunction)csv_writer,
+ METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
+ { "list_dialects", (PyCFunction)csv_list_dialects,
+ METH_NOARGS, csv_list_dialects_doc},
+ { "register_dialect", (PyCFunction)csv_register_dialect,
+ METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
+ { "unregister_dialect", (PyCFunction)csv_unregister_dialect,
+ METH_O, csv_unregister_dialect_doc},
+ { "get_dialect", (PyCFunction)csv_get_dialect,
+ METH_O, csv_get_dialect_doc},
+ { "field_size_limit", (PyCFunction)csv_field_size_limit,
+ METH_VARARGS, csv_field_size_limit_doc},
+ { NULL, NULL }
};
static struct PyModuleDef _csvmodule = {
- PyModuleDef_HEAD_INIT,
- "_csv",
- csv_module_doc,
- -1,
- csv_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_csv",
+ csv_module_doc,
+ -1,
+ csv_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__csv(void)
{
- PyObject *module;
- StyleDesc *style;
-
- if (PyType_Ready(&Dialect_Type) < 0)
- return NULL;
-
- if (PyType_Ready(&Reader_Type) < 0)
- return NULL;
-
- if (PyType_Ready(&Writer_Type) < 0)
- return NULL;
-
- /* Create the module and add the functions */
- module = PyModule_Create(&_csvmodule);
- if (module == NULL)
- return NULL;
-
- /* Add version to the module. */
- if (PyModule_AddStringConstant(module, "__version__",
- MODULE_VERSION) == -1)
- return NULL;
-
- /* Add _dialects dictionary */
- dialects = PyDict_New();
- if (dialects == NULL)
- return NULL;
- if (PyModule_AddObject(module, "_dialects", dialects))
- return NULL;
-
- /* Add quote styles into dictionary */
- for (style = quote_styles; style->name; style++) {
- if (PyModule_AddIntConstant(module, style->name,
- style->style) == -1)
- return NULL;
- }
-
- /* Add the Dialect type */
- Py_INCREF(&Dialect_Type);
- if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
- return NULL;
-
- /* Add the CSV exception object to the module. */
- error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
- if (error_obj == NULL)
- return NULL;
- PyModule_AddObject(module, "Error", error_obj);
- return module;
+ PyObject *module;
+ StyleDesc *style;
+
+ if (PyType_Ready(&Dialect_Type) < 0)
+ return NULL;
+
+ if (PyType_Ready(&Reader_Type) < 0)
+ return NULL;
+
+ if (PyType_Ready(&Writer_Type) < 0)
+ return NULL;
+
+ /* Create the module and add the functions */
+ module = PyModule_Create(&_csvmodule);
+ if (module == NULL)
+ return NULL;
+
+ /* Add version to the module. */
+ if (PyModule_AddStringConstant(module, "__version__",
+ MODULE_VERSION) == -1)
+ return NULL;
+
+ /* Add _dialects dictionary */
+ dialects = PyDict_New();
+ if (dialects == NULL)
+ return NULL;
+ if (PyModule_AddObject(module, "_dialects", dialects))
+ return NULL;
+
+ /* Add quote styles into dictionary */
+ for (style = quote_styles; style->name; style++) {
+ if (PyModule_AddIntConstant(module, style->name,
+ style->style) == -1)
+ return NULL;
+ }
+
+ /* Add the Dialect type */
+ Py_INCREF(&Dialect_Type);
+ if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
+ return NULL;
+
+ /* Add the CSV exception object to the module. */
+ error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
+ if (error_obj == NULL)
+ return NULL;
+ PyModule_AddObject(module, "Error", error_obj);
+ return module;
}
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index 21961ae..c1b3093 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -20,20 +20,20 @@
/*
-Name methods, members, getsets
+Name methods, members, getsets
==============================================================================
-PyCStructType_Type __new__(), from_address(), __mul__(), from_param()
-UnionType_Type __new__(), from_address(), __mul__(), from_param()
-PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
-PyCArrayType_Type __new__(), from_address(), __mul__(), from_param()
-PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param()
+PyCStructType_Type __new__(), from_address(), __mul__(), from_param()
+UnionType_Type __new__(), from_address(), __mul__(), from_param()
+PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
+PyCArrayType_Type __new__(), from_address(), __mul__(), from_param()
+PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param()
PyCData_Type
- Struct_Type __new__(), __init__()
- PyCPointer_Type __new__(), __init__(), _as_parameter_, contents
- PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
- Simple_Type __new__(), __init__(), _as_parameter_
+ Struct_Type __new__(), __init__()
+ PyCPointer_Type __new__(), __init__(), _as_parameter_, contents
+ PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
+ Simple_Type __new__(), __init__(), _as_parameter_
PyCField_Type
PyCStgDict_Type
@@ -45,28 +45,28 @@ class methods
It has some similarity to the byref() construct compared to pointer()
from_address(addr)
- - construct an instance from a given memory block (sharing this memory block)
+ - construct an instance from a given memory block (sharing this memory block)
from_param(obj)
- - typecheck and convert a Python object into a C function call parameter
- the result may be an instance of the type, or an integer or tuple
- (typecode, value[, obj])
+ - typecheck and convert a Python object into a C function call parameter
+ the result may be an instance of the type, or an integer or tuple
+ (typecode, value[, obj])
instance methods/properties
---------------------------
_as_parameter_
- - convert self into a C function call parameter
- This is either an integer, or a 3-tuple (typecode, value, obj)
+ - convert self into a C function call parameter
+ This is either an integer, or a 3-tuple (typecode, value, obj)
functions
---------
sizeof(cdata)
- - return the number of bytes the buffer contains
+ - return the number of bytes the buffer contains
sizeof(ctype)
- - return the number of bytes the buffer of an instance would contain
+ - return the number of bytes the buffer of an instance would contain
byref(cdata)
@@ -77,7 +77,7 @@ pointer(cdata)
POINTER(ctype)
bytes(cdata)
- - return the buffer contents as a sequence of bytes (which is currently a string)
+ - return the buffer contents as a sequence of bytes (which is currently a string)
*/
@@ -98,7 +98,7 @@ bytes(cdata)
* PyCField_Type
*
*/
-
+
#define PY_SSIZE_T_CLEAN
#include "Python.h"
@@ -135,128 +135,128 @@ static PyObject *_unpickle;
char *_ctypes_conversion_encoding = NULL;
char *_ctypes_conversion_errors = NULL;
-
+
/****************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *key;
- PyObject *dict;
+ PyObject_HEAD
+ PyObject *key;
+ PyObject *dict;
} DictRemoverObject;
static void
_DictRemover_dealloc(PyObject *_self)
{
- DictRemoverObject *self = (DictRemoverObject *)_self;
- Py_XDECREF(self->key);
- Py_XDECREF(self->dict);
- Py_TYPE(self)->tp_free(_self);
+ DictRemoverObject *self = (DictRemoverObject *)_self;
+ Py_XDECREF(self->key);
+ Py_XDECREF(self->dict);
+ Py_TYPE(self)->tp_free(_self);
}
static PyObject *
_DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw)
{
- DictRemoverObject *self = (DictRemoverObject *)_self;
- if (self->key && self->dict) {
- if (-1 == PyDict_DelItem(self->dict, self->key))
- /* XXX Error context */
- PyErr_WriteUnraisable(Py_None);
- Py_DECREF(self->key);
- self->key = NULL;
- Py_DECREF(self->dict);
- self->dict = NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ DictRemoverObject *self = (DictRemoverObject *)_self;
+ if (self->key && self->dict) {
+ if (-1 == PyDict_DelItem(self->dict, self->key))
+ /* XXX Error context */
+ PyErr_WriteUnraisable(Py_None);
+ Py_DECREF(self->key);
+ self->key = NULL;
+ Py_DECREF(self->dict);
+ self->dict = NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyTypeObject DictRemover_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.DictRemover", /* tp_name */
- sizeof(DictRemoverObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- _DictRemover_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- _DictRemover_call, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.DictRemover", /* tp_name */
+ sizeof(DictRemoverObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ _DictRemover_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ _DictRemover_call, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
/* XXX should participate in GC? */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- "deletes a key from a dictionary", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ "deletes a key from a dictionary", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
int
PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item)
{
- PyObject *obj;
- DictRemoverObject *remover;
- PyObject *proxy;
- int result;
-
- obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
- if (obj == NULL)
- return -1;
-
- remover = (DictRemoverObject *)obj;
- assert(remover->key == NULL);
- assert(remover->dict == NULL);
- Py_INCREF(key);
- remover->key = key;
- Py_INCREF(dict);
- remover->dict = dict;
-
- proxy = PyWeakref_NewProxy(item, obj);
- Py_DECREF(obj);
- if (proxy == NULL)
- return -1;
-
- result = PyDict_SetItem(dict, key, proxy);
- Py_DECREF(proxy);
- return result;
+ PyObject *obj;
+ DictRemoverObject *remover;
+ PyObject *proxy;
+ int result;
+
+ obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
+ if (obj == NULL)
+ return -1;
+
+ remover = (DictRemoverObject *)obj;
+ assert(remover->key == NULL);
+ assert(remover->dict == NULL);
+ Py_INCREF(key);
+ remover->key = key;
+ Py_INCREF(dict);
+ remover->dict = dict;
+
+ proxy = PyWeakref_NewProxy(item, obj);
+ Py_DECREF(obj);
+ if (proxy == NULL)
+ return -1;
+
+ result = PyDict_SetItem(dict, key, proxy);
+ Py_DECREF(proxy);
+ return result;
}
PyObject *
PyDict_GetItemProxy(PyObject *dict, PyObject *key)
{
- PyObject *result;
- PyObject *item = PyDict_GetItem(dict, key);
-
- if (item == NULL)
- return NULL;
- if (!PyWeakref_CheckProxy(item))
- return item;
- result = PyWeakref_GET_OBJECT(item);
- if (result == Py_None)
- return NULL;
- return result;
+ PyObject *result;
+ PyObject *item = PyDict_GetItem(dict, key);
+
+ if (item == NULL)
+ return NULL;
+ if (!PyWeakref_CheckProxy(item))
+ return item;
+ result = PyWeakref_GET_OBJECT(item);
+ if (result == Py_None)
+ return NULL;
+ return result;
}
/******************************************************************/
@@ -269,25 +269,25 @@ PyDict_GetItemProxy(PyObject *dict, PyObject *key)
char *
_ctypes_alloc_format_string(const char *prefix, const char *suffix)
{
- size_t len;
- char *result;
-
- if (suffix == NULL) {
- assert(PyErr_Occurred());
- return NULL;
- }
- len = strlen(suffix);
- if (prefix)
- len += strlen(prefix);
- result = PyMem_Malloc(len + 1);
- if (result == NULL)
- return NULL;
- if (prefix)
- strcpy(result, prefix);
- else
- result[0] = '\0';
- strcat(result, suffix);
- return result;
+ size_t len;
+ char *result;
+
+ if (suffix == NULL) {
+ assert(PyErr_Occurred());
+ return NULL;
+ }
+ len = strlen(suffix);
+ if (prefix)
+ len += strlen(prefix);
+ result = PyMem_Malloc(len + 1);
+ if (result == NULL)
+ return NULL;
+ if (prefix)
+ strcpy(result, prefix);
+ else
+ result[0] = '\0';
+ strcat(result, suffix);
+ return result;
}
/*
@@ -300,100 +300,100 @@ _ctypes_alloc_format_string(const char *prefix, const char *suffix)
static PyCArgObject *
StructUnionType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
- StgDictObject *stgdict;
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'V';
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for structure/union instances */
- parg->pffi_type = &stgdict->ffi_type_pointer;
- /* For structure parameters (by value), parg->value doesn't contain the structure
- data itself, instead parg->value.p *points* to the structure's data
- See also _ctypes.c, function _call_function_pointer().
- */
- parg->value.p = self->b_ptr;
- parg->size = self->b_size;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- return parg;
+ PyCArgObject *parg;
+ StgDictObject *stgdict;
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'V';
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for structure/union instances */
+ parg->pffi_type = &stgdict->ffi_type_pointer;
+ /* For structure parameters (by value), parg->value doesn't contain the structure
+ data itself, instead parg->value.p *points* to the structure's data
+ See also _ctypes.c, function _call_function_pointer().
+ */
+ parg->value.p = self->b_ptr;
+ parg->size = self->b_size;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ return parg;
}
static PyObject *
StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct)
{
- PyTypeObject *result;
- PyObject *fields;
- StgDictObject *dict;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (!result)
- return NULL;
-
- /* keep this for bw compatibility */
- if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
- return (PyObject *)result;
-
- dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL);
- if (!dict) {
- Py_DECREF(result);
- return NULL;
- }
- /* replace the class dict by our updated stgdict, which holds info
- about storage requirements of the instances */
- if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)dict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)dict;
- dict->format = _ctypes_alloc_format_string(NULL, "B");
- if (dict->format == NULL) {
- Py_DECREF(result);
- return NULL;
- }
-
- dict->paramfunc = StructUnionType_paramfunc;
-
- fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
- if (!fields) {
- StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
-
- if (basedict == NULL)
- return (PyObject *)result;
- /* copy base dict */
- if (-1 == PyCStgDict_clone(dict, basedict)) {
- Py_DECREF(result);
- return NULL;
- }
- dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */
- basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */
- return (PyObject *)result;
- }
-
- if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
- Py_DECREF(result);
- return NULL;
- }
- return (PyObject *)result;
+ PyTypeObject *result;
+ PyObject *fields;
+ StgDictObject *dict;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (!result)
+ return NULL;
+
+ /* keep this for bw compatibility */
+ if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
+ return (PyObject *)result;
+
+ dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL);
+ if (!dict) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ /* replace the class dict by our updated stgdict, which holds info
+ about storage requirements of the instances */
+ if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)dict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)dict;
+ dict->format = _ctypes_alloc_format_string(NULL, "B");
+ if (dict->format == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ dict->paramfunc = StructUnionType_paramfunc;
+
+ fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
+ if (!fields) {
+ StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
+
+ if (basedict == NULL)
+ return (PyObject *)result;
+ /* copy base dict */
+ if (-1 == PyCStgDict_clone(dict, basedict)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */
+ basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */
+ return (PyObject *)result;
+ }
+
+ if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return (PyObject *)result;
}
static PyObject *
PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- return StructUnionType_new(type, args, kwds, 1);
+ return StructUnionType_new(type, args, kwds, 1);
}
static PyObject *
UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- return StructUnionType_new(type, args, kwds, 0);
+ return StructUnionType_new(type, args, kwds, 0);
}
static char from_address_doc[] =
@@ -402,16 +402,16 @@ static char from_address_doc[] =
static PyObject *
CDataType_from_address(PyObject *type, PyObject *value)
{
- void *buf;
- if (!PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "integer expected");
- return NULL;
- }
- buf = (void *)PyLong_AsVoidPtr(value);
- if (PyErr_Occurred())
- return NULL;
- return PyCData_AtAddress(type, buf);
+ void *buf;
+ if (!PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "integer expected");
+ return NULL;
+ }
+ buf = (void *)PyLong_AsVoidPtr(value);
+ if (PyErr_Occurred())
+ return NULL;
+ return PyCData_AtAddress(type, buf);
}
static char from_buffer_doc[] =
@@ -423,51 +423,51 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
static PyObject *
CDataType_from_buffer(PyObject *type, PyObject *args)
{
- void *buffer;
- Py_ssize_t buffer_len;
- Py_ssize_t offset = 0;
- PyObject *obj, *result;
- StgDictObject *dict = PyType_stgdict(type);
- assert (dict);
-
- if (!PyArg_ParseTuple(args,
+ void *buffer;
+ Py_ssize_t buffer_len;
+ Py_ssize_t offset = 0;
+ PyObject *obj, *result;
+ StgDictObject *dict = PyType_stgdict(type);
+ assert (dict);
+
+ if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
- "O|i:from_buffer",
+ "O|i:from_buffer",
#else
- "O|n:from_buffer",
+ "O|n:from_buffer",
#endif
- &obj, &offset))
- return NULL;
-
- if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
- return NULL;
-
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError,
- "offset cannot be negative");
- return NULL;
- }
- if (dict->size > buffer_len - offset) {
- PyErr_Format(PyExc_ValueError,
+ &obj, &offset))
+ return NULL;
+
+ if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
+ return NULL;
+
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "offset cannot be negative");
+ return NULL;
+ }
+ if (dict->size > buffer_len - offset) {
+ PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Buffer size too small (%d instead of at least %d bytes)",
+ "Buffer size too small (%d instead of at least %d bytes)",
#else
- "Buffer size too small (%zd instead of at least %zd bytes)",
+ "Buffer size too small (%zd instead of at least %zd bytes)",
#endif
- buffer_len, dict->size + offset);
- return NULL;
- }
-
- result = PyCData_AtAddress(type, (char *)buffer + offset);
- if (result == NULL)
- return NULL;
-
- Py_INCREF(obj);
- if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
- Py_DECREF(result);
- return NULL;
- }
- return result;
+ buffer_len, dict->size + offset);
+ return NULL;
+ }
+
+ result = PyCData_AtAddress(type, (char *)buffer + offset);
+ if (result == NULL)
+ return NULL;
+
+ Py_INCREF(obj);
+ if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return result;
}
static char from_buffer_copy_doc[] =
@@ -479,48 +479,48 @@ GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
CDataType_from_buffer_copy(PyObject *type, PyObject *args)
{
- const void *buffer;
- Py_ssize_t buffer_len;
- Py_ssize_t offset = 0;
- PyObject *obj, *result;
- StgDictObject *dict = PyType_stgdict(type);
- assert (dict);
-
- if (!PyArg_ParseTuple(args,
+ const void *buffer;
+ Py_ssize_t buffer_len;
+ Py_ssize_t offset = 0;
+ PyObject *obj, *result;
+ StgDictObject *dict = PyType_stgdict(type);
+ assert (dict);
+
+ if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
- "O|i:from_buffer",
+ "O|i:from_buffer",
#else
- "O|n:from_buffer",
+ "O|n:from_buffer",
#endif
- &obj, &offset))
- return NULL;
+ &obj, &offset))
+ return NULL;
- if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len))
- return NULL;
+ if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len))
+ return NULL;
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError,
- "offset cannot be negative");
- return NULL;
- }
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "offset cannot be negative");
+ return NULL;
+ }
- if (dict->size > buffer_len - offset) {
- PyErr_Format(PyExc_ValueError,
+ if (dict->size > buffer_len - offset) {
+ PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Buffer size too small (%d instead of at least %d bytes)",
+ "Buffer size too small (%d instead of at least %d bytes)",
#else
- "Buffer size too small (%zd instead of at least %zd bytes)",
+ "Buffer size too small (%zd instead of at least %zd bytes)",
#endif
- buffer_len, dict->size + offset);
- return NULL;
- }
-
- result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL);
- if (result == NULL)
- return NULL;
- memcpy(((CDataObject *)result)->b_ptr,
- (char *)buffer+offset, dict->size);
- return result;
+ buffer_len, dict->size + offset);
+ return NULL;
+ }
+
+ result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL);
+ if (result == NULL)
+ return NULL;
+ memcpy(((CDataObject *)result)->b_ptr,
+ (char *)buffer+offset, dict->size);
+ return result;
}
static char in_dll_doc[] =
@@ -529,55 +529,55 @@ static char in_dll_doc[] =
static PyObject *
CDataType_in_dll(PyObject *type, PyObject *args)
{
- PyObject *dll;
- char *name;
- PyObject *obj;
- void *handle;
- void *address;
-
- if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
- return NULL;
-
- obj = PyObject_GetAttrString(dll, "_handle");
- if (!obj)
- return NULL;
- if (!PyLong_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "the _handle attribute of the second argument must be an integer");
- Py_DECREF(obj);
- return NULL;
- }
- handle = (void *)PyLong_AsVoidPtr(obj);
- Py_DECREF(obj);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert the _handle attribute to a pointer");
- return NULL;
- }
+ PyObject *dll;
+ char *name;
+ PyObject *obj;
+ void *handle;
+ void *address;
+
+ if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
+ return NULL;
+
+ obj = PyObject_GetAttrString(dll, "_handle");
+ if (!obj)
+ return NULL;
+ if (!PyLong_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the _handle attribute of the second argument must be an integer");
+ Py_DECREF(obj);
+ return NULL;
+ }
+ handle = (void *)PyLong_AsVoidPtr(obj);
+ Py_DECREF(obj);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert the _handle attribute to a pointer");
+ return NULL;
+ }
#ifdef MS_WIN32
- address = (void *)GetProcAddress(handle, name);
- if (!address) {
- PyErr_Format(PyExc_ValueError,
- "symbol '%s' not found",
- name);
- return NULL;
- }
+ address = (void *)GetProcAddress(handle, name);
+ if (!address) {
+ PyErr_Format(PyExc_ValueError,
+ "symbol '%s' not found",
+ name);
+ return NULL;
+ }
#else
- address = (void *)ctypes_dlsym(handle, name);
- if (!address) {
+ address = (void *)ctypes_dlsym(handle, name);
+ if (!address) {
#ifdef __CYGWIN__
/* dlerror() isn't very helpful on cygwin */
- PyErr_Format(PyExc_ValueError,
- "symbol '%s' not found (%s) ",
- name);
+ PyErr_Format(PyExc_ValueError,
+ "symbol '%s' not found (%s) ",
+ name);
#else
- PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
+ PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
#endif
- return NULL;
- }
+ return NULL;
+ }
#endif
- return PyCData_AtAddress(type, address);
+ return PyCData_AtAddress(type, address);
}
static char from_param_doc[] =
@@ -586,210 +586,210 @@ static char from_param_doc[] =
static PyObject *
CDataType_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
- if (1 == PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
- if (PyCArg_CheckExact(value)) {
- PyCArgObject *p = (PyCArgObject *)value;
- PyObject *ob = p->obj;
- const char *ob_name;
- StgDictObject *dict;
- dict = PyType_stgdict(type);
-
- /* If we got a PyCArgObject, we must check if the object packed in it
- is an instance of the type's dict->proto */
- if(dict && ob
- && PyObject_IsInstance(ob, dict->proto)) {
- Py_INCREF(value);
- return value;
- }
- ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
- PyErr_Format(PyExc_TypeError,
- "expected %s instance instead of pointer to %s",
- ((PyTypeObject *)type)->tp_name, ob_name);
- return NULL;
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = CDataType_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- PyErr_Format(PyExc_TypeError,
- "expected %s instance instead of %s",
- ((PyTypeObject *)type)->tp_name,
- Py_TYPE(value)->tp_name);
- return NULL;
+ PyObject *as_parameter;
+ if (1 == PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyCArg_CheckExact(value)) {
+ PyCArgObject *p = (PyCArgObject *)value;
+ PyObject *ob = p->obj;
+ const char *ob_name;
+ StgDictObject *dict;
+ dict = PyType_stgdict(type);
+
+ /* If we got a PyCArgObject, we must check if the object packed in it
+ is an instance of the type's dict->proto */
+ if(dict && ob
+ && PyObject_IsInstance(ob, dict->proto)) {
+ Py_INCREF(value);
+ return value;
+ }
+ ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instance instead of pointer to %s",
+ ((PyTypeObject *)type)->tp_name, ob_name);
+ return NULL;
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = CDataType_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instance instead of %s",
+ ((PyTypeObject *)type)->tp_name,
+ Py_TYPE(value)->tp_name);
+ return NULL;
}
static PyMethodDef CDataType_methods[] = {
- { "from_param", CDataType_from_param, METH_O, from_param_doc },
- { "from_address", CDataType_from_address, METH_O, from_address_doc },
- { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
- { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
- { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
- { NULL, NULL },
+ { "from_param", CDataType_from_param, METH_O, from_param_doc },
+ { "from_address", CDataType_from_address, METH_O, from_address_doc },
+ { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
+ { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
+ { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
+ { NULL, NULL },
};
static PyObject *
CDataType_repeat(PyObject *self, Py_ssize_t length)
{
- if (length < 0)
- return PyErr_Format(PyExc_ValueError,
- "Array length must be >= 0, not %zd",
- length);
- return PyCArrayType_from_ctype(self, length);
+ if (length < 0)
+ return PyErr_Format(PyExc_ValueError,
+ "Array length must be >= 0, not %zd",
+ length);
+ return PyCArrayType_from_ctype(self, length);
}
static PySequenceMethods CDataType_as_sequence = {
- 0, /* inquiry sq_length; */
- 0, /* binaryfunc sq_concat; */
- CDataType_repeat, /* intargfunc sq_repeat; */
- 0, /* intargfunc sq_item; */
- 0, /* intintargfunc sq_slice; */
- 0, /* intobjargproc sq_ass_item; */
- 0, /* intintobjargproc sq_ass_slice; */
- 0, /* objobjproc sq_contains; */
-
- 0, /* binaryfunc sq_inplace_concat; */
- 0, /* intargfunc sq_inplace_repeat; */
+ 0, /* inquiry sq_length; */
+ 0, /* binaryfunc sq_concat; */
+ CDataType_repeat, /* intargfunc sq_repeat; */
+ 0, /* intargfunc sq_item; */
+ 0, /* intintargfunc sq_slice; */
+ 0, /* intobjargproc sq_ass_item; */
+ 0, /* intintobjargproc sq_ass_slice; */
+ 0, /* objobjproc sq_contains; */
+
+ 0, /* binaryfunc sq_inplace_concat; */
+ 0, /* intargfunc sq_inplace_repeat; */
};
static int
CDataType_clear(PyTypeObject *self)
{
- StgDictObject *dict = PyType_stgdict((PyObject *)self);
- if (dict)
- Py_CLEAR(dict->proto);
- return PyType_Type.tp_clear((PyObject *)self);
+ StgDictObject *dict = PyType_stgdict((PyObject *)self);
+ if (dict)
+ Py_CLEAR(dict->proto);
+ return PyType_Type.tp_clear((PyObject *)self);
}
static int
CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg)
{
- StgDictObject *dict = PyType_stgdict((PyObject *)self);
- if (dict)
- Py_VISIT(dict->proto);
- return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
+ StgDictObject *dict = PyType_stgdict((PyObject *)self);
+ if (dict)
+ Py_VISIT(dict->proto);
+ return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
}
static int
PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value)
{
- /* XXX Should we disallow deleting _fields_? */
- if (-1 == PyType_Type.tp_setattro(self, key, value))
- return -1;
-
- if (value && PyUnicode_Check(key) &&
- /* XXX struni _PyUnicode_AsString can fail (also in other places)! */
- 0 == strcmp(_PyUnicode_AsString(key), "_fields_"))
- return PyCStructUnionType_update_stgdict(self, value, 1);
- return 0;
+ /* XXX Should we disallow deleting _fields_? */
+ if (-1 == PyType_Type.tp_setattro(self, key, value))
+ return -1;
+
+ if (value && PyUnicode_Check(key) &&
+ /* XXX struni _PyUnicode_AsString can fail (also in other places)! */
+ 0 == strcmp(_PyUnicode_AsString(key), "_fields_"))
+ return PyCStructUnionType_update_stgdict(self, value, 1);
+ return 0;
}
static int
UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
{
- /* XXX Should we disallow deleting _fields_? */
- if (-1 == PyObject_GenericSetAttr(self, key, value))
- return -1;
-
- if (PyUnicode_Check(key) &&
- 0 == strcmp(_PyUnicode_AsString(key), "_fields_"))
- return PyCStructUnionType_update_stgdict(self, value, 0);
- return 0;
+ /* XXX Should we disallow deleting _fields_? */
+ if (-1 == PyObject_GenericSetAttr(self, key, value))
+ return -1;
+
+ if (PyUnicode_Check(key) &&
+ 0 == strcmp(_PyUnicode_AsString(key), "_fields_"))
+ return PyCStructUnionType_update_stgdict(self, value, 0);
+ return 0;
}
PyTypeObject PyCStructType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCStructType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- PyCStructType_setattro, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for the CData Objects", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCStructType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCStructType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ PyCStructType_setattro, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for the CData Objects", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCStructType_new, /* tp_new */
+ 0, /* tp_free */
};
static PyTypeObject UnionType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.UnionType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- UnionType_setattro, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for the CData Objects", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- UnionType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.UnionType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ UnionType_setattro, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for the CData Objects", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ UnionType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
@@ -809,124 +809,124 @@ size property/method, and the sequence protocol.
static int
PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
{
- if (!proto || !PyType_Check(proto)) {
- PyErr_SetString(PyExc_TypeError,
- "_type_ must be a type");
- return -1;
- }
- if (!PyType_stgdict(proto)) {
- PyErr_SetString(PyExc_TypeError,
- "_type_ must have storage info");
- return -1;
- }
- Py_INCREF(proto);
- Py_XDECREF(stgdict->proto);
- stgdict->proto = proto;
- return 0;
+ if (!proto || !PyType_Check(proto)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_type_ must be a type");
+ return -1;
+ }
+ if (!PyType_stgdict(proto)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_type_ must have storage info");
+ return -1;
+ }
+ Py_INCREF(proto);
+ Py_XDECREF(stgdict->proto);
+ stgdict->proto = proto;
+ return 0;
}
static PyCArgObject *
PyCPointerType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- parg->value.p = *(void **)self->b_ptr;
- return parg;
+ PyCArgObject *parg;
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ parg->value.p = *(void **)self->b_ptr;
+ return parg;
}
static PyObject *
PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- PyObject *proto;
- PyObject *typedict;
-
- typedict = PyTuple_GetItem(args, 2);
- if (!typedict)
- return NULL;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ PyObject *proto;
+ PyObject *typedict;
+
+ typedict = PyTuple_GetItem(args, 2);
+ if (!typedict)
+ return NULL;
/*
stgdict items size, align, length contain info about pointers itself,
stgdict->proto has info about the pointed to type!
*/
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- return NULL;
- stgdict->size = sizeof(void *);
- stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
- stgdict->length = 1;
- stgdict->ffi_type_pointer = ffi_type_pointer;
- stgdict->paramfunc = PyCPointerType_paramfunc;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
-
- proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
- if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- if (proto) {
- StgDictObject *itemdict = PyType_stgdict(proto);
- assert(itemdict);
- /* If itemdict->format is NULL, then this is a pointer to an
- incomplete type. We create a generic format string
- 'pointer to bytes' in this case. XXX Better would be to
- fix the format string later...
- */
- stgdict->format = _ctypes_alloc_format_string("&",
- itemdict->format ? itemdict->format : "B");
- if (stgdict->format == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- }
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- return (PyObject *)result;
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+ stgdict->size = sizeof(void *);
+ stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
+ stgdict->length = 1;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+ stgdict->paramfunc = PyCPointerType_paramfunc;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+
+ proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
+ if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ if (proto) {
+ StgDictObject *itemdict = PyType_stgdict(proto);
+ assert(itemdict);
+ /* If itemdict->format is NULL, then this is a pointer to an
+ incomplete type. We create a generic format string
+ 'pointer to bytes' in this case. XXX Better would be to
+ fix the format string later...
+ */
+ stgdict->format = _ctypes_alloc_format_string("&",
+ itemdict->format ? itemdict->format : "B");
+ if (stgdict->format == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ }
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ return (PyObject *)result;
}
static PyObject *
PyCPointerType_set_type(PyTypeObject *self, PyObject *type)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict((PyObject *)self);
- assert(dict);
+ dict = PyType_stgdict((PyObject *)self);
+ assert(dict);
- if (-1 == PyCPointerType_SetProto(dict, type))
- return NULL;
+ if (-1 == PyCPointerType_SetProto(dict, type))
+ return NULL;
- if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
- return NULL;
+ if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *_byref(PyObject *);
@@ -934,98 +934,98 @@ static PyObject *_byref(PyObject *);
static PyObject *
PyCPointerType_from_param(PyObject *type, PyObject *value)
{
- StgDictObject *typedict;
-
- if (value == Py_None) {
- /* ConvParam will convert to a NULL pointer later */
- Py_INCREF(value);
- return value;
- }
-
- typedict = PyType_stgdict(type);
- assert(typedict); /* Cannot be NULL for pointer types */
-
- /* If we expect POINTER(<type>), but receive a <type> instance, accept
- it by calling byref(<type>).
- */
- switch (PyObject_IsInstance(value, typedict->proto)) {
- case 1:
- Py_INCREF(value); /* _byref steals a refcount */
- return _byref(value);
- case -1:
- PyErr_Clear();
- break;
- default:
- break;
- }
-
- if (PointerObject_Check(value) || ArrayObject_Check(value)) {
- /* Array instances are also pointers when
- the item types are the same.
- */
- StgDictObject *v = PyObject_stgdict(value);
- assert(v); /* Cannot be NULL for pointer or array objects */
- if (PyObject_IsSubclass(v->proto, typedict->proto)) {
- Py_INCREF(value);
- return value;
- }
- }
- return CDataType_from_param(type, value);
+ StgDictObject *typedict;
+
+ if (value == Py_None) {
+ /* ConvParam will convert to a NULL pointer later */
+ Py_INCREF(value);
+ return value;
+ }
+
+ typedict = PyType_stgdict(type);
+ assert(typedict); /* Cannot be NULL for pointer types */
+
+ /* If we expect POINTER(<type>), but receive a <type> instance, accept
+ it by calling byref(<type>).
+ */
+ switch (PyObject_IsInstance(value, typedict->proto)) {
+ case 1:
+ Py_INCREF(value); /* _byref steals a refcount */
+ return _byref(value);
+ case -1:
+ PyErr_Clear();
+ break;
+ default:
+ break;
+ }
+
+ if (PointerObject_Check(value) || ArrayObject_Check(value)) {
+ /* Array instances are also pointers when
+ the item types are the same.
+ */
+ StgDictObject *v = PyObject_stgdict(value);
+ assert(v); /* Cannot be NULL for pointer or array objects */
+ if (PyObject_IsSubclass(v->proto, typedict->proto)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+ return CDataType_from_param(type, value);
}
static PyMethodDef PyCPointerType_methods[] = {
- { "from_address", CDataType_from_address, METH_O, from_address_doc },
- { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
- { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
- { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
- { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc},
- { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O },
- { NULL, NULL },
+ { "from_address", CDataType_from_address, METH_O, from_address_doc },
+ { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
+ { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
+ { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
+ { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc},
+ { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O },
+ { NULL, NULL },
};
PyTypeObject PyCPointerType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCPointerType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for the Pointer Objects", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyCPointerType_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCPointerType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCPointerType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for the Pointer Objects", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyCPointerType_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCPointerType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCArrayType_Type
@@ -1038,152 +1038,152 @@ PyTypeObject PyCPointerType_Type = {
static int
CharArray_set_raw(CDataObject *self, PyObject *value)
{
- char *ptr;
- Py_ssize_t size;
- Py_buffer view;
-
- if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
- return -1;
- size = view.len;
- ptr = view.buf;
- if (size > self->b_size) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- goto fail;
- }
-
- memcpy(self->b_ptr, ptr, size);
-
- PyBuffer_Release(&view);
- return 0;
- fail:
- PyBuffer_Release(&view);
+ char *ptr;
+ Py_ssize_t size;
+ Py_buffer view;
+
+ if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
return -1;
+ size = view.len;
+ ptr = view.buf;
+ if (size > self->b_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ goto fail;
+ }
+
+ memcpy(self->b_ptr, ptr, size);
+
+ PyBuffer_Release(&view);
+ return 0;
+ fail:
+ PyBuffer_Release(&view);
+ return -1;
}
static PyObject *
CharArray_get_raw(CDataObject *self)
{
- return PyBytes_FromStringAndSize(self->b_ptr, self->b_size);
+ return PyBytes_FromStringAndSize(self->b_ptr, self->b_size);
}
static PyObject *
CharArray_get_value(CDataObject *self)
{
- int i;
- char *ptr = self->b_ptr;
- for (i = 0; i < self->b_size; ++i)
- if (*ptr++ == '\0')
- break;
- return PyBytes_FromStringAndSize(self->b_ptr, i);
+ int i;
+ char *ptr = self->b_ptr;
+ for (i = 0; i < self->b_size; ++i)
+ if (*ptr++ == '\0')
+ break;
+ return PyBytes_FromStringAndSize(self->b_ptr, i);
}
static int
CharArray_set_value(CDataObject *self, PyObject *value)
{
- char *ptr;
- Py_ssize_t size;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
-
- if (PyUnicode_Check(value)) {
- value = PyUnicode_AsEncodedString(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return -1;
- } else if (!PyBytes_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "str/bytes expected instead of %s instance",
- Py_TYPE(value)->tp_name);
- return -1;
- } else
- Py_INCREF(value);
- size = PyBytes_GET_SIZE(value);
- if (size > self->b_size) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- Py_DECREF(value);
- return -1;
- }
-
- ptr = PyBytes_AS_STRING(value);
- memcpy(self->b_ptr, ptr, size);
- if (size < self->b_size)
- self->b_ptr[size] = '\0';
- Py_DECREF(value);
-
- return 0;
+ char *ptr;
+ Py_ssize_t size;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+
+ if (PyUnicode_Check(value)) {
+ value = PyUnicode_AsEncodedString(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return -1;
+ } else if (!PyBytes_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "str/bytes expected instead of %s instance",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ } else
+ Py_INCREF(value);
+ size = PyBytes_GET_SIZE(value);
+ if (size > self->b_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ Py_DECREF(value);
+ return -1;
+ }
+
+ ptr = PyBytes_AS_STRING(value);
+ memcpy(self->b_ptr, ptr, size);
+ if (size < self->b_size)
+ self->b_ptr[size] = '\0';
+ Py_DECREF(value);
+
+ return 0;
}
static PyGetSetDef CharArray_getsets[] = {
- { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
- "value", NULL },
- { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
- "string value"},
- { NULL, NULL }
+ { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
+ "value", NULL },
+ { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
+ "string value"},
+ { NULL, NULL }
};
#ifdef CTYPES_UNICODE
static PyObject *
WCharArray_get_value(CDataObject *self)
{
- unsigned int i;
- wchar_t *ptr = (wchar_t *)self->b_ptr;
- for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
- if (*ptr++ == (wchar_t)0)
- break;
- return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
+ unsigned int i;
+ wchar_t *ptr = (wchar_t *)self->b_ptr;
+ for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
+ if (*ptr++ == (wchar_t)0)
+ break;
+ return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
}
static int
WCharArray_set_value(CDataObject *self, PyObject *value)
{
- Py_ssize_t result = 0;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
- if (PyBytes_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return -1;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- Py_TYPE(value)->tp_name);
- return -1;
- } else
- Py_INCREF(value);
- if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- result = -1;
- goto done;
- }
- result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
- (wchar_t *)self->b_ptr,
- self->b_size/sizeof(wchar_t));
- if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
- ((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
+ Py_ssize_t result = 0;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+ if (PyBytes_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return -1;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ } else
+ Py_INCREF(value);
+ if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ result = -1;
+ goto done;
+ }
+ result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
+ (wchar_t *)self->b_ptr,
+ self->b_size/sizeof(wchar_t));
+ if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
+ ((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
done:
- Py_DECREF(value);
+ Py_DECREF(value);
- return result >= 0 ? 0 : -1;
+ return result >= 0 ? 0 : -1;
}
static PyGetSetDef WCharArray_getsets[] = {
- { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
- "string value"},
- { NULL, NULL }
+ { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
+ "string value"},
+ { NULL, NULL }
};
#endif
@@ -1198,236 +1198,236 @@ static PyGetSetDef WCharArray_getsets[] = {
static int
add_methods(PyTypeObject *type, PyMethodDef *meth)
{
- PyObject *dict = type->tp_dict;
- for (; meth->ml_name != NULL; meth++) {
- PyObject *descr;
- descr = PyDescr_NewMethod(type, meth);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ for (; meth->ml_name != NULL; meth++) {
+ PyObject *descr;
+ descr = PyDescr_NewMethod(type, meth);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
static int
add_members(PyTypeObject *type, PyMemberDef *memb)
{
- PyObject *dict = type->tp_dict;
- for (; memb->name != NULL; memb++) {
- PyObject *descr;
- descr = PyDescr_NewMember(type, memb);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, memb->name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ for (; memb->name != NULL; memb++) {
+ PyObject *descr;
+ descr = PyDescr_NewMember(type, memb);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, memb->name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
*/
static int
add_getset(PyTypeObject *type, PyGetSetDef *gsp)
{
- PyObject *dict = type->tp_dict;
- for (; gsp->name != NULL; gsp++) {
- PyObject *descr;
- descr = PyDescr_NewGetSet(type, gsp);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ for (; gsp->name != NULL; gsp++) {
+ PyObject *descr;
+ descr = PyDescr_NewGetSet(type, gsp);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
static PyCArgObject *
PyCArrayType_paramfunc(CDataObject *self)
{
- PyCArgObject *p = PyCArgObject_new();
- if (p == NULL)
- return NULL;
- p->tag = 'P';
- p->pffi_type = &ffi_type_pointer;
- p->value.p = (char *)self->b_ptr;
- Py_INCREF(self);
- p->obj = (PyObject *)self;
- return p;
+ PyCArgObject *p = PyCArgObject_new();
+ if (p == NULL)
+ return NULL;
+ p->tag = 'P';
+ p->pffi_type = &ffi_type_pointer;
+ p->value.p = (char *)self->b_ptr;
+ Py_INCREF(self);
+ p->obj = (PyObject *)self;
+ return p;
}
static PyObject *
PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- StgDictObject *itemdict;
- PyObject *proto;
- PyObject *typedict;
- long length;
- int overflow;
- Py_ssize_t itemsize, itemalign;
- char buf[32];
-
- typedict = PyTuple_GetItem(args, 2);
- if (!typedict)
- return NULL;
-
- proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
- if (!proto || !PyLong_Check(proto)) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_length_' attribute, "
- "which must be a positive integer");
- return NULL;
- }
- length = PyLong_AsLongAndOverflow(proto, &overflow);
- if (overflow) {
- PyErr_SetString(PyExc_OverflowError,
- "The '_length_' attribute is too large");
- return NULL;
- }
-
- proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
- if (!proto) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_type_' attribute");
- return NULL;
- }
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- return NULL;
-
- itemdict = PyType_stgdict(proto);
- if (!itemdict) {
- PyErr_SetString(PyExc_TypeError,
- "_type_ must have storage info");
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- assert(itemdict->format);
- if (itemdict->format[0] == '(') {
- sprintf(buf, "(%ld,", length);
- stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1);
- } else {
- sprintf(buf, "(%ld)", length);
- stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format);
- }
- if (stgdict->format == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- stgdict->ndim = itemdict->ndim + 1;
- stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim);
- if (stgdict->shape == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- stgdict->shape[0] = length;
- memmove(&stgdict->shape[1], itemdict->shape,
- sizeof(Py_ssize_t) * (stgdict->ndim - 1));
-
- itemsize = itemdict->size;
- if (length * itemsize < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "array too large");
- return NULL;
- }
-
- itemalign = itemdict->align;
-
- if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
- stgdict->flags |= TYPEFLAG_HASPOINTER;
-
- stgdict->size = itemsize * length;
- stgdict->align = itemalign;
- stgdict->length = length;
- Py_INCREF(proto);
- stgdict->proto = proto;
-
- stgdict->paramfunc = &PyCArrayType_paramfunc;
-
- /* Arrays are passed as pointers to function calls. */
- stgdict->ffi_type_pointer = ffi_type_pointer;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL)
- return NULL;
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- /* Special case for character arrays.
- A permanent annoyance: char arrays are also strings!
- */
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- if (-1 == add_getset(result, CharArray_getsets))
- return NULL;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ StgDictObject *itemdict;
+ PyObject *proto;
+ PyObject *typedict;
+ long length;
+ int overflow;
+ Py_ssize_t itemsize, itemalign;
+ char buf[32];
+
+ typedict = PyTuple_GetItem(args, 2);
+ if (!typedict)
+ return NULL;
+
+ proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
+ if (!proto || !PyLong_Check(proto)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_length_' attribute, "
+ "which must be a positive integer");
+ return NULL;
+ }
+ length = PyLong_AsLongAndOverflow(proto, &overflow);
+ if (overflow) {
+ PyErr_SetString(PyExc_OverflowError,
+ "The '_length_' attribute is too large");
+ return NULL;
+ }
+
+ proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
+ if (!proto) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_type_' attribute");
+ return NULL;
+ }
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+
+ itemdict = PyType_stgdict(proto);
+ if (!itemdict) {
+ PyErr_SetString(PyExc_TypeError,
+ "_type_ must have storage info");
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ assert(itemdict->format);
+ if (itemdict->format[0] == '(') {
+ sprintf(buf, "(%ld,", length);
+ stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1);
+ } else {
+ sprintf(buf, "(%ld)", length);
+ stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format);
+ }
+ if (stgdict->format == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ stgdict->ndim = itemdict->ndim + 1;
+ stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim);
+ if (stgdict->shape == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ stgdict->shape[0] = length;
+ memmove(&stgdict->shape[1], itemdict->shape,
+ sizeof(Py_ssize_t) * (stgdict->ndim - 1));
+
+ itemsize = itemdict->size;
+ if (length * itemsize < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "array too large");
+ return NULL;
+ }
+
+ itemalign = itemdict->align;
+
+ if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
+ stgdict->flags |= TYPEFLAG_HASPOINTER;
+
+ stgdict->size = itemsize * length;
+ stgdict->align = itemalign;
+ stgdict->length = length;
+ Py_INCREF(proto);
+ stgdict->proto = proto;
+
+ stgdict->paramfunc = &PyCArrayType_paramfunc;
+
+ /* Arrays are passed as pointers to function calls. */
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL)
+ return NULL;
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ /* Special case for character arrays.
+ A permanent annoyance: char arrays are also strings!
+ */
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ if (-1 == add_getset(result, CharArray_getsets))
+ return NULL;
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- if (-1 == add_getset(result, WCharArray_getsets))
- return NULL;
+ } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ if (-1 == add_getset(result, WCharArray_getsets))
+ return NULL;
#endif
- }
+ }
- return (PyObject *)result;
+ return (PyObject *)result;
}
PyTypeObject PyCArrayType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCArrayType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 */
- "metatype for the Array Objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCArrayType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCArrayType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 */
+ "metatype for the Array Objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCArrayType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCSimpleType_Type
@@ -1444,273 +1444,273 @@ static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g";
static PyObject *
c_wchar_p_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyUnicode_Check(value) || PyBytes_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("Z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'Z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
- if (PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
- if (ArrayObject_Check(value) || PointerObject_Check(value)) {
- /* c_wchar array instance or pointer(c_wchar(...)) */
- StgDictObject *dt = PyObject_stgdict(value);
- StgDictObject *dict;
- assert(dt); /* Cannot be NULL for pointer or array objects */
- dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
- if (PyCArg_CheckExact(value)) {
- /* byref(c_char(...)) */
- PyCArgObject *a = (PyCArgObject *)value;
- StgDictObject *dict = PyObject_stgdict(a->obj);
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = c_wchar_p_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- /* XXX better message */
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ PyObject *as_parameter;
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyUnicode_Check(value) || PyBytes_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("Z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'Z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
+ if (PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ if (ArrayObject_Check(value) || PointerObject_Check(value)) {
+ /* c_wchar array instance or pointer(c_wchar(...)) */
+ StgDictObject *dt = PyObject_stgdict(value);
+ StgDictObject *dict;
+ assert(dt); /* Cannot be NULL for pointer or array objects */
+ dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+ if (PyCArg_CheckExact(value)) {
+ /* byref(c_char(...)) */
+ PyCArgObject *a = (PyCArgObject *)value;
+ StgDictObject *dict = PyObject_stgdict(a->obj);
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = c_wchar_p_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ /* XXX better message */
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyObject *
c_char_p_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyBytes_Check(value) || PyUnicode_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
- if (PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
- if (ArrayObject_Check(value) || PointerObject_Check(value)) {
- /* c_char array instance or pointer(c_char(...)) */
- StgDictObject *dt = PyObject_stgdict(value);
- StgDictObject *dict;
- assert(dt); /* Cannot be NULL for pointer or array objects */
- dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
- if (PyCArg_CheckExact(value)) {
- /* byref(c_char(...)) */
- PyCArgObject *a = (PyCArgObject *)value;
- StgDictObject *dict = PyObject_stgdict(a->obj);
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = c_char_p_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- /* XXX better message */
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ PyObject *as_parameter;
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyBytes_Check(value) || PyUnicode_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
+ if (PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ if (ArrayObject_Check(value) || PointerObject_Check(value)) {
+ /* c_char array instance or pointer(c_char(...)) */
+ StgDictObject *dt = PyObject_stgdict(value);
+ StgDictObject *dict;
+ assert(dt); /* Cannot be NULL for pointer or array objects */
+ dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+ if (PyCArg_CheckExact(value)) {
+ /* byref(c_char(...)) */
+ PyCArgObject *a = (PyCArgObject *)value;
+ StgDictObject *dict = PyObject_stgdict(a->obj);
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = c_char_p_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ /* XXX better message */
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyObject *
c_void_p_from_param(PyObject *type, PyObject *value)
{
- StgDictObject *stgd;
- PyObject *as_parameter;
+ StgDictObject *stgd;
+ PyObject *as_parameter;
/* None */
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- /* Should probably allow buffer interface as well */
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ /* Should probably allow buffer interface as well */
/* int, long */
- if (PyLong_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("P");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'P';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
- /* XXX struni: remove later */
+ if (PyLong_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("P");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'P';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
+ /* XXX struni: remove later */
/* string */
- if (PyBytes_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
+ if (PyBytes_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
/* bytes */
- if (PyByteArray_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
+ if (PyByteArray_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
/* unicode */
- if (PyUnicode_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("Z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'Z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
+ if (PyUnicode_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("Z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'Z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
/* c_void_p instance (or subclass) */
- if (PyObject_IsInstance(value, type)) {
- /* c_void_p instances */
- Py_INCREF(value);
- return value;
- }
+ if (PyObject_IsInstance(value, type)) {
+ /* c_void_p instances */
+ Py_INCREF(value);
+ return value;
+ }
/* ctypes array or pointer instance */
- if (ArrayObject_Check(value) || PointerObject_Check(value)) {
- /* Any array or pointer is accepted */
- Py_INCREF(value);
- return value;
- }
+ if (ArrayObject_Check(value) || PointerObject_Check(value)) {
+ /* Any array or pointer is accepted */
+ Py_INCREF(value);
+ return value;
+ }
/* byref(...) */
- if (PyCArg_CheckExact(value)) {
- /* byref(c_xxx()) */
- PyCArgObject *a = (PyCArgObject *)value;
- if (a->tag == 'P') {
- Py_INCREF(value);
- return value;
- }
- }
+ if (PyCArg_CheckExact(value)) {
+ /* byref(c_xxx()) */
+ PyCArgObject *a = (PyCArgObject *)value;
+ if (a->tag == 'P') {
+ Py_INCREF(value);
+ return value;
+ }
+ }
/* function pointer */
- if (PyCFuncPtrObject_Check(value)) {
- PyCArgObject *parg;
- PyCFuncPtrObject *func;
- func = (PyCFuncPtrObject *)value;
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'P';
- Py_INCREF(value);
- parg->value.p = *(void **)func->b_ptr;
- parg->obj = value;
- return (PyObject *)parg;
- }
+ if (PyCFuncPtrObject_Check(value)) {
+ PyCArgObject *parg;
+ PyCFuncPtrObject *func;
+ func = (PyCFuncPtrObject *)value;
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'P';
+ Py_INCREF(value);
+ parg->value.p = *(void **)func->b_ptr;
+ parg->obj = value;
+ return (PyObject *)parg;
+ }
/* c_char_p, c_wchar_p */
- stgd = PyObject_stgdict(value);
- if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) {
- PyCArgObject *parg;
-
- switch (_PyUnicode_AsString(stgd->proto)[0]) {
- case 'z': /* c_char_p */
- case 'Z': /* c_wchar_p */
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'Z';
- Py_INCREF(value);
- parg->obj = value;
- /* Remember: b_ptr points to where the pointer is stored! */
- parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
- return (PyObject *)parg;
- }
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = c_void_p_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- /* XXX better message */
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ stgd = PyObject_stgdict(value);
+ if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) {
+ PyCArgObject *parg;
+
+ switch (_PyUnicode_AsString(stgd->proto)[0]) {
+ case 'z': /* c_char_p */
+ case 'Z': /* c_wchar_p */
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'Z';
+ Py_INCREF(value);
+ parg->obj = value;
+ /* Remember: b_ptr points to where the pointer is stored! */
+ parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
+ return (PyObject *)parg;
+ }
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = c_void_p_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ /* XXX better message */
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O };
@@ -1718,278 +1718,278 @@ static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_O
static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O };
static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds,
- PyObject *proto, struct fielddesc *fmt)
+ PyObject *proto, struct fielddesc *fmt)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- PyObject *name = PyTuple_GET_ITEM(args, 0);
- PyObject *newname;
- PyObject *swapped_args;
- static PyObject *suffix;
- Py_ssize_t i;
-
- swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
- if (!swapped_args)
- return NULL;
-
- if (suffix == NULL)
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ PyObject *name = PyTuple_GET_ITEM(args, 0);
+ PyObject *newname;
+ PyObject *swapped_args;
+ static PyObject *suffix;
+ Py_ssize_t i;
+
+ swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
+ if (!swapped_args)
+ return NULL;
+
+ if (suffix == NULL)
#ifdef WORDS_BIGENDIAN
- suffix = PyUnicode_InternFromString("_le");
+ suffix = PyUnicode_InternFromString("_le");
#else
- suffix = PyUnicode_InternFromString("_be");
+ suffix = PyUnicode_InternFromString("_be");
#endif
- newname = PyUnicode_Concat(name, suffix);
- if (newname == NULL) {
- return NULL;
- }
-
- PyTuple_SET_ITEM(swapped_args, 0, newname);
- for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
- PyObject *v = PyTuple_GET_ITEM(args, i);
- Py_INCREF(v);
- PyTuple_SET_ITEM(swapped_args, i, v);
- }
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
- Py_DECREF(swapped_args);
- if (result == NULL)
- return NULL;
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict) /* XXX leaks result! */
- return NULL;
-
- stgdict->ffi_type_pointer = *fmt->pffi_type;
- stgdict->align = fmt->pffi_type->alignment;
- stgdict->length = 0;
- stgdict->size = fmt->pffi_type->size;
- stgdict->setfunc = fmt->setfunc_swapped;
- stgdict->getfunc = fmt->getfunc_swapped;
-
- Py_INCREF(proto);
- stgdict->proto = proto;
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- return (PyObject *)result;
+ newname = PyUnicode_Concat(name, suffix);
+ if (newname == NULL) {
+ return NULL;
+ }
+
+ PyTuple_SET_ITEM(swapped_args, 0, newname);
+ for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
+ PyObject *v = PyTuple_GET_ITEM(args, i);
+ Py_INCREF(v);
+ PyTuple_SET_ITEM(swapped_args, i, v);
+ }
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
+ Py_DECREF(swapped_args);
+ if (result == NULL)
+ return NULL;
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict) /* XXX leaks result! */
+ return NULL;
+
+ stgdict->ffi_type_pointer = *fmt->pffi_type;
+ stgdict->align = fmt->pffi_type->alignment;
+ stgdict->length = 0;
+ stgdict->size = fmt->pffi_type->size;
+ stgdict->setfunc = fmt->setfunc_swapped;
+ stgdict->getfunc = fmt->getfunc_swapped;
+
+ Py_INCREF(proto);
+ stgdict->proto = proto;
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ return (PyObject *)result;
}
static PyCArgObject *
PyCSimpleType_paramfunc(CDataObject *self)
{
- StgDictObject *dict;
- char *fmt;
- PyCArgObject *parg;
- struct fielddesc *fd;
-
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CDataObject instances */
- fmt = _PyUnicode_AsString(dict->proto);
- assert(fmt);
-
- fd = _ctypes_get_fielddesc(fmt);
- assert(fd);
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = fmt[0];
- parg->pffi_type = fd->pffi_type;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- memcpy(&parg->value, self->b_ptr, self->b_size);
- return parg;
+ StgDictObject *dict;
+ char *fmt;
+ PyCArgObject *parg;
+ struct fielddesc *fd;
+
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ fmt = _PyUnicode_AsString(dict->proto);
+ assert(fmt);
+
+ fd = _ctypes_get_fielddesc(fmt);
+ assert(fd);
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = fmt[0];
+ parg->pffi_type = fd->pffi_type;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ memcpy(&parg->value, self->b_ptr, self->b_size);
+ return parg;
}
static PyObject *
PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- PyObject *proto;
- const char *proto_str;
- Py_ssize_t proto_len;
- PyMethodDef *ml;
- struct fielddesc *fmt;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL)
- return NULL;
-
- proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
- if (!proto) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_type_' attribute");
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ PyObject *proto;
+ const char *proto_str;
+ Py_ssize_t proto_len;
+ PyMethodDef *ml;
+ struct fielddesc *fmt;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL)
+ return NULL;
+
+ proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
+ if (!proto) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_type_' attribute");
error:
- Py_XDECREF(proto);
- Py_XDECREF(result);
- return NULL;
- }
- if (PyUnicode_Check(proto)) {
- PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL);
- if (!v)
- goto error;
- proto_str = PyBytes_AS_STRING(v);
- proto_len = PyBytes_GET_SIZE(v);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "class must define a '_type_' string attribute");
- goto error;
- }
- if (proto_len != 1) {
- PyErr_SetString(PyExc_ValueError,
- "class must define a '_type_' attribute "
- "which must be a string of length 1");
- goto error;
- }
- if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
- PyErr_Format(PyExc_AttributeError,
- "class must define a '_type_' attribute which must be\n"
- "a single character string containing one of '%s'.",
- SIMPLE_TYPE_CHARS);
- goto error;
- }
- fmt = _ctypes_get_fielddesc(proto_str);
- if (fmt == NULL) {
- PyErr_Format(PyExc_ValueError,
- "_type_ '%s' not supported", proto_str);
- goto error;
- }
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- goto error;
-
- stgdict->ffi_type_pointer = *fmt->pffi_type;
- stgdict->align = fmt->pffi_type->alignment;
- stgdict->length = 0;
- stgdict->size = fmt->pffi_type->size;
- stgdict->setfunc = fmt->setfunc;
- stgdict->getfunc = fmt->getfunc;
+ Py_XDECREF(proto);
+ Py_XDECREF(result);
+ return NULL;
+ }
+ if (PyUnicode_Check(proto)) {
+ PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL);
+ if (!v)
+ goto error;
+ proto_str = PyBytes_AS_STRING(v);
+ proto_len = PyBytes_GET_SIZE(v);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "class must define a '_type_' string attribute");
+ goto error;
+ }
+ if (proto_len != 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "class must define a '_type_' attribute "
+ "which must be a string of length 1");
+ goto error;
+ }
+ if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
+ PyErr_Format(PyExc_AttributeError,
+ "class must define a '_type_' attribute which must be\n"
+ "a single character string containing one of '%s'.",
+ SIMPLE_TYPE_CHARS);
+ goto error;
+ }
+ fmt = _ctypes_get_fielddesc(proto_str);
+ if (fmt == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "_type_ '%s' not supported", proto_str);
+ goto error;
+ }
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ goto error;
+
+ stgdict->ffi_type_pointer = *fmt->pffi_type;
+ stgdict->align = fmt->pffi_type->alignment;
+ stgdict->length = 0;
+ stgdict->size = fmt->pffi_type->size;
+ stgdict->setfunc = fmt->setfunc;
+ stgdict->getfunc = fmt->getfunc;
#ifdef WORDS_BIGENDIAN
- stgdict->format = _ctypes_alloc_format_string(">", proto_str);
+ stgdict->format = _ctypes_alloc_format_string(">", proto_str);
#else
- stgdict->format = _ctypes_alloc_format_string("<", proto_str);
+ stgdict->format = _ctypes_alloc_format_string("<", proto_str);
#endif
- if (stgdict->format == NULL) {
- Py_DECREF(result);
- Py_DECREF(proto);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- stgdict->paramfunc = PyCSimpleType_paramfunc;
+ if (stgdict->format == NULL) {
+ Py_DECREF(result);
+ Py_DECREF(proto);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ stgdict->paramfunc = PyCSimpleType_paramfunc;
/*
- if (result->tp_base != &Simple_Type) {
- stgdict->setfunc = NULL;
- stgdict->getfunc = NULL;
- }
+ if (result->tp_base != &Simple_Type) {
+ stgdict->setfunc = NULL;
+ stgdict->getfunc = NULL;
+ }
*/
- /* This consumes the refcount on proto which we have */
- stgdict->proto = proto;
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- /* Install from_param class methods in ctypes base classes.
- Overrides the PyCSimpleType_from_param generic method.
- */
- if (result->tp_base == &Simple_Type) {
- switch (*proto_str) {
- case 'z': /* c_char_p */
- ml = &c_char_p_method;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- case 'Z': /* c_wchar_p */
- ml = &c_wchar_p_method;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- case 'P': /* c_void_p */
- ml = &c_void_p_method;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- case 's':
- case 'X':
- case 'O':
- ml = NULL;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- default:
- ml = NULL;
- break;
- }
-
- if (ml) {
- PyObject *meth;
- int x;
- meth = PyDescr_NewClassMethod(result, ml);
- if (!meth)
- return NULL;
- x = PyDict_SetItemString(result->tp_dict,
- ml->ml_name,
- meth);
- Py_DECREF(meth);
- if (x == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- }
-
- if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) {
- PyObject *swapped = CreateSwappedType(type, args, kwds,
- proto, fmt);
- StgDictObject *sw_dict;
- if (swapped == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- sw_dict = PyType_stgdict(swapped);
+ /* This consumes the refcount on proto which we have */
+ stgdict->proto = proto;
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ /* Install from_param class methods in ctypes base classes.
+ Overrides the PyCSimpleType_from_param generic method.
+ */
+ if (result->tp_base == &Simple_Type) {
+ switch (*proto_str) {
+ case 'z': /* c_char_p */
+ ml = &c_char_p_method;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ case 'Z': /* c_wchar_p */
+ ml = &c_wchar_p_method;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ case 'P': /* c_void_p */
+ ml = &c_void_p_method;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ case 's':
+ case 'X':
+ case 'O':
+ ml = NULL;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ default:
+ ml = NULL;
+ break;
+ }
+
+ if (ml) {
+ PyObject *meth;
+ int x;
+ meth = PyDescr_NewClassMethod(result, ml);
+ if (!meth)
+ return NULL;
+ x = PyDict_SetItemString(result->tp_dict,
+ ml->ml_name,
+ meth);
+ Py_DECREF(meth);
+ if (x == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ }
+
+ if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) {
+ PyObject *swapped = CreateSwappedType(type, args, kwds,
+ proto, fmt);
+ StgDictObject *sw_dict;
+ if (swapped == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ sw_dict = PyType_stgdict(swapped);
#ifdef WORDS_BIGENDIAN
- PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped);
- PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
- /* We are creating the type for the OTHER endian */
- sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
+ /* We are creating the type for the OTHER endian */
+ sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1);
#else
- PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped);
- PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
- /* We are creating the type for the OTHER endian */
- sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
+ /* We are creating the type for the OTHER endian */
+ sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1);
#endif
- Py_DECREF(swapped);
- if (PyErr_Occurred()) {
- Py_DECREF(result);
- return NULL;
- }
- };
-
- return (PyObject *)result;
+ Py_DECREF(swapped);
+ if (PyErr_Occurred()) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ };
+
+ return (PyObject *)result;
}
/*
@@ -1999,101 +1999,101 @@ PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
PyCSimpleType_from_param(PyObject *type, PyObject *value)
{
- StgDictObject *dict;
- char *fmt;
- PyCArgObject *parg;
- struct fielddesc *fd;
- PyObject *as_parameter;
-
- /* If the value is already an instance of the requested type,
- we can use it as is */
- if (1 == PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
-
- dict = PyType_stgdict(type);
- assert(dict);
-
- /* I think we can rely on this being a one-character string */
- fmt = _PyUnicode_AsString(dict->proto);
- assert(fmt);
-
- fd = _ctypes_get_fielddesc(fmt);
- assert(fd);
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = fmt[0];
- parg->pffi_type = fd->pffi_type;
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj)
- return (PyObject *)parg;
- PyErr_Clear();
- Py_DECREF(parg);
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = PyCSimpleType_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ StgDictObject *dict;
+ char *fmt;
+ PyCArgObject *parg;
+ struct fielddesc *fd;
+ PyObject *as_parameter;
+
+ /* If the value is already an instance of the requested type,
+ we can use it as is */
+ if (1 == PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+
+ dict = PyType_stgdict(type);
+ assert(dict);
+
+ /* I think we can rely on this being a one-character string */
+ fmt = _PyUnicode_AsString(dict->proto);
+ assert(fmt);
+
+ fd = _ctypes_get_fielddesc(fmt);
+ assert(fd);
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = fmt[0];
+ parg->pffi_type = fd->pffi_type;
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj)
+ return (PyObject *)parg;
+ PyErr_Clear();
+ Py_DECREF(parg);
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = PyCSimpleType_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyMethodDef PyCSimpleType_methods[] = {
- { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc },
- { "from_address", CDataType_from_address, METH_O, from_address_doc },
- { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
- { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
- { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
- { NULL, NULL },
+ { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc },
+ { "from_address", CDataType_from_address, METH_O, from_address_doc },
+ { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
+ { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
+ { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
+ { NULL, NULL },
};
PyTypeObject PyCSimpleType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCSimpleType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 */
- "metatype for the PyCSimpleType Objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyCSimpleType_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCSimpleType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCSimpleType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 */
+ "metatype for the PyCSimpleType Objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyCSimpleType_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCSimpleType_new, /* tp_new */
+ 0, /* tp_free */
};
/******************************************************************/
@@ -2104,217 +2104,217 @@ PyTypeObject PyCSimpleType_Type = {
static PyObject *
converters_from_argtypes(PyObject *ob)
{
- PyObject *converters;
- Py_ssize_t i;
- Py_ssize_t nArgs;
-
- ob = PySequence_Tuple(ob); /* new reference */
- if (!ob) {
- PyErr_SetString(PyExc_TypeError,
- "_argtypes_ must be a sequence of types");
- return NULL;
- }
-
- nArgs = PyTuple_GET_SIZE(ob);
- converters = PyTuple_New(nArgs);
- if (!converters)
- return NULL;
-
- /* I have to check if this is correct. Using c_char, which has a size
- of 1, will be assumed to be pushed as only one byte!
- Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
- */
-
- for (i = 0; i < nArgs; ++i) {
- PyObject *tp = PyTuple_GET_ITEM(ob, i);
- PyObject *cnv = PyObject_GetAttrString(tp, "from_param");
- if (!cnv)
- goto argtypes_error_1;
- PyTuple_SET_ITEM(converters, i, cnv);
- }
- Py_DECREF(ob);
- return converters;
+ PyObject *converters;
+ Py_ssize_t i;
+ Py_ssize_t nArgs;
+
+ ob = PySequence_Tuple(ob); /* new reference */
+ if (!ob) {
+ PyErr_SetString(PyExc_TypeError,
+ "_argtypes_ must be a sequence of types");
+ return NULL;
+ }
+
+ nArgs = PyTuple_GET_SIZE(ob);
+ converters = PyTuple_New(nArgs);
+ if (!converters)
+ return NULL;
+
+ /* I have to check if this is correct. Using c_char, which has a size
+ of 1, will be assumed to be pushed as only one byte!
+ Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
+ */
+
+ for (i = 0; i < nArgs; ++i) {
+ PyObject *tp = PyTuple_GET_ITEM(ob, i);
+ PyObject *cnv = PyObject_GetAttrString(tp, "from_param");
+ if (!cnv)
+ goto argtypes_error_1;
+ PyTuple_SET_ITEM(converters, i, cnv);
+ }
+ Py_DECREF(ob);
+ return converters;
argtypes_error_1:
- Py_XDECREF(converters);
- Py_DECREF(ob);
- PyErr_Format(PyExc_TypeError,
- "item %zd in _argtypes_ has no from_param method",
- i+1);
- return NULL;
+ Py_XDECREF(converters);
+ Py_DECREF(ob);
+ PyErr_Format(PyExc_TypeError,
+ "item %zd in _argtypes_ has no from_param method",
+ i+1);
+ return NULL;
}
static int
make_funcptrtype_dict(StgDictObject *stgdict)
{
- PyObject *ob;
- PyObject *converters = NULL;
-
- stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
- stgdict->length = 1;
- stgdict->size = sizeof(void *);
- stgdict->setfunc = NULL;
- stgdict->getfunc = NULL;
- stgdict->ffi_type_pointer = ffi_type_pointer;
-
- ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
- if (!ob || !PyLong_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "class must define _flags_ which must be an integer");
- return -1;
- }
- stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER;
-
- /* _argtypes_ is optional... */
- ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_");
- if (ob) {
- converters = converters_from_argtypes(ob);
- if (!converters)
- goto error;
- Py_INCREF(ob);
- stgdict->argtypes = ob;
- stgdict->converters = converters;
- }
-
- ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_");
- if (ob) {
- if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "_restype_ must be a type, a callable, or None");
- return -1;
- }
- Py_INCREF(ob);
- stgdict->restype = ob;
- stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_");
- if (stgdict->checker == NULL)
- PyErr_Clear();
- }
+ PyObject *ob;
+ PyObject *converters = NULL;
+
+ stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
+ stgdict->length = 1;
+ stgdict->size = sizeof(void *);
+ stgdict->setfunc = NULL;
+ stgdict->getfunc = NULL;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
+ if (!ob || !PyLong_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "class must define _flags_ which must be an integer");
+ return -1;
+ }
+ stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER;
+
+ /* _argtypes_ is optional... */
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_");
+ if (ob) {
+ converters = converters_from_argtypes(ob);
+ if (!converters)
+ goto error;
+ Py_INCREF(ob);
+ stgdict->argtypes = ob;
+ stgdict->converters = converters;
+ }
+
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_");
+ if (ob) {
+ if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_restype_ must be a type, a callable, or None");
+ return -1;
+ }
+ Py_INCREF(ob);
+ stgdict->restype = ob;
+ stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_");
+ if (stgdict->checker == NULL)
+ PyErr_Clear();
+ }
/* XXX later, maybe.
- ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
- if (ob) {
- if (!PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "_errcheck_ must be callable");
- return -1;
- }
- Py_INCREF(ob);
- stgdict->errcheck = ob;
- }
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
+ if (ob) {
+ if (!PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_errcheck_ must be callable");
+ return -1;
+ }
+ Py_INCREF(ob);
+ stgdict->errcheck = ob;
+ }
*/
- return 0;
+ return 0;
error:
- Py_XDECREF(converters);
- return -1;
+ Py_XDECREF(converters);
+ return -1;
}
static PyCArgObject *
PyCFuncPtrType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- parg->value.p = *(void **)self->b_ptr;
- return parg;
+ PyCArgObject *parg;
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ parg->value.p = *(void **)self->b_ptr;
+ return parg;
}
static PyObject *
PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- return NULL;
-
- stgdict->paramfunc = PyCFuncPtrType_paramfunc;
- /* We do NOT expose the function signature in the format string. It
- is impossible, generally, because the only requirement for the
- argtypes items is that they have a .from_param method - we do not
- know the types of the arguments (although, in practice, most
- argtypes would be a ctypes type).
- */
- stgdict->format = _ctypes_alloc_format_string(NULL, "X{}");
- stgdict->flags |= TYPEFLAG_ISPOINTER;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- /* replace the class dict by our updated storage dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- if (-1 == make_funcptrtype_dict(stgdict)) {
- Py_DECREF(result);
- return NULL;
- }
-
- return (PyObject *)result;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+
+ stgdict->paramfunc = PyCFuncPtrType_paramfunc;
+ /* We do NOT expose the function signature in the format string. It
+ is impossible, generally, because the only requirement for the
+ argtypes items is that they have a .from_param method - we do not
+ know the types of the arguments (although, in practice, most
+ argtypes would be a ctypes type).
+ */
+ stgdict->format = _ctypes_alloc_format_string(NULL, "X{}");
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ /* replace the class dict by our updated storage dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ if (-1 == make_funcptrtype_dict(stgdict)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
}
PyTypeObject PyCFuncPtrType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCFuncPtrType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for C function pointers", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCFuncPtrType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCFuncPtrType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for C function pointers", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCFuncPtrType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/*****************************************************************
* Code to keep needed objects alive
*/
@@ -2322,46 +2322,46 @@ PyTypeObject PyCFuncPtrType_Type = {
static CDataObject *
PyCData_GetContainer(CDataObject *self)
{
- while (self->b_base)
- self = self->b_base;
- if (self->b_objects == NULL) {
- if (self->b_length) {
- self->b_objects = PyDict_New();
- } else {
- Py_INCREF(Py_None);
- self->b_objects = Py_None;
- }
- }
- return self;
+ while (self->b_base)
+ self = self->b_base;
+ if (self->b_objects == NULL) {
+ if (self->b_length) {
+ self->b_objects = PyDict_New();
+ } else {
+ Py_INCREF(Py_None);
+ self->b_objects = Py_None;
+ }
+ }
+ return self;
}
static PyObject *
GetKeepedObjects(CDataObject *target)
{
- return PyCData_GetContainer(target)->b_objects;
+ return PyCData_GetContainer(target)->b_objects;
}
static PyObject *
unique_key(CDataObject *target, Py_ssize_t index)
{
- char string[256];
- char *cp = string;
- size_t bytes_left;
-
- assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
- cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
- while (target->b_base) {
- bytes_left = sizeof(string) - (cp - string) - 1;
- /* Hex format needs 2 characters per byte */
- if (bytes_left < sizeof(Py_ssize_t) * 2) {
- PyErr_SetString(PyExc_ValueError,
- "ctypes object structure too deep");
- return NULL;
- }
- cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
- target = target->b_base;
- }
- return PyUnicode_FromStringAndSize(string, cp-string);
+ char string[256];
+ char *cp = string;
+ size_t bytes_left;
+
+ assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
+ cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
+ while (target->b_base) {
+ bytes_left = sizeof(string) - (cp - string) - 1;
+ /* Hex format needs 2 characters per byte */
+ if (bytes_left < sizeof(Py_ssize_t) * 2) {
+ PyErr_SetString(PyExc_ValueError,
+ "ctypes object structure too deep");
+ return NULL;
+ }
+ cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
+ target = target->b_base;
+ }
+ return PyUnicode_FromStringAndSize(string, cp-string);
}
/*
@@ -2385,30 +2385,30 @@ unique_key(CDataObject *target, Py_ssize_t index)
static int
KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
{
- int result;
- CDataObject *ob;
- PyObject *key;
+ int result;
+ CDataObject *ob;
+ PyObject *key;
/* Optimization: no need to store None */
- if (keep == Py_None) {
- Py_DECREF(Py_None);
- return 0;
- }
- ob = PyCData_GetContainer(target);
- if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
- Py_XDECREF(ob->b_objects);
- ob->b_objects = keep; /* refcount consumed */
- return 0;
- }
- key = unique_key(target, index);
- if (key == NULL) {
- Py_DECREF(keep);
- return -1;
- }
- result = PyDict_SetItem(ob->b_objects, key, keep);
- Py_DECREF(key);
- Py_DECREF(keep);
- return result;
+ if (keep == Py_None) {
+ Py_DECREF(Py_None);
+ return 0;
+ }
+ ob = PyCData_GetContainer(target);
+ if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
+ Py_XDECREF(ob->b_objects);
+ ob->b_objects = keep; /* refcount consumed */
+ return 0;
+ }
+ key = unique_key(target, index);
+ if (key == NULL) {
+ Py_DECREF(keep);
+ return -1;
+ }
+ result = PyDict_SetItem(ob->b_objects, key, keep);
+ Py_DECREF(key);
+ Py_DECREF(keep);
+ return result;
}
/******************************************************************/
@@ -2418,75 +2418,75 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
static int
PyCData_traverse(CDataObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->b_objects);
- Py_VISIT((PyObject *)self->b_base);
- return 0;
+ Py_VISIT(self->b_objects);
+ Py_VISIT((PyObject *)self->b_base);
+ return 0;
}
static int
PyCData_clear(CDataObject *self)
{
- StgDictObject *dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CDataObject instances */
- Py_CLEAR(self->b_objects);
- if ((self->b_needsfree)
- && ((size_t)dict->size > sizeof(self->b_value)))
- PyMem_Free(self->b_ptr);
- self->b_ptr = NULL;
- Py_CLEAR(self->b_base);
- return 0;
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ Py_CLEAR(self->b_objects);
+ if ((self->b_needsfree)
+ && ((size_t)dict->size > sizeof(self->b_value)))
+ PyMem_Free(self->b_ptr);
+ self->b_ptr = NULL;
+ Py_CLEAR(self->b_base);
+ return 0;
}
static void
PyCData_dealloc(PyObject *self)
{
- PyCData_clear((CDataObject *)self);
- Py_TYPE(self)->tp_free(self);
+ PyCData_clear((CDataObject *)self);
+ Py_TYPE(self)->tp_free(self);
}
static PyMemberDef PyCData_members[] = {
- { "_b_base_", T_OBJECT,
- offsetof(CDataObject, b_base), READONLY,
- "the base object" },
- { "_b_needsfree_", T_INT,
- offsetof(CDataObject, b_needsfree), READONLY,
- "whether the object owns the memory or not" },
- { "_objects", T_OBJECT,
- offsetof(CDataObject, b_objects), READONLY,
- "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
- { NULL },
+ { "_b_base_", T_OBJECT,
+ offsetof(CDataObject, b_base), READONLY,
+ "the base object" },
+ { "_b_needsfree_", T_INT,
+ offsetof(CDataObject, b_needsfree), READONLY,
+ "whether the object owns the memory or not" },
+ { "_objects", T_OBJECT,
+ offsetof(CDataObject, b_objects), READONLY,
+ "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
+ { NULL },
};
static int PyCData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags)
{
- CDataObject *self = (CDataObject *)_self;
- StgDictObject *dict = PyObject_stgdict(_self);
- Py_ssize_t i;
-
- if (view == NULL) return 0;
-
- view->buf = self->b_ptr;
- view->obj = _self;
- Py_INCREF(_self);
- view->len = self->b_size;
- view->readonly = 0;
- /* use default format character if not set */
- view->format = dict->format ? dict->format : "B";
- view->ndim = dict->ndim;
- view->shape = dict->shape;
- view->itemsize = self->b_size;
- for (i = 0; i < view->ndim; ++i) {
- view->itemsize /= dict->shape[i];
- }
- view->strides = NULL;
- view->suboffsets = NULL;
- view->internal = NULL;
- return 0;
+ CDataObject *self = (CDataObject *)_self;
+ StgDictObject *dict = PyObject_stgdict(_self);
+ Py_ssize_t i;
+
+ if (view == NULL) return 0;
+
+ view->buf = self->b_ptr;
+ view->obj = _self;
+ Py_INCREF(_self);
+ view->len = self->b_size;
+ view->readonly = 0;
+ /* use default format character if not set */
+ view->format = dict->format ? dict->format : "B";
+ view->ndim = dict->ndim;
+ view->shape = dict->shape;
+ view->itemsize = self->b_size;
+ for (i = 0; i < view->ndim; ++i) {
+ view->itemsize /= dict->shape[i];
+ }
+ view->strides = NULL;
+ view->suboffsets = NULL;
+ view->internal = NULL;
+ return 0;
}
static PyBufferProcs PyCData_as_buffer = {
- PyCData_NewGetBuffer,
- NULL,
+ PyCData_NewGetBuffer,
+ NULL,
};
/*
@@ -2495,47 +2495,47 @@ static PyBufferProcs PyCData_as_buffer = {
static long
PyCData_nohash(PyObject *self)
{
- PyErr_SetString(PyExc_TypeError, "unhashable type");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "unhashable type");
+ return -1;
}
static PyObject *
PyCData_reduce(PyObject *_self, PyObject *args)
{
- CDataObject *self = (CDataObject *)_self;
-
- if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
- PyErr_SetString(PyExc_ValueError,
- "ctypes objects containing pointers cannot be pickled");
- return NULL;
- }
- return Py_BuildValue("O(O(NN))",
- _unpickle,
- Py_TYPE(_self),
- PyObject_GetAttrString(_self, "__dict__"),
- PyBytes_FromStringAndSize(self->b_ptr, self->b_size));
+ CDataObject *self = (CDataObject *)_self;
+
+ if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
+ PyErr_SetString(PyExc_ValueError,
+ "ctypes objects containing pointers cannot be pickled");
+ return NULL;
+ }
+ return Py_BuildValue("O(O(NN))",
+ _unpickle,
+ Py_TYPE(_self),
+ PyObject_GetAttrString(_self, "__dict__"),
+ PyBytes_FromStringAndSize(self->b_ptr, self->b_size));
}
static PyObject *
PyCData_setstate(PyObject *_self, PyObject *args)
{
- void *data;
- Py_ssize_t len;
- int res;
- PyObject *dict, *mydict;
- CDataObject *self = (CDataObject *)_self;
- if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len))
- return NULL;
- if (len > self->b_size)
- len = self->b_size;
- memmove(self->b_ptr, data, len);
- mydict = PyObject_GetAttrString(_self, "__dict__");
- res = PyDict_Update(mydict, dict);
- Py_DECREF(mydict);
- if (res == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ void *data;
+ Py_ssize_t len;
+ int res;
+ PyObject *dict, *mydict;
+ CDataObject *self = (CDataObject *)_self;
+ if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len))
+ return NULL;
+ if (len > self->b_size)
+ len = self->b_size;
+ memmove(self->b_ptr, data, len);
+ mydict = PyObject_GetAttrString(_self, "__dict__");
+ res = PyDict_Update(mydict, dict);
+ Py_DECREF(mydict);
+ if (res == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/*
@@ -2544,124 +2544,124 @@ PyCData_setstate(PyObject *_self, PyObject *args)
static PyObject *
PyCData_from_outparam(PyObject *self, PyObject *args)
{
- Py_INCREF(self);
- return self;
+ Py_INCREF(self);
+ return self;
}
static PyMethodDef PyCData_methods[] = {
- { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, },
- { "__reduce__", PyCData_reduce, METH_NOARGS, },
- { "__setstate__", PyCData_setstate, METH_VARARGS, },
- { NULL, NULL },
+ { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, },
+ { "__reduce__", PyCData_reduce, METH_NOARGS, },
+ { "__setstate__", PyCData_setstate, METH_VARARGS, },
+ { NULL, NULL },
};
PyTypeObject PyCData_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._CData",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- PyCData_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- PyCData_nohash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyCData_methods, /* tp_methods */
- PyCData_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes._CData",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ PyCData_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ PyCData_nohash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyCData_methods, /* tp_methods */
+ PyCData_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
{
- if ((size_t)dict->size <= sizeof(obj->b_value)) {
- /* No need to call malloc, can use the default buffer */
- obj->b_ptr = (char *)&obj->b_value;
- /* The b_needsfree flag does not mean that we actually did
- call PyMem_Malloc to allocate the memory block; instead it
- means we are the *owner* of the memory and are responsible
- for freeing resources associated with the memory. This is
- also the reason that b_needsfree is exposed to Python.
- */
- obj->b_needsfree = 1;
- } else {
- /* In python 2.4, and ctypes 0.9.6, the malloc call took about
- 33% of the creation time for c_int().
- */
- obj->b_ptr = (char *)PyMem_Malloc(dict->size);
- if (obj->b_ptr == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- obj->b_needsfree = 1;
- memset(obj->b_ptr, 0, dict->size);
- }
- obj->b_size = dict->size;
- return 0;
+ if ((size_t)dict->size <= sizeof(obj->b_value)) {
+ /* No need to call malloc, can use the default buffer */
+ obj->b_ptr = (char *)&obj->b_value;
+ /* The b_needsfree flag does not mean that we actually did
+ call PyMem_Malloc to allocate the memory block; instead it
+ means we are the *owner* of the memory and are responsible
+ for freeing resources associated with the memory. This is
+ also the reason that b_needsfree is exposed to Python.
+ */
+ obj->b_needsfree = 1;
+ } else {
+ /* In python 2.4, and ctypes 0.9.6, the malloc call took about
+ 33% of the creation time for c_int().
+ */
+ obj->b_ptr = (char *)PyMem_Malloc(dict->size);
+ if (obj->b_ptr == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ obj->b_needsfree = 1;
+ memset(obj->b_ptr, 0, dict->size);
+ }
+ obj->b_size = dict->size;
+ return 0;
}
PyObject *
PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
{
- CDataObject *cmem;
- StgDictObject *dict;
-
- assert(PyType_Check(type));
- dict = PyType_stgdict(type);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "abstract class");
- return NULL;
- }
- dict->flags |= DICTFLAG_FINAL;
- cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
- if (cmem == NULL)
- return NULL;
- assert(CDataObject_Check(cmem));
-
- cmem->b_length = dict->length;
- cmem->b_size = dict->size;
- if (base) { /* use base's buffer */
- assert(CDataObject_Check(base));
- cmem->b_ptr = adr;
- cmem->b_needsfree = 0;
- Py_INCREF(base);
- cmem->b_base = (CDataObject *)base;
- cmem->b_index = index;
- } else { /* copy contents of adr */
- if (-1 == PyCData_MallocBuffer(cmem, dict)) {
- return NULL;
- Py_DECREF(cmem);
- }
- memcpy(cmem->b_ptr, adr, dict->size);
- cmem->b_index = index;
- }
- return (PyObject *)cmem;
+ CDataObject *cmem;
+ StgDictObject *dict;
+
+ assert(PyType_Check(type));
+ dict = PyType_stgdict(type);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "abstract class");
+ return NULL;
+ }
+ dict->flags |= DICTFLAG_FINAL;
+ cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
+ if (cmem == NULL)
+ return NULL;
+ assert(CDataObject_Check(cmem));
+
+ cmem->b_length = dict->length;
+ cmem->b_size = dict->size;
+ if (base) { /* use base's buffer */
+ assert(CDataObject_Check(base));
+ cmem->b_ptr = adr;
+ cmem->b_needsfree = 0;
+ Py_INCREF(base);
+ cmem->b_base = (CDataObject *)base;
+ cmem->b_index = index;
+ } else { /* copy contents of adr */
+ if (-1 == PyCData_MallocBuffer(cmem, dict)) {
+ return NULL;
+ Py_DECREF(cmem);
+ }
+ memcpy(cmem->b_ptr, adr, dict->size);
+ cmem->b_index = index;
+ }
+ return (PyObject *)cmem;
}
/*
@@ -2670,26 +2670,26 @@ PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
PyObject *
PyCData_AtAddress(PyObject *type, void *buf)
{
- CDataObject *pd;
- StgDictObject *dict;
-
- assert(PyType_Check(type));
- dict = PyType_stgdict(type);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "abstract class");
- return NULL;
- }
- dict->flags |= DICTFLAG_FINAL;
-
- pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
- if (!pd)
- return NULL;
- assert(CDataObject_Check(pd));
- pd->b_ptr = (char *)buf;
- pd->b_length = dict->length;
- pd->b_size = dict->size;
- return (PyObject *)pd;
+ CDataObject *pd;
+ StgDictObject *dict;
+
+ assert(PyType_Check(type));
+ dict = PyType_stgdict(type);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "abstract class");
+ return NULL;
+ }
+ dict->flags |= DICTFLAG_FINAL;
+
+ pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
+ if (!pd)
+ return NULL;
+ assert(CDataObject_Check(pd));
+ pd->b_ptr = (char *)buf;
+ pd->b_length = dict->length;
+ pd->b_size = dict->size;
+ return (PyObject *)pd;
}
/*
@@ -2699,25 +2699,25 @@ PyCData_AtAddress(PyObject *type, void *buf)
*/
int _ctypes_simple_instance(PyObject *obj)
{
- PyTypeObject *type = (PyTypeObject *)obj;
+ PyTypeObject *type = (PyTypeObject *)obj;
- if (PyCSimpleTypeObject_Check(type))
- return type->tp_base != &Simple_Type;
- return 0;
+ if (PyCSimpleTypeObject_Check(type))
+ return type->tp_base != &Simple_Type;
+ return 0;
}
PyObject *
PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
- Py_ssize_t index, Py_ssize_t size, char *adr)
+ Py_ssize_t index, Py_ssize_t size, char *adr)
{
- StgDictObject *dict;
- if (getfunc)
- return getfunc(adr, size);
- assert(type);
- dict = PyType_stgdict(type);
- if (dict && dict->getfunc && !_ctypes_simple_instance(type))
- return dict->getfunc(adr, size);
- return PyCData_FromBaseObj(type, src, index, adr);
+ StgDictObject *dict;
+ if (getfunc)
+ return getfunc(adr, size);
+ assert(type);
+ dict = PyType_stgdict(type);
+ if (dict && dict->getfunc && !_ctypes_simple_instance(type))
+ return dict->getfunc(adr, size);
+ return PyCData_FromBaseObj(type, src, index, adr);
}
/*
@@ -2725,96 +2725,96 @@ PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
*/
static PyObject *
_PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- Py_ssize_t size, char *ptr)
+ Py_ssize_t size, char *ptr)
{
- CDataObject *src;
-
- if (setfunc)
- return setfunc(ptr, value, size);
-
- if (!CDataObject_Check(value)) {
- StgDictObject *dict = PyType_stgdict(type);
- if (dict && dict->setfunc)
- return dict->setfunc(ptr, value, size);
- /*
- If value is a tuple, we try to call the type with the tuple
- and use the result!
- */
- assert(PyType_Check(type));
- if (PyTuple_Check(value)) {
- PyObject *ob;
- PyObject *result;
- ob = PyObject_CallObject(type, value);
- if (ob == NULL) {
- _ctypes_extend_error(PyExc_RuntimeError, "(%s) ",
- ((PyTypeObject *)type)->tp_name);
- return NULL;
- }
- result = _PyCData_set(dst, type, setfunc, ob,
- size, ptr);
- Py_DECREF(ob);
- return result;
- } else if (value == Py_None && PyCPointerTypeObject_Check(type)) {
- *(void **)ptr = NULL;
- Py_INCREF(Py_None);
- return Py_None;
- } else {
- PyErr_Format(PyExc_TypeError,
- "expected %s instance, got %s",
- ((PyTypeObject *)type)->tp_name,
- Py_TYPE(value)->tp_name);
- return NULL;
- }
- }
- src = (CDataObject *)value;
-
- if (PyObject_IsInstance(value, type)) {
- memcpy(ptr,
- src->b_ptr,
- size);
-
- if (PyCPointerTypeObject_Check(type))
- /* XXX */;
-
- value = GetKeepedObjects(src);
- Py_INCREF(value);
- return value;
- }
-
- if (PyCPointerTypeObject_Check(type)
- && ArrayObject_Check(value)) {
- StgDictObject *p1, *p2;
- PyObject *keep;
- p1 = PyObject_stgdict(value);
- assert(p1); /* Cannot be NULL for array instances */
- p2 = PyType_stgdict(type);
- assert(p2); /* Cannot be NULL for pointer types */
-
- if (p1->proto != p2->proto) {
- PyErr_Format(PyExc_TypeError,
- "incompatible types, %s instance instead of %s instance",
- Py_TYPE(value)->tp_name,
- ((PyTypeObject *)type)->tp_name);
- return NULL;
- }
- *(void **)ptr = src->b_ptr;
-
- keep = GetKeepedObjects(src);
- /*
- We are assigning an array object to a field which represents
- a pointer. This has the same effect as converting an array
- into a pointer. So, again, we have to keep the whole object
- pointed to (which is the array in this case) alive, and not
- only it's object list. So we create a tuple, containing
- b_objects list PLUS the array itself, and return that!
- */
- return PyTuple_Pack(2, keep, value);
- }
- PyErr_Format(PyExc_TypeError,
- "incompatible types, %s instance instead of %s instance",
- Py_TYPE(value)->tp_name,
- ((PyTypeObject *)type)->tp_name);
- return NULL;
+ CDataObject *src;
+
+ if (setfunc)
+ return setfunc(ptr, value, size);
+
+ if (!CDataObject_Check(value)) {
+ StgDictObject *dict = PyType_stgdict(type);
+ if (dict && dict->setfunc)
+ return dict->setfunc(ptr, value, size);
+ /*
+ If value is a tuple, we try to call the type with the tuple
+ and use the result!
+ */
+ assert(PyType_Check(type));
+ if (PyTuple_Check(value)) {
+ PyObject *ob;
+ PyObject *result;
+ ob = PyObject_CallObject(type, value);
+ if (ob == NULL) {
+ _ctypes_extend_error(PyExc_RuntimeError, "(%s) ",
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
+ }
+ result = _PyCData_set(dst, type, setfunc, ob,
+ size, ptr);
+ Py_DECREF(ob);
+ return result;
+ } else if (value == Py_None && PyCPointerTypeObject_Check(type)) {
+ *(void **)ptr = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
+ } else {
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instance, got %s",
+ ((PyTypeObject *)type)->tp_name,
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+ }
+ src = (CDataObject *)value;
+
+ if (PyObject_IsInstance(value, type)) {
+ memcpy(ptr,
+ src->b_ptr,
+ size);
+
+ if (PyCPointerTypeObject_Check(type))
+ /* XXX */;
+
+ value = GetKeepedObjects(src);
+ Py_INCREF(value);
+ return value;
+ }
+
+ if (PyCPointerTypeObject_Check(type)
+ && ArrayObject_Check(value)) {
+ StgDictObject *p1, *p2;
+ PyObject *keep;
+ p1 = PyObject_stgdict(value);
+ assert(p1); /* Cannot be NULL for array instances */
+ p2 = PyType_stgdict(type);
+ assert(p2); /* Cannot be NULL for pointer types */
+
+ if (p1->proto != p2->proto) {
+ PyErr_Format(PyExc_TypeError,
+ "incompatible types, %s instance instead of %s instance",
+ Py_TYPE(value)->tp_name,
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
+ }
+ *(void **)ptr = src->b_ptr;
+
+ keep = GetKeepedObjects(src);
+ /*
+ We are assigning an array object to a field which represents
+ a pointer. This has the same effect as converting an array
+ into a pointer. So, again, we have to keep the whole object
+ pointed to (which is the array in this case) alive, and not
+ only it's object list. So we create a tuple, containing
+ b_objects list PLUS the array itself, and return that!
+ */
+ return PyTuple_Pack(2, keep, value);
+ }
+ PyErr_Format(PyExc_TypeError,
+ "incompatible types, %s instance instead of %s instance",
+ Py_TYPE(value)->tp_name,
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
}
/*
@@ -2823,58 +2823,58 @@ _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
*/
int
PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- Py_ssize_t index, Py_ssize_t size, char *ptr)
+ Py_ssize_t index, Py_ssize_t size, char *ptr)
{
- CDataObject *mem = (CDataObject *)dst;
- PyObject *result;
-
- if (!CDataObject_Check(dst)) {
- PyErr_SetString(PyExc_TypeError,
- "not a ctype instance");
- return -1;
- }
-
- result = _PyCData_set(mem, type, setfunc, value,
- size, ptr);
- if (result == NULL)
- return -1;
-
- /* KeepRef steals a refcount from it's last argument */
- /* If KeepRef fails, we are stumped. The dst memory block has already
- been changed */
- return KeepRef(mem, index, result);
+ CDataObject *mem = (CDataObject *)dst;
+ PyObject *result;
+
+ if (!CDataObject_Check(dst)) {
+ PyErr_SetString(PyExc_TypeError,
+ "not a ctype instance");
+ return -1;
+ }
+
+ result = _PyCData_set(mem, type, setfunc, value,
+ size, ptr);
+ if (result == NULL)
+ return -1;
+
+ /* KeepRef steals a refcount from it's last argument */
+ /* If KeepRef fails, we are stumped. The dst memory block has already
+ been changed */
+ return KeepRef(mem, index, result);
}
-
+
/******************************************************************/
static PyObject *
GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- CDataObject *obj;
- StgDictObject *dict;
-
- dict = PyType_stgdict((PyObject *)type);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "abstract class");
- return NULL;
- }
- dict->flags |= DICTFLAG_FINAL;
-
- obj = (CDataObject *)type->tp_alloc(type, 0);
- if (!obj)
- return NULL;
-
- obj->b_base = NULL;
- obj->b_index = 0;
- obj->b_objects = NULL;
- obj->b_length = dict->length;
-
- if (-1 == PyCData_MallocBuffer(obj, dict)) {
- Py_DECREF(obj);
- return NULL;
- }
- return (PyObject *)obj;
+ CDataObject *obj;
+ StgDictObject *dict;
+
+ dict = PyType_stgdict((PyObject *)type);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "abstract class");
+ return NULL;
+ }
+ dict->flags |= DICTFLAG_FINAL;
+
+ obj = (CDataObject *)type->tp_alloc(type, 0);
+ if (!obj)
+ return NULL;
+
+ obj->b_base = NULL;
+ obj->b_index = 0;
+ obj->b_objects = NULL;
+ obj->b_length = dict->length;
+
+ if (-1 == PyCData_MallocBuffer(obj, dict)) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ return (PyObject *)obj;
}
/*****************************************************************/
/*
@@ -2884,165 +2884,165 @@ GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob)
{
- if (ob && !PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "the errcheck attribute must be callable");
- return -1;
- }
- Py_XDECREF(self->errcheck);
- Py_XINCREF(ob);
- self->errcheck = ob;
- return 0;
+ if (ob && !PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the errcheck attribute must be callable");
+ return -1;
+ }
+ Py_XDECREF(self->errcheck);
+ Py_XINCREF(ob);
+ self->errcheck = ob;
+ return 0;
}
static PyObject *
PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self)
{
- if (self->errcheck) {
- Py_INCREF(self->errcheck);
- return self->errcheck;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (self->errcheck) {
+ Py_INCREF(self->errcheck);
+ return self->errcheck;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static int
PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob)
{
- if (ob == NULL) {
- Py_XDECREF(self->restype);
- self->restype = NULL;
- Py_XDECREF(self->checker);
- self->checker = NULL;
- return 0;
- }
- if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "restype must be a type, a callable, or None");
- return -1;
- }
- Py_XDECREF(self->checker);
- Py_XDECREF(self->restype);
- Py_INCREF(ob);
- self->restype = ob;
- self->checker = PyObject_GetAttrString(ob, "_check_retval_");
- if (self->checker == NULL)
- PyErr_Clear();
- return 0;
+ if (ob == NULL) {
+ Py_XDECREF(self->restype);
+ self->restype = NULL;
+ Py_XDECREF(self->checker);
+ self->checker = NULL;
+ return 0;
+ }
+ if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "restype must be a type, a callable, or None");
+ return -1;
+ }
+ Py_XDECREF(self->checker);
+ Py_XDECREF(self->restype);
+ Py_INCREF(ob);
+ self->restype = ob;
+ self->checker = PyObject_GetAttrString(ob, "_check_retval_");
+ if (self->checker == NULL)
+ PyErr_Clear();
+ return 0;
}
static PyObject *
PyCFuncPtr_get_restype(PyCFuncPtrObject *self)
{
- StgDictObject *dict;
- if (self->restype) {
- Py_INCREF(self->restype);
- return self->restype;
- }
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
- if (dict->restype) {
- Py_INCREF(dict->restype);
- return dict->restype;
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ StgDictObject *dict;
+ if (self->restype) {
+ Py_INCREF(self->restype);
+ return self->restype;
+ }
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
+ if (dict->restype) {
+ Py_INCREF(dict->restype);
+ return dict->restype;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static int
PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob)
{
- PyObject *converters;
-
- if (ob == NULL || ob == Py_None) {
- Py_XDECREF(self->converters);
- self->converters = NULL;
- Py_XDECREF(self->argtypes);
- self->argtypes = NULL;
- } else {
- converters = converters_from_argtypes(ob);
- if (!converters)
- return -1;
- Py_XDECREF(self->converters);
- self->converters = converters;
- Py_XDECREF(self->argtypes);
- Py_INCREF(ob);
- self->argtypes = ob;
- }
- return 0;
+ PyObject *converters;
+
+ if (ob == NULL || ob == Py_None) {
+ Py_XDECREF(self->converters);
+ self->converters = NULL;
+ Py_XDECREF(self->argtypes);
+ self->argtypes = NULL;
+ } else {
+ converters = converters_from_argtypes(ob);
+ if (!converters)
+ return -1;
+ Py_XDECREF(self->converters);
+ self->converters = converters;
+ Py_XDECREF(self->argtypes);
+ Py_INCREF(ob);
+ self->argtypes = ob;
+ }
+ return 0;
}
static PyObject *
PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self)
{
- StgDictObject *dict;
- if (self->argtypes) {
- Py_INCREF(self->argtypes);
- return self->argtypes;
- }
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
- if (dict->argtypes) {
- Py_INCREF(dict->argtypes);
- return dict->argtypes;
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ StgDictObject *dict;
+ if (self->argtypes) {
+ Py_INCREF(self->argtypes);
+ return self->argtypes;
+ }
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
+ if (dict->argtypes) {
+ Py_INCREF(dict->argtypes);
+ return dict->argtypes;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static PyGetSetDef PyCFuncPtr_getsets[] = {
- { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck,
- "a function to check for errors", NULL },
- { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype,
- "specify the result type", NULL },
- { "argtypes", (getter)PyCFuncPtr_get_argtypes,
- (setter)PyCFuncPtr_set_argtypes,
- "specify the argument types", NULL },
- { NULL, NULL }
+ { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck,
+ "a function to check for errors", NULL },
+ { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype,
+ "specify the result type", NULL },
+ { "argtypes", (getter)PyCFuncPtr_get_argtypes,
+ (setter)PyCFuncPtr_set_argtypes,
+ "specify the argument types", NULL },
+ { NULL, NULL }
};
#ifdef MS_WIN32
static PPROC FindAddress(void *handle, char *name, PyObject *type)
{
#ifdef MS_WIN64
- /* win64 has no stdcall calling conv, so it should
- also not have the name mangling of it.
- */
- return (PPROC)GetProcAddress(handle, name);
+ /* win64 has no stdcall calling conv, so it should
+ also not have the name mangling of it.
+ */
+ return (PPROC)GetProcAddress(handle, name);
#else
- PPROC address;
- char *mangled_name;
- int i;
- StgDictObject *dict;
-
- address = (PPROC)GetProcAddress(handle, name);
- if (address)
- return address;
- if (((size_t)name & ~0xFFFF) == 0) {
- return NULL;
- }
-
- dict = PyType_stgdict((PyObject *)type);
- /* It should not happen that dict is NULL, but better be safe */
- if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
- return address;
-
- /* for stdcall, try mangled names:
- funcname -> _funcname@<n>
- where n is 0, 4, 8, 12, ..., 128
- */
- mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
- if (!mangled_name)
- return NULL;
- for (i = 0; i < 32; ++i) {
- sprintf(mangled_name, "_%s@%d", name, i*4);
- address = (PPROC)GetProcAddress(handle, mangled_name);
- if (address)
- return address;
- }
- return NULL;
+ PPROC address;
+ char *mangled_name;
+ int i;
+ StgDictObject *dict;
+
+ address = (PPROC)GetProcAddress(handle, name);
+ if (address)
+ return address;
+ if (((size_t)name & ~0xFFFF) == 0) {
+ return NULL;
+ }
+
+ dict = PyType_stgdict((PyObject *)type);
+ /* It should not happen that dict is NULL, but better be safe */
+ if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
+ return address;
+
+ /* for stdcall, try mangled names:
+ funcname -> _funcname@<n>
+ where n is 0, 4, 8, 12, ..., 128
+ */
+ mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
+ if (!mangled_name)
+ return NULL;
+ for (i = 0; i < 32; ++i) {
+ sprintf(mangled_name, "_%s@%d", name, i*4);
+ address = (PPROC)GetProcAddress(handle, mangled_name);
+ if (address)
+ return address;
+ }
+ return NULL;
#endif
}
#endif
@@ -3051,227 +3051,227 @@ static PPROC FindAddress(void *handle, char *name, PyObject *type)
static int
_check_outarg_type(PyObject *arg, Py_ssize_t index)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- if (PyCPointerTypeObject_Check(arg))
- return 1;
+ if (PyCPointerTypeObject_Check(arg))
+ return 1;
- if (PyCArrayTypeObject_Check(arg))
- return 1;
+ if (PyCArrayTypeObject_Check(arg))
+ return 1;
- dict = PyType_stgdict(arg);
- if (dict
- /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
- && PyUnicode_Check(dict->proto)
+ dict = PyType_stgdict(arg);
+ if (dict
+ /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
+ && PyUnicode_Check(dict->proto)
/* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
- && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) {
- return 1;
- }
-
- PyErr_Format(PyExc_TypeError,
- "'out' parameter %d must be a pointer type, not %s",
- Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
- PyType_Check(arg) ?
- ((PyTypeObject *)arg)->tp_name :
- Py_TYPE(arg)->tp_name);
- return 0;
+ && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) {
+ return 1;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "'out' parameter %d must be a pointer type, not %s",
+ Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
+ PyType_Check(arg) ?
+ ((PyTypeObject *)arg)->tp_name :
+ Py_TYPE(arg)->tp_name);
+ return 0;
}
/* Returns 1 on success, 0 on error */
static int
_validate_paramflags(PyTypeObject *type, PyObject *paramflags)
{
- Py_ssize_t i, len;
- StgDictObject *dict;
- PyObject *argtypes;
-
- dict = PyType_stgdict((PyObject *)type);
- assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */
- argtypes = dict->argtypes;
-
- if (paramflags == NULL || dict->argtypes == NULL)
- return 1;
-
- if (!PyTuple_Check(paramflags)) {
- PyErr_SetString(PyExc_TypeError,
- "paramflags must be a tuple or None");
- return 0;
- }
-
- len = PyTuple_GET_SIZE(paramflags);
- if (len != PyTuple_GET_SIZE(dict->argtypes)) {
- PyErr_SetString(PyExc_ValueError,
- "paramflags must have the same length as argtypes");
- return 0;
- }
-
- for (i = 0; i < len; ++i) {
- PyObject *item = PyTuple_GET_ITEM(paramflags, i);
- int flag;
- char *name;
- PyObject *defval;
- PyObject *typ;
- if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) {
- PyErr_SetString(PyExc_TypeError,
- "paramflags must be a sequence of (int [,string [,value]]) tuples");
- return 0;
- }
- typ = PyTuple_GET_ITEM(argtypes, i);
- switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
- case 0:
- case PARAMFLAG_FIN:
- case PARAMFLAG_FIN | PARAMFLAG_FLCID:
- case PARAMFLAG_FIN | PARAMFLAG_FOUT:
- break;
- case PARAMFLAG_FOUT:
- if (!_check_outarg_type(typ, i+1))
- return 0;
- break;
- default:
- PyErr_Format(PyExc_TypeError,
- "paramflag value %d not supported",
- flag);
- return 0;
- }
- }
- return 1;
+ Py_ssize_t i, len;
+ StgDictObject *dict;
+ PyObject *argtypes;
+
+ dict = PyType_stgdict((PyObject *)type);
+ assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */
+ argtypes = dict->argtypes;
+
+ if (paramflags == NULL || dict->argtypes == NULL)
+ return 1;
+
+ if (!PyTuple_Check(paramflags)) {
+ PyErr_SetString(PyExc_TypeError,
+ "paramflags must be a tuple or None");
+ return 0;
+ }
+
+ len = PyTuple_GET_SIZE(paramflags);
+ if (len != PyTuple_GET_SIZE(dict->argtypes)) {
+ PyErr_SetString(PyExc_ValueError,
+ "paramflags must have the same length as argtypes");
+ return 0;
+ }
+
+ for (i = 0; i < len; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(paramflags, i);
+ int flag;
+ char *name;
+ PyObject *defval;
+ PyObject *typ;
+ if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) {
+ PyErr_SetString(PyExc_TypeError,
+ "paramflags must be a sequence of (int [,string [,value]]) tuples");
+ return 0;
+ }
+ typ = PyTuple_GET_ITEM(argtypes, i);
+ switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
+ case 0:
+ case PARAMFLAG_FIN:
+ case PARAMFLAG_FIN | PARAMFLAG_FLCID:
+ case PARAMFLAG_FIN | PARAMFLAG_FOUT:
+ break;
+ case PARAMFLAG_FOUT:
+ if (!_check_outarg_type(typ, i+1))
+ return 0;
+ break;
+ default:
+ PyErr_Format(PyExc_TypeError,
+ "paramflag value %d not supported",
+ flag);
+ return 0;
+ }
+ }
+ return 1;
}
static int
_get_name(PyObject *obj, char **pname)
{
#ifdef MS_WIN32
- if (PyLong_Check(obj)) {
- /* We have to use MAKEINTRESOURCEA for Windows CE.
- Works on Windows as well, of course.
- */
- *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF);
- return 1;
- }
+ if (PyLong_Check(obj)) {
+ /* We have to use MAKEINTRESOURCEA for Windows CE.
+ Works on Windows as well, of course.
+ */
+ *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF);
+ return 1;
+ }
#endif
- if (PyBytes_Check(obj)) {
- *pname = PyBytes_AS_STRING(obj);
- return *pname ? 1 : 0;
- }
- if (PyUnicode_Check(obj)) {
- *pname = _PyUnicode_AsString(obj);
- return *pname ? 1 : 0;
- }
- PyErr_SetString(PyExc_TypeError,
- "function name must be string or integer");
- return 0;
+ if (PyBytes_Check(obj)) {
+ *pname = PyBytes_AS_STRING(obj);
+ return *pname ? 1 : 0;
+ }
+ if (PyUnicode_Check(obj)) {
+ *pname = _PyUnicode_AsString(obj);
+ return *pname ? 1 : 0;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "function name must be string or integer");
+ return 0;
}
static PyObject *
PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char *name;
- int (* address)(void);
- PyObject *dll;
- PyObject *obj;
- PyCFuncPtrObject *self;
- void *handle;
- PyObject *paramflags = NULL;
-
- if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, &paramflags))
- return NULL;
- if (paramflags == Py_None)
- paramflags = NULL;
-
- obj = PyObject_GetAttrString(dll, "_handle");
- if (!obj)
- return NULL;
- if (!PyLong_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "the _handle attribute of the second argument must be an integer");
- Py_DECREF(obj);
- return NULL;
- }
- handle = (void *)PyLong_AsVoidPtr(obj);
- Py_DECREF(obj);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert the _handle attribute to a pointer");
- return NULL;
- }
+ char *name;
+ int (* address)(void);
+ PyObject *dll;
+ PyObject *obj;
+ PyCFuncPtrObject *self;
+ void *handle;
+ PyObject *paramflags = NULL;
+
+ if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, &paramflags))
+ return NULL;
+ if (paramflags == Py_None)
+ paramflags = NULL;
+
+ obj = PyObject_GetAttrString(dll, "_handle");
+ if (!obj)
+ return NULL;
+ if (!PyLong_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the _handle attribute of the second argument must be an integer");
+ Py_DECREF(obj);
+ return NULL;
+ }
+ handle = (void *)PyLong_AsVoidPtr(obj);
+ Py_DECREF(obj);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert the _handle attribute to a pointer");
+ return NULL;
+ }
#ifdef MS_WIN32
- address = FindAddress(handle, name, (PyObject *)type);
- if (!address) {
- if (!IS_INTRESOURCE(name))
- PyErr_Format(PyExc_AttributeError,
- "function '%s' not found",
- name);
- else
- PyErr_Format(PyExc_AttributeError,
- "function ordinal %d not found",
- (WORD)(size_t)name);
- return NULL;
- }
+ address = FindAddress(handle, name, (PyObject *)type);
+ if (!address) {
+ if (!IS_INTRESOURCE(name))
+ PyErr_Format(PyExc_AttributeError,
+ "function '%s' not found",
+ name);
+ else
+ PyErr_Format(PyExc_AttributeError,
+ "function ordinal %d not found",
+ (WORD)(size_t)name);
+ return NULL;
+ }
#else
- address = (PPROC)ctypes_dlsym(handle, name);
- if (!address) {
+ address = (PPROC)ctypes_dlsym(handle, name);
+ if (!address) {
#ifdef __CYGWIN__
/* dlerror() isn't very helpful on cygwin */
- PyErr_Format(PyExc_AttributeError,
- "function '%s' not found (%s) ",
- name);
+ PyErr_Format(PyExc_AttributeError,
+ "function '%s' not found (%s) ",
+ name);
#else
- PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
+ PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
#endif
- return NULL;
- }
+ return NULL;
+ }
#endif
- if (!_validate_paramflags(type, paramflags))
- return NULL;
+ if (!_validate_paramflags(type, paramflags))
+ return NULL;
- self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
- if (!self)
- return NULL;
+ self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
+ if (!self)
+ return NULL;
- Py_XINCREF(paramflags);
- self->paramflags = paramflags;
+ Py_XINCREF(paramflags);
+ self->paramflags = paramflags;
- *(void **)self->b_ptr = address;
+ *(void **)self->b_ptr = address;
- Py_INCREF((PyObject *)dll); /* for KeepRef */
- if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
- Py_DECREF((PyObject *)self);
- return NULL;
- }
+ Py_INCREF((PyObject *)dll); /* for KeepRef */
+ if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
+ Py_DECREF((PyObject *)self);
+ return NULL;
+ }
- Py_INCREF(self);
- self->callable = (PyObject *)self;
- return (PyObject *)self;
+ Py_INCREF(self);
+ self->callable = (PyObject *)self;
+ return (PyObject *)self;
}
#ifdef MS_WIN32
static PyObject *
PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyCFuncPtrObject *self;
- int index;
- char *name = NULL;
- PyObject *paramflags = NULL;
- GUID *iid = NULL;
- Py_ssize_t iid_len = 0;
-
- if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
- return NULL;
- if (paramflags == Py_None)
- paramflags = NULL;
-
- if (!_validate_paramflags(type, paramflags))
- return NULL;
-
- self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
- self->index = index + 0x1000;
- Py_XINCREF(paramflags);
- self->paramflags = paramflags;
- if (iid_len == sizeof(GUID))
- self->iid = iid;
- return (PyObject *)self;
+ PyCFuncPtrObject *self;
+ int index;
+ char *name = NULL;
+ PyObject *paramflags = NULL;
+ GUID *iid = NULL;
+ Py_ssize_t iid_len = 0;
+
+ if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
+ return NULL;
+ if (paramflags == Py_None)
+ paramflags = NULL;
+
+ if (!_validate_paramflags(type, paramflags))
+ return NULL;
+
+ self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
+ self->index = index + 0x1000;
+ Py_XINCREF(paramflags);
+ self->paramflags = paramflags;
+ if (iid_len == sizeof(GUID))
+ self->iid = iid;
+ return (PyObject *)self;
}
#endif
@@ -3291,90 +3291,90 @@ PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyCFuncPtrObject *self;
- PyObject *callable;
- StgDictObject *dict;
- CThunkObject *thunk;
+ PyCFuncPtrObject *self;
+ PyObject *callable;
+ StgDictObject *dict;
+ CThunkObject *thunk;
- if (PyTuple_GET_SIZE(args) == 0)
- return GenericPyCData_new(type, args, kwds);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return GenericPyCData_new(type, args, kwds);
- if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
- return PyCFuncPtr_FromDll(type, args, kwds);
+ if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
+ return PyCFuncPtr_FromDll(type, args, kwds);
#ifdef MS_WIN32
- if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0)))
- return PyCFuncPtr_FromVtblIndex(type, args, kwds);
+ if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0)))
+ return PyCFuncPtr_FromVtblIndex(type, args, kwds);
#endif
- if (1 == PyTuple_GET_SIZE(args)
- && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
- CDataObject *ob;
- void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
- if (ptr == NULL && PyErr_Occurred())
- return NULL;
- ob = (CDataObject *)GenericPyCData_new(type, args, kwds);
- if (ob == NULL)
- return NULL;
- *(void **)ob->b_ptr = ptr;
- return (PyObject *)ob;
- }
-
- if (!PyArg_ParseTuple(args, "O", &callable))
- return NULL;
- if (!PyCallable_Check(callable)) {
- PyErr_SetString(PyExc_TypeError,
- "argument must be callable or integer function address");
- return NULL;
- }
-
- /* XXX XXX This would allow to pass additional options. For COM
- method *implementations*, we would probably want different
- behaviour than in 'normal' callback functions: return a HRESULT if
- an exception occurrs in the callback, and print the traceback not
- only on the console, but also to OutputDebugString() or something
- like that.
- */
+ if (1 == PyTuple_GET_SIZE(args)
+ && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
+ CDataObject *ob;
+ void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
+ if (ptr == NULL && PyErr_Occurred())
+ return NULL;
+ ob = (CDataObject *)GenericPyCData_new(type, args, kwds);
+ if (ob == NULL)
+ return NULL;
+ *(void **)ob->b_ptr = ptr;
+ return (PyObject *)ob;
+ }
+
+ if (!PyArg_ParseTuple(args, "O", &callable))
+ return NULL;
+ if (!PyCallable_Check(callable)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument must be callable or integer function address");
+ return NULL;
+ }
+
+ /* XXX XXX This would allow to pass additional options. For COM
+ method *implementations*, we would probably want different
+ behaviour than in 'normal' callback functions: return a HRESULT if
+ an exception occurrs in the callback, and print the traceback not
+ only on the console, but also to OutputDebugString() or something
+ like that.
+ */
/*
- if (kwds && PyDict_GetItemString(kwds, "options")) {
- ...
- }
+ if (kwds && PyDict_GetItemString(kwds, "options")) {
+ ...
+ }
*/
- dict = PyType_stgdict((PyObject *)type);
- /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
- if (!dict || !dict->argtypes) {
- PyErr_SetString(PyExc_TypeError,
- "cannot construct instance of this class:"
- " no argtypes");
- return NULL;
- }
-
- thunk = _ctypes_alloc_callback(callable,
- dict->argtypes,
- dict->restype,
- dict->flags);
- if (!thunk)
- return NULL;
-
- self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
- if (self == NULL) {
- Py_DECREF(thunk);
- return NULL;
- }
-
- Py_INCREF(callable);
- self->callable = callable;
-
- self->thunk = thunk;
- *(void **)self->b_ptr = (void *)thunk->pcl;
-
- Py_INCREF((PyObject *)thunk); /* for KeepRef */
- if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
- Py_DECREF((PyObject *)self);
- return NULL;
- }
- return (PyObject *)self;
+ dict = PyType_stgdict((PyObject *)type);
+ /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
+ if (!dict || !dict->argtypes) {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot construct instance of this class:"
+ " no argtypes");
+ return NULL;
+ }
+
+ thunk = _ctypes_alloc_callback(callable,
+ dict->argtypes,
+ dict->restype,
+ dict->flags);
+ if (!thunk)
+ return NULL;
+
+ self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
+ if (self == NULL) {
+ Py_DECREF(thunk);
+ return NULL;
+ }
+
+ Py_INCREF(callable);
+ self->callable = callable;
+
+ self->thunk = thunk;
+ *(void **)self->b_ptr = (void *)thunk->pcl;
+
+ Py_INCREF((PyObject *)thunk); /* for KeepRef */
+ if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
+ Py_DECREF((PyObject *)self);
+ return NULL;
+ }
+ return (PyObject *)self;
}
@@ -3384,54 +3384,54 @@ PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
_byref(PyObject *obj)
{
- PyCArgObject *parg;
- if (!CDataObject_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "expected CData instance");
- return NULL;
- }
-
- parg = PyCArgObject_new();
- if (parg == NULL) {
- Py_DECREF(obj);
- return NULL;
- }
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- parg->obj = obj;
- parg->value.p = ((CDataObject *)obj)->b_ptr;
- return (PyObject *)parg;
+ PyCArgObject *parg;
+ if (!CDataObject_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected CData instance");
+ return NULL;
+ }
+
+ parg = PyCArgObject_new();
+ if (parg == NULL) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ parg->obj = obj;
+ parg->value.p = ((CDataObject *)obj)->b_ptr;
+ return (PyObject *)parg;
}
static PyObject *
_get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds)
{
- PyObject *v;
-
- if (*pindex < PyTuple_GET_SIZE(inargs)) {
- v = PyTuple_GET_ITEM(inargs, *pindex);
- ++*pindex;
- Py_INCREF(v);
- return v;
- }
- if (kwds && (v = PyDict_GetItem(kwds, name))) {
- ++*pindex;
- Py_INCREF(v);
- return v;
- }
- if (defval) {
- Py_INCREF(defval);
- return defval;
- }
- /* we can't currently emit a better error message */
- if (name)
- PyErr_Format(PyExc_TypeError,
- "required argument '%S' missing", name);
- else
- PyErr_Format(PyExc_TypeError,
- "not enough arguments");
- return NULL;
+ PyObject *v;
+
+ if (*pindex < PyTuple_GET_SIZE(inargs)) {
+ v = PyTuple_GET_ITEM(inargs, *pindex);
+ ++*pindex;
+ Py_INCREF(v);
+ return v;
+ }
+ if (kwds && (v = PyDict_GetItem(kwds, name))) {
+ ++*pindex;
+ Py_INCREF(v);
+ return v;
+ }
+ if (defval) {
+ Py_INCREF(defval);
+ return defval;
+ }
+ /* we can't currently emit a better error message */
+ if (name)
+ PyErr_Format(PyExc_TypeError,
+ "required argument '%S' missing", name);
+ else
+ PyErr_Format(PyExc_TypeError,
+ "not enough arguments");
+ return NULL;
}
/*
@@ -3454,166 +3454,166 @@ _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObje
*/
static PyObject *
_build_callargs(PyCFuncPtrObject *self, PyObject *argtypes,
- PyObject *inargs, PyObject *kwds,
- int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
+ PyObject *inargs, PyObject *kwds,
+ int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
{
- PyObject *paramflags = self->paramflags;
- PyObject *callargs;
- StgDictObject *dict;
- Py_ssize_t i, len;
- int inargs_index = 0;
- /* It's a little bit difficult to determine how many arguments the
- function call requires/accepts. For simplicity, we count the consumed
- args and compare this to the number of supplied args. */
- Py_ssize_t actual_args;
-
- *poutmask = 0;
- *pinoutmask = 0;
- *pnumretvals = 0;
-
- /* Trivial cases, where we either return inargs itself, or a slice of it. */
- if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
+ PyObject *paramflags = self->paramflags;
+ PyObject *callargs;
+ StgDictObject *dict;
+ Py_ssize_t i, len;
+ int inargs_index = 0;
+ /* It's a little bit difficult to determine how many arguments the
+ function call requires/accepts. For simplicity, we count the consumed
+ args and compare this to the number of supplied args. */
+ Py_ssize_t actual_args;
+
+ *poutmask = 0;
+ *pinoutmask = 0;
+ *pnumretvals = 0;
+
+ /* Trivial cases, where we either return inargs itself, or a slice of it. */
+ if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
#ifdef MS_WIN32
- if (self->index)
- return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
+ if (self->index)
+ return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
#endif
- Py_INCREF(inargs);
- return inargs;
- }
+ Py_INCREF(inargs);
+ return inargs;
+ }
- len = PyTuple_GET_SIZE(argtypes);
- callargs = PyTuple_New(len); /* the argument tuple we build */
- if (callargs == NULL)
- return NULL;
+ len = PyTuple_GET_SIZE(argtypes);
+ callargs = PyTuple_New(len); /* the argument tuple we build */
+ if (callargs == NULL)
+ return NULL;
#ifdef MS_WIN32
- /* For a COM method, skip the first arg */
- if (self->index) {
- inargs_index = 1;
- }
+ /* For a COM method, skip the first arg */
+ if (self->index) {
+ inargs_index = 1;
+ }
#endif
- for (i = 0; i < len; ++i) {
- PyObject *item = PyTuple_GET_ITEM(paramflags, i);
- PyObject *ob;
- int flag;
- PyObject *name = NULL;
- PyObject *defval = NULL;
-
- /* This way seems to be ~2 us faster than the PyArg_ParseTuple
- calls below. */
- /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */
- Py_ssize_t tsize = PyTuple_GET_SIZE(item);
- flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0));
- name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL;
- defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
-
- switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
- case PARAMFLAG_FIN | PARAMFLAG_FLCID:
- /* ['in', 'lcid'] parameter. Always taken from defval,
- if given, else the integer 0. */
- if (defval == NULL) {
- defval = PyLong_FromLong(0);
- if (defval == NULL)
- goto error;
- } else
- Py_INCREF(defval);
- PyTuple_SET_ITEM(callargs, i, defval);
- break;
- case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
- *pinoutmask |= (1 << i); /* mark as inout arg */
- (*pnumretvals)++;
- /* fall through to PARAMFLAG_FIN... */
- case 0:
- case PARAMFLAG_FIN:
- /* 'in' parameter. Copy it from inargs. */
- ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
- if (ob == NULL)
- goto error;
- PyTuple_SET_ITEM(callargs, i, ob);
- break;
- case PARAMFLAG_FOUT:
- /* XXX Refactor this code into a separate function. */
- /* 'out' parameter.
- argtypes[i] must be a POINTER to a c type.
-
- Cannot by supplied in inargs, but a defval will be used
- if available. XXX Should we support getting it from kwds?
- */
- if (defval) {
- /* XXX Using mutable objects as defval will
- make the function non-threadsafe, unless we
- copy the object in each invocation */
- Py_INCREF(defval);
- PyTuple_SET_ITEM(callargs, i, defval);
- *poutmask |= (1 << i); /* mark as out arg */
- (*pnumretvals)++;
- break;
- }
- ob = PyTuple_GET_ITEM(argtypes, i);
- dict = PyType_stgdict(ob);
- if (dict == NULL) {
- /* Cannot happen: _validate_paramflags()
- would not accept such an object */
- PyErr_Format(PyExc_RuntimeError,
- "NULL stgdict unexpected");
- goto error;
- }
- if (PyUnicode_Check(dict->proto)) {
- PyErr_Format(
- PyExc_TypeError,
- "%s 'out' parameter must be passed as default value",
- ((PyTypeObject *)ob)->tp_name);
- goto error;
- }
- if (PyCArrayTypeObject_Check(ob))
- ob = PyObject_CallObject(ob, NULL);
- else
- /* Create an instance of the pointed-to type */
- ob = PyObject_CallObject(dict->proto, NULL);
- /*
- XXX Is the following correct any longer?
- We must not pass a byref() to the array then but
- the array instance itself. Then, we cannot retrive
- the result from the PyCArgObject.
- */
- if (ob == NULL)
- goto error;
- /* The .from_param call that will ocurr later will pass this
- as a byref parameter. */
- PyTuple_SET_ITEM(callargs, i, ob);
- *poutmask |= (1 << i); /* mark as out arg */
- (*pnumretvals)++;
- break;
- default:
- PyErr_Format(PyExc_ValueError,
- "paramflag %d not yet implemented", flag);
- goto error;
- break;
- }
- }
-
- /* We have counted the arguments we have consumed in 'inargs_index'. This
- must be the same as len(inargs) + len(kwds), otherwise we have
- either too much or not enough arguments. */
-
- actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0);
- if (actual_args != inargs_index) {
- /* When we have default values or named parameters, this error
- message is misleading. See unittests/test_paramflags.py
- */
- PyErr_Format(PyExc_TypeError,
- "call takes exactly %d arguments (%zd given)",
- inargs_index, actual_args);
- goto error;
- }
-
- /* outmask is a bitmask containing indexes into callargs. Items at
- these indexes contain values to return.
- */
- return callargs;
+ for (i = 0; i < len; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(paramflags, i);
+ PyObject *ob;
+ int flag;
+ PyObject *name = NULL;
+ PyObject *defval = NULL;
+
+ /* This way seems to be ~2 us faster than the PyArg_ParseTuple
+ calls below. */
+ /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */
+ Py_ssize_t tsize = PyTuple_GET_SIZE(item);
+ flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0));
+ name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL;
+ defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
+
+ switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
+ case PARAMFLAG_FIN | PARAMFLAG_FLCID:
+ /* ['in', 'lcid'] parameter. Always taken from defval,
+ if given, else the integer 0. */
+ if (defval == NULL) {
+ defval = PyLong_FromLong(0);
+ if (defval == NULL)
+ goto error;
+ } else
+ Py_INCREF(defval);
+ PyTuple_SET_ITEM(callargs, i, defval);
+ break;
+ case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
+ *pinoutmask |= (1 << i); /* mark as inout arg */
+ (*pnumretvals)++;
+ /* fall through to PARAMFLAG_FIN... */
+ case 0:
+ case PARAMFLAG_FIN:
+ /* 'in' parameter. Copy it from inargs. */
+ ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
+ if (ob == NULL)
+ goto error;
+ PyTuple_SET_ITEM(callargs, i, ob);
+ break;
+ case PARAMFLAG_FOUT:
+ /* XXX Refactor this code into a separate function. */
+ /* 'out' parameter.
+ argtypes[i] must be a POINTER to a c type.
+
+ Cannot by supplied in inargs, but a defval will be used
+ if available. XXX Should we support getting it from kwds?
+ */
+ if (defval) {
+ /* XXX Using mutable objects as defval will
+ make the function non-threadsafe, unless we
+ copy the object in each invocation */
+ Py_INCREF(defval);
+ PyTuple_SET_ITEM(callargs, i, defval);
+ *poutmask |= (1 << i); /* mark as out arg */
+ (*pnumretvals)++;
+ break;
+ }
+ ob = PyTuple_GET_ITEM(argtypes, i);
+ dict = PyType_stgdict(ob);
+ if (dict == NULL) {
+ /* Cannot happen: _validate_paramflags()
+ would not accept such an object */
+ PyErr_Format(PyExc_RuntimeError,
+ "NULL stgdict unexpected");
+ goto error;
+ }
+ if (PyUnicode_Check(dict->proto)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s 'out' parameter must be passed as default value",
+ ((PyTypeObject *)ob)->tp_name);
+ goto error;
+ }
+ if (PyCArrayTypeObject_Check(ob))
+ ob = PyObject_CallObject(ob, NULL);
+ else
+ /* Create an instance of the pointed-to type */
+ ob = PyObject_CallObject(dict->proto, NULL);
+ /*
+ XXX Is the following correct any longer?
+ We must not pass a byref() to the array then but
+ the array instance itself. Then, we cannot retrive
+ the result from the PyCArgObject.
+ */
+ if (ob == NULL)
+ goto error;
+ /* The .from_param call that will ocurr later will pass this
+ as a byref parameter. */
+ PyTuple_SET_ITEM(callargs, i, ob);
+ *poutmask |= (1 << i); /* mark as out arg */
+ (*pnumretvals)++;
+ break;
+ default:
+ PyErr_Format(PyExc_ValueError,
+ "paramflag %d not yet implemented", flag);
+ goto error;
+ break;
+ }
+ }
+
+ /* We have counted the arguments we have consumed in 'inargs_index'. This
+ must be the same as len(inargs) + len(kwds), otherwise we have
+ either too much or not enough arguments. */
+
+ actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0);
+ if (actual_args != inargs_index) {
+ /* When we have default values or named parameters, this error
+ message is misleading. See unittests/test_paramflags.py
+ */
+ PyErr_Format(PyExc_TypeError,
+ "call takes exactly %d arguments (%zd given)",
+ inargs_index, actual_args);
+ goto error;
+ }
+
+ /* outmask is a bitmask containing indexes into callargs. Items at
+ these indexes contain values to return.
+ */
+ return callargs;
error:
- Py_DECREF(callargs);
- return NULL;
+ Py_DECREF(callargs);
+ return NULL;
}
/* See also:
@@ -3626,307 +3626,307 @@ _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes,
*/
static PyObject *
_build_result(PyObject *result, PyObject *callargs,
- int outmask, int inoutmask, unsigned int numretvals)
+ int outmask, int inoutmask, unsigned int numretvals)
{
- unsigned int i, index;
- int bit;
- PyObject *tup = NULL;
-
- if (callargs == NULL)
- return result;
- if (result == NULL || numretvals == 0) {
- Py_DECREF(callargs);
- return result;
- }
- Py_DECREF(result);
-
- /* tup will not be allocated if numretvals == 1 */
- /* allocate tuple to hold the result */
- if (numretvals > 1) {
- tup = PyTuple_New(numretvals);
- if (tup == NULL) {
- Py_DECREF(callargs);
- return NULL;
- }
- }
-
- index = 0;
- for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
- PyObject *v;
- if (bit & inoutmask) {
- v = PyTuple_GET_ITEM(callargs, i);
- Py_INCREF(v);
- if (numretvals == 1) {
- Py_DECREF(callargs);
- return v;
- }
- PyTuple_SET_ITEM(tup, index, v);
- index++;
- } else if (bit & outmask) {
- v = PyTuple_GET_ITEM(callargs, i);
- v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL);
- if (v == NULL || numretvals == 1) {
- Py_DECREF(callargs);
- return v;
- }
- PyTuple_SET_ITEM(tup, index, v);
- index++;
- }
- if (index == numretvals)
- break;
- }
-
- Py_DECREF(callargs);
- return tup;
+ unsigned int i, index;
+ int bit;
+ PyObject *tup = NULL;
+
+ if (callargs == NULL)
+ return result;
+ if (result == NULL || numretvals == 0) {
+ Py_DECREF(callargs);
+ return result;
+ }
+ Py_DECREF(result);
+
+ /* tup will not be allocated if numretvals == 1 */
+ /* allocate tuple to hold the result */
+ if (numretvals > 1) {
+ tup = PyTuple_New(numretvals);
+ if (tup == NULL) {
+ Py_DECREF(callargs);
+ return NULL;
+ }
+ }
+
+ index = 0;
+ for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
+ PyObject *v;
+ if (bit & inoutmask) {
+ v = PyTuple_GET_ITEM(callargs, i);
+ Py_INCREF(v);
+ if (numretvals == 1) {
+ Py_DECREF(callargs);
+ return v;
+ }
+ PyTuple_SET_ITEM(tup, index, v);
+ index++;
+ } else if (bit & outmask) {
+ v = PyTuple_GET_ITEM(callargs, i);
+ v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL);
+ if (v == NULL || numretvals == 1) {
+ Py_DECREF(callargs);
+ return v;
+ }
+ PyTuple_SET_ITEM(tup, index, v);
+ index++;
+ }
+ if (index == numretvals)
+ break;
+ }
+
+ Py_DECREF(callargs);
+ return tup;
}
static PyObject *
PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds)
{
- PyObject *restype;
- PyObject *converters;
- PyObject *checker;
- PyObject *argtypes;
- StgDictObject *dict = PyObject_stgdict((PyObject *)self);
- PyObject *result;
- PyObject *callargs;
- PyObject *errcheck;
+ PyObject *restype;
+ PyObject *converters;
+ PyObject *checker;
+ PyObject *argtypes;
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+ PyObject *result;
+ PyObject *callargs;
+ PyObject *errcheck;
#ifdef MS_WIN32
- IUnknown *piunk = NULL;
+ IUnknown *piunk = NULL;
#endif
- void *pProc = NULL;
+ void *pProc = NULL;
- int inoutmask;
- int outmask;
- unsigned int numretvals;
+ int inoutmask;
+ int outmask;
+ unsigned int numretvals;
- assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
- restype = self->restype ? self->restype : dict->restype;
- converters = self->converters ? self->converters : dict->converters;
- checker = self->checker ? self->checker : dict->checker;
- argtypes = self->argtypes ? self->argtypes : dict->argtypes;
+ assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
+ restype = self->restype ? self->restype : dict->restype;
+ converters = self->converters ? self->converters : dict->converters;
+ checker = self->checker ? self->checker : dict->checker;
+ argtypes = self->argtypes ? self->argtypes : dict->argtypes;
/* later, we probably want to have an errcheck field in stgdict */
- errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */;
+ errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */;
- pProc = *(void **)self->b_ptr;
+ pProc = *(void **)self->b_ptr;
#ifdef MS_WIN32
- if (self->index) {
- /* It's a COM method */
- CDataObject *this;
- this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
- if (!this) {
- PyErr_SetString(PyExc_ValueError,
- "native com method call without 'this' parameter");
- return NULL;
- }
- if (!CDataObject_Check(this)) {
- PyErr_SetString(PyExc_TypeError,
- "Expected a COM this pointer as first argument");
- return NULL;
- }
- /* there should be more checks? No, in Python */
- /* First arg is an pointer to an interface instance */
- if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL COM pointer access");
- return NULL;
- }
- piunk = *(IUnknown **)this->b_ptr;
- if (NULL == piunk->lpVtbl) {
- PyErr_SetString(PyExc_ValueError,
- "COM method call without VTable");
- return NULL;
- }
- pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
- }
+ if (self->index) {
+ /* It's a COM method */
+ CDataObject *this;
+ this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
+ if (!this) {
+ PyErr_SetString(PyExc_ValueError,
+ "native com method call without 'this' parameter");
+ return NULL;
+ }
+ if (!CDataObject_Check(this)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected a COM this pointer as first argument");
+ return NULL;
+ }
+ /* there should be more checks? No, in Python */
+ /* First arg is an pointer to an interface instance */
+ if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL COM pointer access");
+ return NULL;
+ }
+ piunk = *(IUnknown **)this->b_ptr;
+ if (NULL == piunk->lpVtbl) {
+ PyErr_SetString(PyExc_ValueError,
+ "COM method call without VTable");
+ return NULL;
+ }
+ pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
+ }
#endif
- callargs = _build_callargs(self, argtypes,
- inargs, kwds,
- &outmask, &inoutmask, &numretvals);
- if (callargs == NULL)
- return NULL;
-
- if (converters) {
- int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
- Py_ssize_t, int);
- int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
- Py_ssize_t, int);
-
- if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
- /* For cdecl functions, we allow more actual arguments
- than the length of the argtypes tuple.
- */
- if (required > actual) {
- Py_DECREF(callargs);
- PyErr_Format(PyExc_TypeError,
- "this function takes at least %d argument%s (%d given)",
- required,
- required == 1 ? "" : "s",
- actual);
- return NULL;
- }
- } else if (required != actual) {
- Py_DECREF(callargs);
- PyErr_Format(PyExc_TypeError,
- "this function takes %d argument%s (%d given)",
- required,
- required == 1 ? "" : "s",
- actual);
- return NULL;
- }
- }
-
- result = _ctypes_callproc(pProc,
- callargs,
+ callargs = _build_callargs(self, argtypes,
+ inargs, kwds,
+ &outmask, &inoutmask, &numretvals);
+ if (callargs == NULL)
+ return NULL;
+
+ if (converters) {
+ int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
+ Py_ssize_t, int);
+ int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
+ Py_ssize_t, int);
+
+ if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
+ /* For cdecl functions, we allow more actual arguments
+ than the length of the argtypes tuple.
+ */
+ if (required > actual) {
+ Py_DECREF(callargs);
+ PyErr_Format(PyExc_TypeError,
+ "this function takes at least %d argument%s (%d given)",
+ required,
+ required == 1 ? "" : "s",
+ actual);
+ return NULL;
+ }
+ } else if (required != actual) {
+ Py_DECREF(callargs);
+ PyErr_Format(PyExc_TypeError,
+ "this function takes %d argument%s (%d given)",
+ required,
+ required == 1 ? "" : "s",
+ actual);
+ return NULL;
+ }
+ }
+
+ result = _ctypes_callproc(pProc,
+ callargs,
#ifdef MS_WIN32
- piunk,
- self->iid,
+ piunk,
+ self->iid,
#endif
- dict->flags,
- converters,
- restype,
- checker);
+ dict->flags,
+ converters,
+ restype,
+ checker);
/* The 'errcheck' protocol */
- if (result != NULL && errcheck) {
- PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
- result,
- self,
- callargs,
- NULL);
- /* If the errcheck funtion failed, return NULL.
- If the errcheck function returned callargs unchanged,
- continue normal processing.
- If the errcheck function returned something else,
- use that as result.
- */
- if (v == NULL || v != callargs) {
- Py_DECREF(result);
- Py_DECREF(callargs);
- return v;
- }
- Py_DECREF(v);
- }
-
- return _build_result(result, callargs,
- outmask, inoutmask, numretvals);
+ if (result != NULL && errcheck) {
+ PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
+ result,
+ self,
+ callargs,
+ NULL);
+ /* If the errcheck funtion failed, return NULL.
+ If the errcheck function returned callargs unchanged,
+ continue normal processing.
+ If the errcheck function returned something else,
+ use that as result.
+ */
+ if (v == NULL || v != callargs) {
+ Py_DECREF(result);
+ Py_DECREF(callargs);
+ return v;
+ }
+ Py_DECREF(v);
+ }
+
+ return _build_result(result, callargs,
+ outmask, inoutmask, numretvals);
}
static int
PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->callable);
- Py_VISIT(self->restype);
- Py_VISIT(self->checker);
- Py_VISIT(self->errcheck);
- Py_VISIT(self->argtypes);
- Py_VISIT(self->converters);
- Py_VISIT(self->paramflags);
- Py_VISIT(self->thunk);
- return PyCData_traverse((CDataObject *)self, visit, arg);
+ Py_VISIT(self->callable);
+ Py_VISIT(self->restype);
+ Py_VISIT(self->checker);
+ Py_VISIT(self->errcheck);
+ Py_VISIT(self->argtypes);
+ Py_VISIT(self->converters);
+ Py_VISIT(self->paramflags);
+ Py_VISIT(self->thunk);
+ return PyCData_traverse((CDataObject *)self, visit, arg);
}
static int
PyCFuncPtr_clear(PyCFuncPtrObject *self)
{
- Py_CLEAR(self->callable);
- Py_CLEAR(self->restype);
- Py_CLEAR(self->checker);
- Py_CLEAR(self->errcheck);
- Py_CLEAR(self->argtypes);
- Py_CLEAR(self->converters);
- Py_CLEAR(self->paramflags);
- Py_CLEAR(self->thunk);
- return PyCData_clear((CDataObject *)self);
+ Py_CLEAR(self->callable);
+ Py_CLEAR(self->restype);
+ Py_CLEAR(self->checker);
+ Py_CLEAR(self->errcheck);
+ Py_CLEAR(self->argtypes);
+ Py_CLEAR(self->converters);
+ Py_CLEAR(self->paramflags);
+ Py_CLEAR(self->thunk);
+ return PyCData_clear((CDataObject *)self);
}
static void
PyCFuncPtr_dealloc(PyCFuncPtrObject *self)
{
- PyCFuncPtr_clear(self);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ PyCFuncPtr_clear(self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
PyCFuncPtr_repr(PyCFuncPtrObject *self)
{
#ifdef MS_WIN32
- if (self->index)
- return PyUnicode_FromFormat("<COM method offset %d: %s at %p>",
- self->index - 0x1000,
- Py_TYPE(self)->tp_name,
- self);
+ if (self->index)
+ return PyUnicode_FromFormat("<COM method offset %d: %s at %p>",
+ self->index - 0x1000,
+ Py_TYPE(self)->tp_name,
+ self);
#endif
- return PyUnicode_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name,
- self);
+ return PyUnicode_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name,
+ self);
}
static int
PyCFuncPtr_bool(PyCFuncPtrObject *self)
{
- return ((*(void **)self->b_ptr != NULL)
+ return ((*(void **)self->b_ptr != NULL)
#ifdef MS_WIN32
- || (self->index != 0)
+ || (self->index != 0)
#endif
- );
+ );
}
static PyNumberMethods PyCFuncPtr_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)PyCFuncPtr_bool, /* nb_bool */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)PyCFuncPtr_bool, /* nb_bool */
};
PyTypeObject PyCFuncPtr_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCFuncPtr",
- sizeof(PyCFuncPtrObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)PyCFuncPtr_repr, /* tp_repr */
- &PyCFuncPtr_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)PyCFuncPtr_call, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Function Pointer", /* tp_doc */
- (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */
- (inquiry)PyCFuncPtr_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- PyCFuncPtr_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCFuncPtr_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCFuncPtr",
+ sizeof(PyCFuncPtrObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)PyCFuncPtr_repr, /* tp_repr */
+ &PyCFuncPtr_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)PyCFuncPtr_call, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Function Pointer", /* tp_doc */
+ (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */
+ (inquiry)PyCFuncPtr_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ PyCFuncPtr_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCFuncPtr_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/*****************************************************************/
/*
Struct_Type
@@ -3941,61 +3941,61 @@ PyTypeObject PyCFuncPtr_Type = {
*/
static int
_init_pos_args(PyObject *self, PyTypeObject *type,
- PyObject *args, PyObject *kwds,
- int index)
+ PyObject *args, PyObject *kwds,
+ int index)
{
- StgDictObject *dict;
- PyObject *fields;
- int i;
-
- if (PyType_stgdict((PyObject *)type->tp_base)) {
- index = _init_pos_args(self, type->tp_base,
- args, kwds,
- index);
- if (index == -1)
- return -1;
- }
-
- dict = PyType_stgdict((PyObject *)type);
- fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
- if (fields == NULL)
- return index;
-
- for (i = 0;
- i < dict->length && (i+index) < PyTuple_GET_SIZE(args);
- ++i) {
- PyObject *pair = PySequence_GetItem(fields, i);
- PyObject *name, *val;
- int res;
- if (!pair)
- return -1;
- name = PySequence_GetItem(pair, 0);
- if (!name) {
- Py_DECREF(pair);
- return -1;
- }
- val = PyTuple_GET_ITEM(args, i + index);
- if (kwds && PyDict_GetItem(kwds, name)) {
- char *field = PyBytes_AsString(name);
- if (field == NULL) {
- PyErr_Clear();
- field = "???";
- }
- PyErr_Format(PyExc_TypeError,
- "duplicate values for field '%s'",
- field);
- Py_DECREF(pair);
- Py_DECREF(name);
- return -1;
- }
-
- res = PyObject_SetAttr(self, name, val);
- Py_DECREF(pair);
- Py_DECREF(name);
- if (res == -1)
- return -1;
- }
- return index + dict->length;
+ StgDictObject *dict;
+ PyObject *fields;
+ int i;
+
+ if (PyType_stgdict((PyObject *)type->tp_base)) {
+ index = _init_pos_args(self, type->tp_base,
+ args, kwds,
+ index);
+ if (index == -1)
+ return -1;
+ }
+
+ dict = PyType_stgdict((PyObject *)type);
+ fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
+ if (fields == NULL)
+ return index;
+
+ for (i = 0;
+ i < dict->length && (i+index) < PyTuple_GET_SIZE(args);
+ ++i) {
+ PyObject *pair = PySequence_GetItem(fields, i);
+ PyObject *name, *val;
+ int res;
+ if (!pair)
+ return -1;
+ name = PySequence_GetItem(pair, 0);
+ if (!name) {
+ Py_DECREF(pair);
+ return -1;
+ }
+ val = PyTuple_GET_ITEM(args, i + index);
+ if (kwds && PyDict_GetItem(kwds, name)) {
+ char *field = PyBytes_AsString(name);
+ if (field == NULL) {
+ PyErr_Clear();
+ field = "???";
+ }
+ PyErr_Format(PyExc_TypeError,
+ "duplicate values for field '%s'",
+ field);
+ Py_DECREF(pair);
+ Py_DECREF(name);
+ return -1;
+ }
+
+ res = PyObject_SetAttr(self, name, val);
+ Py_DECREF(pair);
+ Py_DECREF(name);
+ if (res == -1)
+ return -1;
+ }
+ return index + dict->length;
}
static int
@@ -4004,119 +4004,119 @@ Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
/* Optimization possible: Store the attribute names _fields_[x][0]
* in C accessible fields somewhere ?
*/
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_TypeError,
- "args not a tuple?");
- return -1;
- }
- if (PyTuple_GET_SIZE(args)) {
- int res = _init_pos_args(self, Py_TYPE(self),
- args, kwds, 0);
- if (res == -1)
- return -1;
- if (res < PyTuple_GET_SIZE(args)) {
- PyErr_SetString(PyExc_TypeError,
- "too many initializers");
- return -1;
- }
- }
-
- if (kwds) {
- PyObject *key, *value;
- Py_ssize_t pos = 0;
- while(PyDict_Next(kwds, &pos, &key, &value)) {
- if (-1 == PyObject_SetAttr(self, key, value))
- return -1;
- }
- }
- return 0;
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "args not a tuple?");
+ return -1;
+ }
+ if (PyTuple_GET_SIZE(args)) {
+ int res = _init_pos_args(self, Py_TYPE(self),
+ args, kwds, 0);
+ if (res == -1)
+ return -1;
+ if (res < PyTuple_GET_SIZE(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "too many initializers");
+ return -1;
+ }
+ }
+
+ if (kwds) {
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+ while(PyDict_Next(kwds, &pos, &key, &value)) {
+ if (-1 == PyObject_SetAttr(self, key, value))
+ return -1;
+ }
+ }
+ return 0;
}
static PyTypeObject Struct_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.Structure",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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 */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Structure base class", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- Struct_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.Structure",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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 */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Structure base class", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ Struct_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
static PyTypeObject Union_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.Union",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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 */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Union base class", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- Struct_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.Union",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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 */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Union base class", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ Struct_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCArray_Type
@@ -4124,371 +4124,371 @@ static PyTypeObject Union_Type = {
static int
Array_init(CDataObject *self, PyObject *args, PyObject *kw)
{
- Py_ssize_t i;
- Py_ssize_t n;
-
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_TypeError,
- "args not a tuple?");
- return -1;
- }
- n = PyTuple_GET_SIZE(args);
- for (i = 0; i < n; ++i) {
- PyObject *v;
- v = PyTuple_GET_ITEM(args, i);
- if (-1 == PySequence_SetItem((PyObject *)self, i, v))
- return -1;
- }
- return 0;
+ Py_ssize_t i;
+ Py_ssize_t n;
+
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "args not a tuple?");
+ return -1;
+ }
+ n = PyTuple_GET_SIZE(args);
+ for (i = 0; i < n; ++i) {
+ PyObject *v;
+ v = PyTuple_GET_ITEM(args, i);
+ if (-1 == PySequence_SetItem((PyObject *)self, i, v))
+ return -1;
+ }
+ return 0;
}
static PyObject *
Array_item(PyObject *_self, Py_ssize_t index)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t offset, size;
- StgDictObject *stgdict;
-
-
- if (index < 0 || index >= self->b_length) {
- PyErr_SetString(PyExc_IndexError,
- "invalid index");
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array instances */
- /* Would it be clearer if we got the item size from
- stgdict->proto's stgdict?
- */
- size = stgdict->size / stgdict->length;
- offset = index * size;
-
- return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
- index, size, self->b_ptr + offset);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t offset, size;
+ StgDictObject *stgdict;
+
+
+ if (index < 0 || index >= self->b_length) {
+ PyErr_SetString(PyExc_IndexError,
+ "invalid index");
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array instances */
+ /* Would it be clearer if we got the item size from
+ stgdict->proto's stgdict?
+ */
+ size = stgdict->size / stgdict->length;
+ offset = index * size;
+
+ return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
+ index, size, self->b_ptr + offset);
}
static PyObject *
Array_subscript(PyObject *_self, PyObject *item)
{
- CDataObject *self = (CDataObject *)_self;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += self->b_length;
- return Array_item(_self, i);
- }
- else if PySlice_Check(item) {
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- PyObject *np;
- Py_ssize_t start, stop, step, slicelen, cur, i;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- self->b_length, &start, &stop,
- &step, &slicelen) < 0) {
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array object instances */
- proto = stgdict->proto;
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* proto is the item type of the array, a
- ctypes type, so this cannot be NULL */
-
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *ptr = (char *)self->b_ptr;
- char *dest;
-
- if (slicelen <= 0)
- return PyBytes_FromStringAndSize("", 0);
- if (step == 1) {
- return PyBytes_FromStringAndSize(ptr + start,
- slicelen);
- }
- dest = (char *)PyMem_Malloc(slicelen);
-
- if (dest == NULL)
- return PyErr_NoMemory();
-
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- dest[i] = ptr[cur];
- }
-
- np = PyBytes_FromStringAndSize(dest, slicelen);
- PyMem_Free(dest);
- return np;
- }
+ CDataObject *self = (CDataObject *)_self;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += self->b_length;
+ return Array_item(_self, i);
+ }
+ else if PySlice_Check(item) {
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ PyObject *np;
+ Py_ssize_t start, stop, step, slicelen, cur, i;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ self->b_length, &start, &stop,
+ &step, &slicelen) < 0) {
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array object instances */
+ proto = stgdict->proto;
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* proto is the item type of the array, a
+ ctypes type, so this cannot be NULL */
+
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ char *ptr = (char *)self->b_ptr;
+ char *dest;
+
+ if (slicelen <= 0)
+ return PyBytes_FromStringAndSize("", 0);
+ if (step == 1) {
+ return PyBytes_FromStringAndSize(ptr + start,
+ slicelen);
+ }
+ dest = (char *)PyMem_Malloc(slicelen);
+
+ if (dest == NULL)
+ return PyErr_NoMemory();
+
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+
+ np = PyBytes_FromStringAndSize(dest, slicelen);
+ PyMem_Free(dest);
+ return np;
+ }
#ifdef CTYPES_UNICODE
- if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- wchar_t *ptr = (wchar_t *)self->b_ptr;
- wchar_t *dest;
-
- if (slicelen <= 0)
- return PyUnicode_FromUnicode(NULL, 0);
- if (step == 1) {
- return PyUnicode_FromWideChar(ptr + start,
- slicelen);
- }
-
- dest = (wchar_t *)PyMem_Malloc(
- slicelen * sizeof(wchar_t));
-
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- dest[i] = ptr[cur];
- }
-
- np = PyUnicode_FromWideChar(dest, slicelen);
- PyMem_Free(dest);
- return np;
- }
+ if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ wchar_t *ptr = (wchar_t *)self->b_ptr;
+ wchar_t *dest;
+
+ if (slicelen <= 0)
+ return PyUnicode_FromUnicode(NULL, 0);
+ if (step == 1) {
+ return PyUnicode_FromWideChar(ptr + start,
+ slicelen);
+ }
+
+ dest = (wchar_t *)PyMem_Malloc(
+ slicelen * sizeof(wchar_t));
+
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+
+ np = PyUnicode_FromWideChar(dest, slicelen);
+ PyMem_Free(dest);
+ return np;
+ }
#endif
- np = PyList_New(slicelen);
- if (np == NULL)
- return NULL;
-
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- PyObject *v = Array_item(_self, cur);
- PyList_SET_ITEM(np, i, v);
- }
- return np;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "indices must be integers");
- return NULL;
- }
+ np = PyList_New(slicelen);
+ if (np == NULL)
+ return NULL;
+
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ PyObject *v = Array_item(_self, cur);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return np;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "indices must be integers");
+ return NULL;
+ }
}
static int
Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t size, offset;
- StgDictObject *stgdict;
- char *ptr;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Array does not support item deletion");
- return -1;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array object instances */
- if (index < 0 || index >= stgdict->length) {
- PyErr_SetString(PyExc_IndexError,
- "invalid index");
- return -1;
- }
- size = stgdict->size / stgdict->length;
- offset = index * size;
- ptr = self->b_ptr + offset;
-
- return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
- index, size, ptr);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t size, offset;
+ StgDictObject *stgdict;
+ char *ptr;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Array does not support item deletion");
+ return -1;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array object instances */
+ if (index < 0 || index >= stgdict->length) {
+ PyErr_SetString(PyExc_IndexError,
+ "invalid index");
+ return -1;
+ }
+ size = stgdict->size / stgdict->length;
+ offset = index * size;
+ ptr = self->b_ptr + offset;
+
+ return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
+ index, size, ptr);
}
static int
Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Array does not support item deletion");
- return -1;
- }
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += self->b_length;
- return Array_ass_item(_self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- self->b_length, &start, &stop,
- &step, &slicelen) < 0) {
- return -1;
- }
- if ((step < 0 && start < stop) ||
- (step > 0 && start > stop))
- stop = start;
-
- otherlen = PySequence_Length(value);
- if (otherlen != slicelen) {
- PyErr_SetString(PyExc_ValueError,
- "Can only assign sequence of same size");
- return -1;
- }
- for (cur = start, i = 0; i < otherlen; cur += step, i++) {
- PyObject *item = PySequence_GetItem(value, i);
- int result;
- if (item == NULL)
- return -1;
- result = Array_ass_item(_self, cur, item);
- Py_DECREF(item);
- if (result == -1)
- return -1;
- }
- return 0;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "indices must be integer");
- return -1;
- }
+ CDataObject *self = (CDataObject *)_self;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Array does not support item deletion");
+ return -1;
+ }
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += self->b_length;
+ return Array_ass_item(_self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ self->b_length, &start, &stop,
+ &step, &slicelen) < 0) {
+ return -1;
+ }
+ if ((step < 0 && start < stop) ||
+ (step > 0 && start > stop))
+ stop = start;
+
+ otherlen = PySequence_Length(value);
+ if (otherlen != slicelen) {
+ PyErr_SetString(PyExc_ValueError,
+ "Can only assign sequence of same size");
+ return -1;
+ }
+ for (cur = start, i = 0; i < otherlen; cur += step, i++) {
+ PyObject *item = PySequence_GetItem(value, i);
+ int result;
+ if (item == NULL)
+ return -1;
+ result = Array_ass_item(_self, cur, item);
+ Py_DECREF(item);
+ if (result == -1)
+ return -1;
+ }
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "indices must be integer");
+ return -1;
+ }
}
static Py_ssize_t
Array_length(PyObject *_self)
{
- CDataObject *self = (CDataObject *)_self;
- return self->b_length;
+ CDataObject *self = (CDataObject *)_self;
+ return self->b_length;
}
static PySequenceMethods Array_as_sequence = {
- Array_length, /* sq_length; */
- 0, /* sq_concat; */
- 0, /* sq_repeat; */
- Array_item, /* sq_item; */
- 0, /* sq_slice; */
- Array_ass_item, /* sq_ass_item; */
- 0, /* sq_ass_slice; */
- 0, /* sq_contains; */
-
- 0, /* sq_inplace_concat; */
- 0, /* sq_inplace_repeat; */
+ Array_length, /* sq_length; */
+ 0, /* sq_concat; */
+ 0, /* sq_repeat; */
+ Array_item, /* sq_item; */
+ 0, /* sq_slice; */
+ Array_ass_item, /* sq_ass_item; */
+ 0, /* sq_ass_slice; */
+ 0, /* sq_contains; */
+
+ 0, /* sq_inplace_concat; */
+ 0, /* sq_inplace_repeat; */
};
static PyMappingMethods Array_as_mapping = {
- Array_length,
- Array_subscript,
- Array_ass_subscript,
+ Array_length,
+ Array_subscript,
+ Array_ass_subscript,
};
PyTypeObject PyCArray_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.Array",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &Array_as_sequence, /* tp_as_sequence */
- &Array_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Array_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.Array",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &Array_as_sequence, /* tp_as_sequence */
+ &Array_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Array_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
PyObject *
PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length)
{
- static PyObject *cache;
- PyObject *key;
- PyObject *result;
- char name[256];
- PyObject *len;
-
- if (cache == NULL) {
- cache = PyDict_New();
- if (cache == NULL)
- return NULL;
- }
- len = PyLong_FromSsize_t(length);
- if (len == NULL)
- return NULL;
- key = PyTuple_Pack(2, itemtype, len);
- Py_DECREF(len);
- if (!key)
- return NULL;
- result = PyDict_GetItemProxy(cache, key);
- if (result) {
- Py_INCREF(result);
- Py_DECREF(key);
- return result;
- }
-
- if (!PyType_Check(itemtype)) {
- PyErr_SetString(PyExc_TypeError,
- "Expected a type object");
- return NULL;
- }
+ static PyObject *cache;
+ PyObject *key;
+ PyObject *result;
+ char name[256];
+ PyObject *len;
+
+ if (cache == NULL) {
+ cache = PyDict_New();
+ if (cache == NULL)
+ return NULL;
+ }
+ len = PyLong_FromSsize_t(length);
+ if (len == NULL)
+ return NULL;
+ key = PyTuple_Pack(2, itemtype, len);
+ Py_DECREF(len);
+ if (!key)
+ return NULL;
+ result = PyDict_GetItemProxy(cache, key);
+ if (result) {
+ Py_INCREF(result);
+ Py_DECREF(key);
+ return result;
+ }
+
+ if (!PyType_Check(itemtype)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected a type object");
+ return NULL;
+ }
#ifdef MS_WIN64
- sprintf(name, "%.200s_Array_%Id",
- ((PyTypeObject *)itemtype)->tp_name, length);
+ sprintf(name, "%.200s_Array_%Id",
+ ((PyTypeObject *)itemtype)->tp_name, length);
#else
- sprintf(name, "%.200s_Array_%ld",
- ((PyTypeObject *)itemtype)->tp_name, (long)length);
+ sprintf(name, "%.200s_Array_%ld",
+ ((PyTypeObject *)itemtype)->tp_name, (long)length);
#endif
- result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type,
- "U(O){s:n,s:O}",
- name,
- &PyCArray_Type,
- "_length_",
- length,
- "_type_",
- itemtype
- );
- if (result == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- if (-1 == PyDict_SetItemProxy(cache, key, result)) {
- Py_DECREF(key);
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(key);
- return result;
+ result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type,
+ "U(O){s:n,s:O}",
+ name,
+ &PyCArray_Type,
+ "_length_",
+ length,
+ "_type_",
+ itemtype
+ );
+ if (result == NULL) {
+ Py_DECREF(key);
+ return NULL;
+ }
+ if (-1 == PyDict_SetItemProxy(cache, key, result)) {
+ Py_DECREF(key);
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(key);
+ return result;
}
-
+
/******************************************************************/
/*
Simple_Type
@@ -4497,166 +4497,166 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length)
static int
Simple_set_value(CDataObject *self, PyObject *value)
{
- PyObject *result;
- StgDictObject *dict = PyObject_stgdict((PyObject *)self);
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
- assert(dict); /* Cannot be NULL for CDataObject instances */
- assert(dict->setfunc);
- result = dict->setfunc(self->b_ptr, value, dict->size);
- if (!result)
- return -1;
-
- /* consumes the refcount the setfunc returns */
- return KeepRef(self, 0, result);
+ PyObject *result;
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ assert(dict->setfunc);
+ result = dict->setfunc(self->b_ptr, value, dict->size);
+ if (!result)
+ return -1;
+
+ /* consumes the refcount the setfunc returns */
+ return KeepRef(self, 0, result);
}
static int
Simple_init(CDataObject *self, PyObject *args, PyObject *kw)
{
- PyObject *value = NULL;
- if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
- return -1;
- if (value)
- return Simple_set_value(self, value);
- return 0;
+ PyObject *value = NULL;
+ if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
+ return -1;
+ if (value)
+ return Simple_set_value(self, value);
+ return 0;
}
static PyObject *
Simple_get_value(CDataObject *self)
{
- StgDictObject *dict;
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CDataObject instances */
- assert(dict->getfunc);
- return dict->getfunc(self->b_ptr, self->b_size);
+ StgDictObject *dict;
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ assert(dict->getfunc);
+ return dict->getfunc(self->b_ptr, self->b_size);
}
static PyGetSetDef Simple_getsets[] = {
- { "value", (getter)Simple_get_value, (setter)Simple_set_value,
- "current value", NULL },
- { NULL, NULL }
+ { "value", (getter)Simple_get_value, (setter)Simple_set_value,
+ "current value", NULL },
+ { NULL, NULL }
};
static PyObject *
Simple_from_outparm(PyObject *self, PyObject *args)
{
- if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) {
- Py_INCREF(self);
- return self;
- }
- /* call stgdict->getfunc */
- return Simple_get_value((CDataObject *)self);
+ if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) {
+ Py_INCREF(self);
+ return self;
+ }
+ /* call stgdict->getfunc */
+ return Simple_get_value((CDataObject *)self);
}
static PyMethodDef Simple_methods[] = {
- { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, },
- { NULL, NULL },
+ { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, },
+ { NULL, NULL },
};
static int Simple_bool(CDataObject *self)
{
- return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
+ return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
}
static PyNumberMethods Simple_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)Simple_bool, /* nb_bool */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)Simple_bool, /* nb_bool */
};
/* "%s(%s)" % (self.__class__.__name__, self.value) */
static PyObject *
Simple_repr(CDataObject *self)
{
- PyObject *val, *name, *args, *result;
- static PyObject *format;
-
- if (Py_TYPE(self)->tp_base != &Simple_Type) {
- return PyUnicode_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name, self);
- }
-
- if (format == NULL) {
- format = PyUnicode_InternFromString("%s(%r)");
- if (format == NULL)
- return NULL;
- }
-
- val = Simple_get_value(self);
- if (val == NULL)
- return NULL;
-
- name = PyUnicode_FromString(Py_TYPE(self)->tp_name);
- if (name == NULL) {
- Py_DECREF(val);
- return NULL;
- }
-
- args = PyTuple_Pack(2, name, val);
- Py_DECREF(name);
- Py_DECREF(val);
- if (args == NULL)
- return NULL;
-
- result = PyUnicode_Format(format, args);
- Py_DECREF(args);
- return result;
+ PyObject *val, *name, *args, *result;
+ static PyObject *format;
+
+ if (Py_TYPE(self)->tp_base != &Simple_Type) {
+ return PyUnicode_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name, self);
+ }
+
+ if (format == NULL) {
+ format = PyUnicode_InternFromString("%s(%r)");
+ if (format == NULL)
+ return NULL;
+ }
+
+ val = Simple_get_value(self);
+ if (val == NULL)
+ return NULL;
+
+ name = PyUnicode_FromString(Py_TYPE(self)->tp_name);
+ if (name == NULL) {
+ Py_DECREF(val);
+ return NULL;
+ }
+
+ args = PyTuple_Pack(2, name, val);
+ Py_DECREF(name);
+ Py_DECREF(val);
+ if (args == NULL)
+ return NULL;
+
+ result = PyUnicode_Format(format, args);
+ Py_DECREF(args);
+ return result;
}
static PyTypeObject Simple_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._SimpleCData",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)&Simple_repr, /* tp_repr */
- &Simple_as_number, /* 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 */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Simple_methods, /* tp_methods */
- 0, /* tp_members */
- Simple_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Simple_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes._SimpleCData",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)&Simple_repr, /* tp_repr */
+ &Simple_as_number, /* 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 */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Simple_methods, /* tp_methods */
+ 0, /* tp_members */
+ Simple_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Simple_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCPointer_Type
@@ -4664,377 +4664,377 @@ static PyTypeObject Simple_Type = {
static PyObject *
Pointer_item(PyObject *_self, Py_ssize_t index)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t size;
- Py_ssize_t offset;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
-
- if (*(void **)self->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL pointer access");
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for pointer object instances */
-
- proto = stgdict->proto;
- assert(proto);
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* proto is the item type of the pointer, a ctypes
- type, so this cannot be NULL */
-
- size = itemdict->size;
- offset = index * itemdict->size;
-
- return PyCData_get(proto, stgdict->getfunc, (PyObject *)self,
- index, size, (*(char **)self->b_ptr) + offset);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t size;
+ Py_ssize_t offset;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+
+ if (*(void **)self->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL pointer access");
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for pointer object instances */
+
+ proto = stgdict->proto;
+ assert(proto);
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* proto is the item type of the pointer, a ctypes
+ type, so this cannot be NULL */
+
+ size = itemdict->size;
+ offset = index * itemdict->size;
+
+ return PyCData_get(proto, stgdict->getfunc, (PyObject *)self,
+ index, size, (*(char **)self->b_ptr) + offset);
}
static int
Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t size;
- Py_ssize_t offset;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Pointer does not support item deletion");
- return -1;
- }
-
- if (*(void **)self->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL pointer access");
- return -1;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
-
- proto = stgdict->proto;
- assert(proto);
-
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* Cannot be NULL because the itemtype of a pointer
- is always a ctypes type */
-
- size = itemdict->size;
- offset = index * itemdict->size;
-
- return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value,
- index, size, (*(char **)self->b_ptr) + offset);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t size;
+ Py_ssize_t offset;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer does not support item deletion");
+ return -1;
+ }
+
+ if (*(void **)self->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL pointer access");
+ return -1;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+
+ proto = stgdict->proto;
+ assert(proto);
+
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* Cannot be NULL because the itemtype of a pointer
+ is always a ctypes type */
+
+ size = itemdict->size;
+ offset = index * itemdict->size;
+
+ return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value,
+ index, size, (*(char **)self->b_ptr) + offset);
}
static PyObject *
Pointer_get_contents(CDataObject *self, void *closure)
{
- StgDictObject *stgdict;
-
- if (*(void **)self->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL pointer access");
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
- return PyCData_FromBaseObj(stgdict->proto,
- (PyObject *)self, 0,
- *(void **)self->b_ptr);
+ StgDictObject *stgdict;
+
+ if (*(void **)self->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL pointer access");
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+ return PyCData_FromBaseObj(stgdict->proto,
+ (PyObject *)self, 0,
+ *(void **)self->b_ptr);
}
static int
Pointer_set_contents(CDataObject *self, PyObject *value, void *closure)
{
- StgDictObject *stgdict;
- CDataObject *dst;
- PyObject *keep;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Pointer does not support item deletion");
- return -1;
- }
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
- assert(stgdict->proto);
- if (!CDataObject_Check(value)
- || 0 == PyObject_IsInstance(value, stgdict->proto)) {
- /* XXX PyObject_IsInstance could return -1! */
- PyErr_Format(PyExc_TypeError,
- "expected %s instead of %s",
- ((PyTypeObject *)(stgdict->proto))->tp_name,
- Py_TYPE(value)->tp_name);
- return -1;
- }
-
- dst = (CDataObject *)value;
- *(void **)self->b_ptr = dst->b_ptr;
-
- /*
- A Pointer instance must keep a the value it points to alive. So, a
- pointer instance has b_length set to 2 instead of 1, and we set
- 'value' itself as the second item of the b_objects list, additionally.
- */
- Py_INCREF(value);
- if (-1 == KeepRef(self, 1, value))
- return -1;
-
- keep = GetKeepedObjects(dst);
- Py_INCREF(keep);
- return KeepRef(self, 0, keep);
+ StgDictObject *stgdict;
+ CDataObject *dst;
+ PyObject *keep;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer does not support item deletion");
+ return -1;
+ }
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+ assert(stgdict->proto);
+ if (!CDataObject_Check(value)
+ || 0 == PyObject_IsInstance(value, stgdict->proto)) {
+ /* XXX PyObject_IsInstance could return -1! */
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instead of %s",
+ ((PyTypeObject *)(stgdict->proto))->tp_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
+ dst = (CDataObject *)value;
+ *(void **)self->b_ptr = dst->b_ptr;
+
+ /*
+ A Pointer instance must keep a the value it points to alive. So, a
+ pointer instance has b_length set to 2 instead of 1, and we set
+ 'value' itself as the second item of the b_objects list, additionally.
+ */
+ Py_INCREF(value);
+ if (-1 == KeepRef(self, 1, value))
+ return -1;
+
+ keep = GetKeepedObjects(dst);
+ Py_INCREF(keep);
+ return KeepRef(self, 0, keep);
}
static PyGetSetDef Pointer_getsets[] = {
- { "contents", (getter)Pointer_get_contents,
- (setter)Pointer_set_contents,
- "the object this pointer points to (read-write)", NULL },
- { NULL, NULL }
+ { "contents", (getter)Pointer_get_contents,
+ (setter)Pointer_set_contents,
+ "the object this pointer points to (read-write)", NULL },
+ { NULL, NULL }
};
static int
Pointer_init(CDataObject *self, PyObject *args, PyObject *kw)
{
- PyObject *value = NULL;
+ PyObject *value = NULL;
- if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
- return -1;
- if (value == NULL)
- return 0;
- return Pointer_set_contents(self, value, NULL);
+ if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
+ return -1;
+ if (value == NULL)
+ return 0;
+ return Pointer_set_contents(self, value, NULL);
}
static PyObject *
Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- StgDictObject *dict = PyType_stgdict((PyObject *)type);
- if (!dict || !dict->proto) {
- PyErr_SetString(PyExc_TypeError,
- "Cannot create instance: has no _type_");
- return NULL;
- }
- return GenericPyCData_new(type, args, kw);
+ StgDictObject *dict = PyType_stgdict((PyObject *)type);
+ if (!dict || !dict->proto) {
+ PyErr_SetString(PyExc_TypeError,
+ "Cannot create instance: has no _type_");
+ return NULL;
+ }
+ return GenericPyCData_new(type, args, kw);
}
static PyObject *
Pointer_subscript(PyObject *_self, PyObject *item)
{
- CDataObject *self = (CDataObject *)_self;
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- return Pointer_item(_self, i);
- }
- else if (PySlice_Check(item)) {
- PySliceObject *slice = (PySliceObject *)item;
- Py_ssize_t start, stop, step;
- PyObject *np;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- Py_ssize_t i, len, cur;
-
- /* Since pointers have no length, and we want to apply
- different semantics to negative indices than normal
- slicing, we have to dissect the slice object ourselves.*/
- if (slice->step == Py_None) {
- step = 1;
- }
- else {
- step = PyNumber_AsSsize_t(slice->step,
- PyExc_ValueError);
- if (step == -1 && PyErr_Occurred())
- return NULL;
- if (step == 0) {
- PyErr_SetString(PyExc_ValueError,
- "slice step cannot be zero");
- return NULL;
- }
- }
- if (slice->start == Py_None) {
- if (step < 0) {
- PyErr_SetString(PyExc_ValueError,
- "slice start is required "
- "for step < 0");
- return NULL;
- }
- start = 0;
- }
- else {
- start = PyNumber_AsSsize_t(slice->start,
- PyExc_ValueError);
- if (start == -1 && PyErr_Occurred())
- return NULL;
- }
- if (slice->stop == Py_None) {
- PyErr_SetString(PyExc_ValueError,
- "slice stop is required");
- return NULL;
- }
- stop = PyNumber_AsSsize_t(slice->stop,
- PyExc_ValueError);
- if (stop == -1 && PyErr_Occurred())
- return NULL;
- if ((step > 0 && start > stop) ||
- (step < 0 && start < stop))
- len = 0;
- else if (step > 0)
- len = (stop - start - 1) / step + 1;
- else
- len = (stop - start + 1) / step + 1;
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for pointer instances */
- proto = stgdict->proto;
- assert(proto);
- itemdict = PyType_stgdict(proto);
- assert(itemdict);
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *ptr = *(char **)self->b_ptr;
- char *dest;
-
- if (len <= 0)
- return PyBytes_FromStringAndSize("", 0);
- if (step == 1) {
- return PyBytes_FromStringAndSize(ptr + start,
- len);
- }
- dest = (char *)PyMem_Malloc(len);
- if (dest == NULL)
- return PyErr_NoMemory();
- for (cur = start, i = 0; i < len; cur += step, i++) {
- dest[i] = ptr[cur];
- }
- np = PyBytes_FromStringAndSize(dest, len);
- PyMem_Free(dest);
- return np;
- }
+ CDataObject *self = (CDataObject *)_self;
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ return Pointer_item(_self, i);
+ }
+ else if (PySlice_Check(item)) {
+ PySliceObject *slice = (PySliceObject *)item;
+ Py_ssize_t start, stop, step;
+ PyObject *np;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ Py_ssize_t i, len, cur;
+
+ /* Since pointers have no length, and we want to apply
+ different semantics to negative indices than normal
+ slicing, we have to dissect the slice object ourselves.*/
+ if (slice->step == Py_None) {
+ step = 1;
+ }
+ else {
+ step = PyNumber_AsSsize_t(slice->step,
+ PyExc_ValueError);
+ if (step == -1 && PyErr_Occurred())
+ return NULL;
+ if (step == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice step cannot be zero");
+ return NULL;
+ }
+ }
+ if (slice->start == Py_None) {
+ if (step < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice start is required "
+ "for step < 0");
+ return NULL;
+ }
+ start = 0;
+ }
+ else {
+ start = PyNumber_AsSsize_t(slice->start,
+ PyExc_ValueError);
+ if (start == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ if (slice->stop == Py_None) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice stop is required");
+ return NULL;
+ }
+ stop = PyNumber_AsSsize_t(slice->stop,
+ PyExc_ValueError);
+ if (stop == -1 && PyErr_Occurred())
+ return NULL;
+ if ((step > 0 && start > stop) ||
+ (step < 0 && start < stop))
+ len = 0;
+ else if (step > 0)
+ len = (stop - start - 1) / step + 1;
+ else
+ len = (stop - start + 1) / step + 1;
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for pointer instances */
+ proto = stgdict->proto;
+ assert(proto);
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict);
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ char *ptr = *(char **)self->b_ptr;
+ char *dest;
+
+ if (len <= 0)
+ return PyBytes_FromStringAndSize("", 0);
+ if (step == 1) {
+ return PyBytes_FromStringAndSize(ptr + start,
+ len);
+ }
+ dest = (char *)PyMem_Malloc(len);
+ if (dest == NULL)
+ return PyErr_NoMemory();
+ for (cur = start, i = 0; i < len; cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+ np = PyBytes_FromStringAndSize(dest, len);
+ PyMem_Free(dest);
+ return np;
+ }
#ifdef CTYPES_UNICODE
- if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- wchar_t *ptr = *(wchar_t **)self->b_ptr;
- wchar_t *dest;
-
- if (len <= 0)
- return PyUnicode_FromUnicode(NULL, 0);
- if (step == 1) {
- return PyUnicode_FromWideChar(ptr + start,
- len);
- }
- dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t));
- if (dest == NULL)
- return PyErr_NoMemory();
- for (cur = start, i = 0; i < len; cur += step, i++) {
- dest[i] = ptr[cur];
- }
- np = PyUnicode_FromWideChar(dest, len);
- PyMem_Free(dest);
- return np;
- }
+ if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ wchar_t *ptr = *(wchar_t **)self->b_ptr;
+ wchar_t *dest;
+
+ if (len <= 0)
+ return PyUnicode_FromUnicode(NULL, 0);
+ if (step == 1) {
+ return PyUnicode_FromWideChar(ptr + start,
+ len);
+ }
+ dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t));
+ if (dest == NULL)
+ return PyErr_NoMemory();
+ for (cur = start, i = 0; i < len; cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+ np = PyUnicode_FromWideChar(dest, len);
+ PyMem_Free(dest);
+ return np;
+ }
#endif
- np = PyList_New(len);
- if (np == NULL)
- return NULL;
-
- for (cur = start, i = 0; i < len; cur += step, i++) {
- PyObject *v = Pointer_item(_self, cur);
- PyList_SET_ITEM(np, i, v);
- }
- return np;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "Pointer indices must be integer");
- return NULL;
- }
+ np = PyList_New(len);
+ if (np == NULL)
+ return NULL;
+
+ for (cur = start, i = 0; i < len; cur += step, i++) {
+ PyObject *v = Pointer_item(_self, cur);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return np;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer indices must be integer");
+ return NULL;
+ }
}
static PySequenceMethods Pointer_as_sequence = {
- 0, /* inquiry sq_length; */
- 0, /* binaryfunc sq_concat; */
- 0, /* intargfunc sq_repeat; */
- Pointer_item, /* intargfunc sq_item; */
- 0, /* intintargfunc sq_slice; */
- Pointer_ass_item, /* intobjargproc sq_ass_item; */
- 0, /* intintobjargproc sq_ass_slice; */
- 0, /* objobjproc sq_contains; */
- /* Added in release 2.0 */
- 0, /* binaryfunc sq_inplace_concat; */
- 0, /* intargfunc sq_inplace_repeat; */
+ 0, /* inquiry sq_length; */
+ 0, /* binaryfunc sq_concat; */
+ 0, /* intargfunc sq_repeat; */
+ Pointer_item, /* intargfunc sq_item; */
+ 0, /* intintargfunc sq_slice; */
+ Pointer_ass_item, /* intobjargproc sq_ass_item; */
+ 0, /* intintobjargproc sq_ass_slice; */
+ 0, /* objobjproc sq_contains; */
+ /* Added in release 2.0 */
+ 0, /* binaryfunc sq_inplace_concat; */
+ 0, /* intargfunc sq_inplace_repeat; */
};
static PyMappingMethods Pointer_as_mapping = {
- 0,
- Pointer_subscript,
+ 0,
+ Pointer_subscript,
};
static int
Pointer_bool(CDataObject *self)
{
- return (*(void **)self->b_ptr != NULL);
+ return (*(void **)self->b_ptr != NULL);
}
static PyNumberMethods Pointer_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)Pointer_bool, /* nb_bool */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)Pointer_bool, /* nb_bool */
};
PyTypeObject PyCPointer_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._Pointer",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- &Pointer_as_number, /* tp_as_number */
- &Pointer_as_sequence, /* tp_as_sequence */
- &Pointer_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- Pointer_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Pointer_init, /* tp_init */
- 0, /* tp_alloc */
- Pointer_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes._Pointer",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ &Pointer_as_number, /* tp_as_number */
+ &Pointer_as_sequence, /* tp_as_sequence */
+ &Pointer_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ Pointer_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Pointer_init, /* tp_init */
+ 0, /* tp_alloc */
+ Pointer_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
* Module initialization.
@@ -5056,27 +5056,27 @@ comerror_init(PyObject *self, PyObject *args, PyObject *kwds)
int status;
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
- return -1;
+ return -1;
if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details))
- return -1;
+ return -1;
a = PySequence_GetSlice(args, 1, PySequence_Size(args));
if (!a)
- return -1;
+ return -1;
status = PyObject_SetAttrString(self, "args", a);
Py_DECREF(a);
if (status < 0)
- return -1;
+ return -1;
if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
- return -1;
+ return -1;
if (PyObject_SetAttrString(self, "text", text) < 0)
- return -1;
+ return -1;
if (PyObject_SetAttrString(self, "details", details) < 0)
- return -1;
+ return -1;
bself = (PyBaseExceptionObject *)self;
Py_DECREF(bself->args);
@@ -5131,11 +5131,11 @@ static PyTypeObject PyComError_Type = {
static int
create_comerror(void)
{
- PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception;
- if (PyType_Ready(&PyComError_Type) < 0)
- return -1;
- ComError = (PyObject*)&PyComError_Type;
- return 0;
+ PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception;
+ if (PyType_Ready(&PyComError_Type) < 0)
+ return -1;
+ ComError = (PyObject*)&PyComError_Type;
+ return 0;
}
#endif
@@ -5143,259 +5143,259 @@ create_comerror(void)
static PyObject *
string_at(const char *ptr, int size)
{
- if (size == -1)
- return PyBytes_FromStringAndSize(ptr, strlen(ptr));
- return PyBytes_FromStringAndSize(ptr, size);
+ if (size == -1)
+ return PyBytes_FromStringAndSize(ptr, strlen(ptr));
+ return PyBytes_FromStringAndSize(ptr, size);
}
static int
cast_check_pointertype(PyObject *arg)
{
- StgDictObject *dict;
-
- if (PyCPointerTypeObject_Check(arg))
- return 1;
- if (PyCFuncPtrTypeObject_Check(arg))
- return 1;
- dict = PyType_stgdict(arg);
- if (dict) {
- if (PyUnicode_Check(dict->proto)
- && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) {
- /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
- return 1;
- }
- }
- PyErr_Format(PyExc_TypeError,
- "cast() argument 2 must be a pointer type, not %s",
- PyType_Check(arg)
- ? ((PyTypeObject *)arg)->tp_name
- : Py_TYPE(arg)->tp_name);
- return 0;
+ StgDictObject *dict;
+
+ if (PyCPointerTypeObject_Check(arg))
+ return 1;
+ if (PyCFuncPtrTypeObject_Check(arg))
+ return 1;
+ dict = PyType_stgdict(arg);
+ if (dict) {
+ if (PyUnicode_Check(dict->proto)
+ && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) {
+ /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
+ return 1;
+ }
+ }
+ PyErr_Format(PyExc_TypeError,
+ "cast() argument 2 must be a pointer type, not %s",
+ PyType_Check(arg)
+ ? ((PyTypeObject *)arg)->tp_name
+ : Py_TYPE(arg)->tp_name);
+ return 0;
}
static PyObject *
cast(void *ptr, PyObject *src, PyObject *ctype)
{
- CDataObject *result;
- if (0 == cast_check_pointertype(ctype))
- return NULL;
- result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
- if (result == NULL)
- return NULL;
-
- /*
- The casted objects '_objects' member:
-
- It must certainly contain the source objects one.
- It must contain the source object itself.
- */
- if (CDataObject_Check(src)) {
- CDataObject *obj = (CDataObject *)src;
- /* PyCData_GetContainer will initialize src.b_objects, we need
- this so it can be shared */
- PyCData_GetContainer(obj);
- /* But we need a dictionary! */
- if (obj->b_objects == Py_None) {
- Py_DECREF(Py_None);
- obj->b_objects = PyDict_New();
- if (obj->b_objects == NULL)
- goto failed;
- }
- Py_XINCREF(obj->b_objects);
- result->b_objects = obj->b_objects;
- if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
- PyObject *index;
- int rc;
- index = PyLong_FromVoidPtr((void *)src);
- if (index == NULL)
- goto failed;
- rc = PyDict_SetItem(result->b_objects, index, src);
- Py_DECREF(index);
- if (rc == -1)
- goto failed;
- }
- }
- /* Should we assert that result is a pointer type? */
- memcpy(result->b_ptr, &ptr, sizeof(void *));
- return (PyObject *)result;
+ CDataObject *result;
+ if (0 == cast_check_pointertype(ctype))
+ return NULL;
+ result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
+ if (result == NULL)
+ return NULL;
+
+ /*
+ The casted objects '_objects' member:
+
+ It must certainly contain the source objects one.
+ It must contain the source object itself.
+ */
+ if (CDataObject_Check(src)) {
+ CDataObject *obj = (CDataObject *)src;
+ /* PyCData_GetContainer will initialize src.b_objects, we need
+ this so it can be shared */
+ PyCData_GetContainer(obj);
+ /* But we need a dictionary! */
+ if (obj->b_objects == Py_None) {
+ Py_DECREF(Py_None);
+ obj->b_objects = PyDict_New();
+ if (obj->b_objects == NULL)
+ goto failed;
+ }
+ Py_XINCREF(obj->b_objects);
+ result->b_objects = obj->b_objects;
+ if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
+ PyObject *index;
+ int rc;
+ index = PyLong_FromVoidPtr((void *)src);
+ if (index == NULL)
+ goto failed;
+ rc = PyDict_SetItem(result->b_objects, index, src);
+ Py_DECREF(index);
+ if (rc == -1)
+ goto failed;
+ }
+ }
+ /* Should we assert that result is a pointer type? */
+ memcpy(result->b_ptr, &ptr, sizeof(void *));
+ return (PyObject *)result;
failed:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
#ifdef CTYPES_UNICODE
static PyObject *
wstring_at(const wchar_t *ptr, int size)
{
- Py_ssize_t ssize = size;
- if (ssize == -1)
- ssize = wcslen(ptr);
- return PyUnicode_FromWideChar(ptr, ssize);
+ Py_ssize_t ssize = size;
+ if (ssize == -1)
+ ssize = wcslen(ptr);
+ return PyUnicode_FromWideChar(ptr, ssize);
}
#endif
static struct PyModuleDef _ctypesmodule = {
- PyModuleDef_HEAD_INIT,
- "_ctypes",
- module_docs,
- -1,
- _ctypes_module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_ctypes",
+ module_docs,
+ -1,
+ _ctypes_module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__ctypes(void)
{
- PyObject *m;
+ PyObject *m;
/* Note:
ob_type is the metatype (the 'type'), defaults to PyType_Type,
tp_base is the base type, defaults to 'object' aka PyBaseObject_Type.
*/
#ifdef WITH_THREAD
- PyEval_InitThreads();
+ PyEval_InitThreads();
#endif
- m = PyModule_Create(&_ctypesmodule);
- if (!m)
- return NULL;
-
- _ctypes_ptrtype_cache = PyDict_New();
- if (_ctypes_ptrtype_cache == NULL)
- return NULL;
-
- PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache);
-
- _unpickle = PyObject_GetAttrString(m, "_unpickle");
- if (_unpickle == NULL)
- return NULL;
-
- if (PyType_Ready(&PyCArg_Type) < 0)
- return NULL;
-
- if (PyType_Ready(&PyCThunk_Type) < 0)
- return NULL;
-
- /* StgDict is derived from PyDict_Type */
- PyCStgDict_Type.tp_base = &PyDict_Type;
- if (PyType_Ready(&PyCStgDict_Type) < 0)
- return NULL;
-
- /*************************************************
- *
- * Metaclasses
- */
-
- PyCStructType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCStructType_Type) < 0)
- return NULL;
-
- UnionType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&UnionType_Type) < 0)
- return NULL;
-
- PyCPointerType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCPointerType_Type) < 0)
- return NULL;
-
- PyCArrayType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCArrayType_Type) < 0)
- return NULL;
-
- PyCSimpleType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCSimpleType_Type) < 0)
- return NULL;
-
- PyCFuncPtrType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCFuncPtrType_Type) < 0)
- return NULL;
-
- /*************************************************
- *
- * Classes using a custom metaclass
- */
-
- if (PyType_Ready(&PyCData_Type) < 0)
- return NULL;
-
- Py_TYPE(&Struct_Type) = &PyCStructType_Type;
- Struct_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&Struct_Type) < 0)
- return NULL;
- PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
-
- Py_TYPE(&Union_Type) = &UnionType_Type;
- Union_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&Union_Type) < 0)
- return NULL;
- PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
-
- Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type;
- PyCPointer_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&PyCPointer_Type) < 0)
- return NULL;
- PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type);
-
- Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type;
- PyCArray_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&PyCArray_Type) < 0)
- return NULL;
- PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type);
-
- Py_TYPE(&Simple_Type) = &PyCSimpleType_Type;
- Simple_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&Simple_Type) < 0)
- return NULL;
- PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
-
- Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type;
- PyCFuncPtr_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&PyCFuncPtr_Type) < 0)
- return NULL;
- PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type);
-
- /*************************************************
- *
- * Simple classes
- */
-
- /* PyCField_Type is derived from PyBaseObject_Type */
- if (PyType_Ready(&PyCField_Type) < 0)
- return NULL;
-
- /*************************************************
- *
- * Other stuff
- */
-
- DictRemover_Type.tp_new = PyType_GenericNew;
- if (PyType_Ready(&DictRemover_Type) < 0)
- return NULL;
+ m = PyModule_Create(&_ctypesmodule);
+ if (!m)
+ return NULL;
+
+ _ctypes_ptrtype_cache = PyDict_New();
+ if (_ctypes_ptrtype_cache == NULL)
+ return NULL;
+
+ PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache);
+
+ _unpickle = PyObject_GetAttrString(m, "_unpickle");
+ if (_unpickle == NULL)
+ return NULL;
+
+ if (PyType_Ready(&PyCArg_Type) < 0)
+ return NULL;
+
+ if (PyType_Ready(&PyCThunk_Type) < 0)
+ return NULL;
+
+ /* StgDict is derived from PyDict_Type */
+ PyCStgDict_Type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&PyCStgDict_Type) < 0)
+ return NULL;
+
+ /*************************************************
+ *
+ * Metaclasses
+ */
+
+ PyCStructType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCStructType_Type) < 0)
+ return NULL;
+
+ UnionType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&UnionType_Type) < 0)
+ return NULL;
+
+ PyCPointerType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCPointerType_Type) < 0)
+ return NULL;
+
+ PyCArrayType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCArrayType_Type) < 0)
+ return NULL;
+
+ PyCSimpleType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCSimpleType_Type) < 0)
+ return NULL;
+
+ PyCFuncPtrType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCFuncPtrType_Type) < 0)
+ return NULL;
+
+ /*************************************************
+ *
+ * Classes using a custom metaclass
+ */
+
+ if (PyType_Ready(&PyCData_Type) < 0)
+ return NULL;
+
+ Py_TYPE(&Struct_Type) = &PyCStructType_Type;
+ Struct_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&Struct_Type) < 0)
+ return NULL;
+ PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
+
+ Py_TYPE(&Union_Type) = &UnionType_Type;
+ Union_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&Union_Type) < 0)
+ return NULL;
+ PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
+
+ Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type;
+ PyCPointer_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&PyCPointer_Type) < 0)
+ return NULL;
+ PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type);
+
+ Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type;
+ PyCArray_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&PyCArray_Type) < 0)
+ return NULL;
+ PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type);
+
+ Py_TYPE(&Simple_Type) = &PyCSimpleType_Type;
+ Simple_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&Simple_Type) < 0)
+ return NULL;
+ PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
+
+ Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type;
+ PyCFuncPtr_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&PyCFuncPtr_Type) < 0)
+ return NULL;
+ PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type);
+
+ /*************************************************
+ *
+ * Simple classes
+ */
+
+ /* PyCField_Type is derived from PyBaseObject_Type */
+ if (PyType_Ready(&PyCField_Type) < 0)
+ return NULL;
+
+ /*************************************************
+ *
+ * Other stuff
+ */
+
+ DictRemover_Type.tp_new = PyType_GenericNew;
+ if (PyType_Ready(&DictRemover_Type) < 0)
+ return NULL;
#ifdef MS_WIN32
- if (create_comerror() < 0)
- return NULL;
- PyModule_AddObject(m, "COMError", ComError);
+ if (create_comerror() < 0)
+ return NULL;
+ PyModule_AddObject(m, "COMError", ComError);
- PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT));
- PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL));
+ PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT));
+ PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL));
#endif
- PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL));
- PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO));
- PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR));
- PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI));
- PyModule_AddStringConstant(m, "__version__", "1.1.0");
-
- PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
- PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
- PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
- PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
+ PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL));
+ PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO));
+ PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR));
+ PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI));
+ PyModule_AddStringConstant(m, "__version__", "1.1.0");
+
+ PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
+ PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
+ PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
+ PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
#ifdef CTYPES_UNICODE
- PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
+ PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
#endif
/* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
@@ -5410,15 +5410,15 @@ PyInit__ctypes(void)
#define RTLD_GLOBAL RTLD_LOCAL
#endif
- PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL));
- PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL));
-
- PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
- if (PyExc_ArgError) {
- Py_INCREF(PyExc_ArgError);
- PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
- }
- return m;
+ PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL));
+ PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL));
+
+ PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
+ if (PyExc_ArgError) {
+ Py_INCREF(PyExc_ArgError);
+ PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
+ }
+ return m;
}
/*
diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c
index 2d957de..36bd0a1 100644
--- a/Modules/_ctypes/_ctypes_test.c
+++ b/Modules/_ctypes/_ctypes_test.c
@@ -14,152 +14,152 @@
EXPORT(void)testfunc_array(int values[4])
{
- printf("testfunc_array %d %d %d %d\n",
- values[0],
- values[1],
- values[2],
- values[3]);
+ printf("testfunc_array %d %d %d %d\n",
+ values[0],
+ values[1],
+ values[2],
+ values[3]);
}
EXPORT(long double)testfunc_Ddd(double a, double b)
{
- long double result = (long double)(a * b);
- printf("testfunc_Ddd(%p, %p)\n", &a, &b);
- printf("testfunc_Ddd(%g, %g)\n", a, b);
- return result;
+ long double result = (long double)(a * b);
+ printf("testfunc_Ddd(%p, %p)\n", &a, &b);
+ printf("testfunc_Ddd(%g, %g)\n", a, b);
+ return result;
}
EXPORT(long double)testfunc_DDD(long double a, long double b)
{
- long double result = a * b;
- printf("testfunc_DDD(%p, %p)\n", &a, &b);
- printf("testfunc_DDD(%Lg, %Lg)\n", a, b);
- return result;
+ long double result = a * b;
+ printf("testfunc_DDD(%p, %p)\n", &a, &b);
+ printf("testfunc_DDD(%Lg, %Lg)\n", a, b);
+ return result;
}
EXPORT(int)testfunc_iii(int a, int b)
{
- int result = a * b;
- printf("testfunc_iii(%p, %p)\n", &a, &b);
- return result;
+ int result = a * b;
+ printf("testfunc_iii(%p, %p)\n", &a, &b);
+ return result;
}
EXPORT(int)myprintf(char *fmt, ...)
{
- int result;
- va_list argptr;
- va_start(argptr, fmt);
- result = vprintf(fmt, argptr);
- va_end(argptr);
- return result;
+ int result;
+ va_list argptr;
+ va_start(argptr, fmt);
+ result = vprintf(fmt, argptr);
+ va_end(argptr);
+ return result;
}
EXPORT(char *)my_strtok(char *token, const char *delim)
{
- return strtok(token, delim);
+ return strtok(token, delim);
}
EXPORT(char *)my_strchr(const char *s, int c)
{
- return strchr(s, c);
+ return strchr(s, c);
}
EXPORT(double) my_sqrt(double a)
{
- return sqrt(a);
+ return sqrt(a);
}
EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*))
{
- qsort(base, num, width, compare);
+ qsort(base, num, width, compare);
}
EXPORT(int *) _testfunc_ai8(int a[8])
{
- return a;
+ return a;
}
EXPORT(void) _testfunc_v(int a, int b, int *presult)
{
- *presult = a + b;
+ *presult = a + b;
}
EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
-/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
- b, h, i, l, f, d);
+/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
*/
- return (int)(b + h + i + l + f + d);
+ return (int)(b + h + i + l + f + d);
}
EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
-/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
- b, h, i, l, f, d);
+/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
*/
- return (float)(b + h + i + l + f + d);
+ return (float)(b + h + i + l + f + d);
}
EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
-/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
- b, h, i, l, f, d);
+/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
*/
- return (double)(b + h + i + l + f + d);
+ return (double)(b + h + i + l + f + d);
}
EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d)
{
-/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
- b, h, i, l, f, d);
+/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
*/
- return (long double)(b + h + i + l + f + d);
+ return (long double)(b + h + i + l + f + d);
}
EXPORT(char *) _testfunc_p_p(void *s)
{
- return (char *)s;
+ return (char *)s;
}
EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv)
{
- return argv[(*argcp)-1];
+ return argv[(*argcp)-1];
}
EXPORT(void *) get_strchr(void)
{
- return (void *)strchr;
+ return (void *)strchr;
}
EXPORT(char *) my_strdup(char *src)
{
- char *dst = (char *)malloc(strlen(src)+1);
- if (!dst)
- return NULL;
- strcpy(dst, src);
- return dst;
+ char *dst = (char *)malloc(strlen(src)+1);
+ if (!dst)
+ return NULL;
+ strcpy(dst, src);
+ return dst;
}
EXPORT(void)my_free(void *ptr)
{
- free(ptr);
+ free(ptr);
}
#ifdef HAVE_WCHAR_H
EXPORT(wchar_t *) my_wcsdup(wchar_t *src)
{
- size_t len = wcslen(src);
- wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
- if (ptr == NULL)
- return NULL;
- memcpy(ptr, src, (len+1) * sizeof(wchar_t));
- return ptr;
+ size_t len = wcslen(src);
+ wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
+ if (ptr == NULL)
+ return NULL;
+ memcpy(ptr, src, (len+1) * sizeof(wchar_t));
+ return ptr;
}
EXPORT(size_t) my_wcslen(wchar_t *src)
{
- return wcslen(src);
+ return wcslen(src);
}
#endif
@@ -170,158 +170,158 @@ EXPORT(size_t) my_wcslen(wchar_t *src)
#endif
typedef struct {
- int (*c)(int, int);
- int (__stdcall *s)(int, int);
+ int (*c)(int, int);
+ int (__stdcall *s)(int, int);
} FUNCS;
EXPORT(int) _testfunc_callfuncp(FUNCS *fp)
{
- fp->c(1, 2);
- fp->s(3, 4);
- return 0;
+ fp->c(1, 2);
+ fp->s(3, 4);
+ return 0;
}
EXPORT(int) _testfunc_deref_pointer(int *pi)
{
- return *pi;
+ return *pi;
}
#ifdef MS_WIN32
EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk)
{
- piunk->lpVtbl->AddRef(piunk);
- return piunk->lpVtbl->Release(piunk);
+ piunk->lpVtbl->AddRef(piunk);
+ return piunk->lpVtbl->Release(piunk);
}
#endif
EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *))
{
- int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+ int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- return (*func)(table);
+ return (*func)(table);
}
#ifdef HAVE_LONG_LONG
EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f,
- double d, PY_LONG_LONG q)
+ double d, PY_LONG_LONG q)
{
- return (PY_LONG_LONG)(b + h + i + l + f + d + q);
+ return (PY_LONG_LONG)(b + h + i + l + f + d + q);
}
EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
- return (PY_LONG_LONG)(b + h + i + l + f + d);
+ return (PY_LONG_LONG)(b + h + i + l + f + d);
}
EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int))
{
- int sum = 0;
- while (value != 0) {
- sum += func(value);
- value /= 2;
- }
- return sum;
+ int sum = 0;
+ while (value != 0) {
+ sum += func(value);
+ value /= 2;
+ }
+ return sum;
}
EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value,
- PY_LONG_LONG (*func)(PY_LONG_LONG))
+ PY_LONG_LONG (*func)(PY_LONG_LONG))
{
- PY_LONG_LONG sum = 0;
+ PY_LONG_LONG sum = 0;
- while (value != 0) {
- sum += func(value);
- value /= 2;
- }
- return sum;
+ while (value != 0) {
+ sum += func(value);
+ value /= 2;
+ }
+ return sum;
}
#endif
typedef struct {
- char *name;
- char *value;
+ char *name;
+ char *value;
} SPAM;
typedef struct {
- char *name;
- int num_spams;
- SPAM *spams;
+ char *name;
+ int num_spams;
+ SPAM *spams;
} EGG;
SPAM my_spams[2] = {
- { "name1", "value1" },
- { "name2", "value2" },
+ { "name1", "value1" },
+ { "name2", "value2" },
};
EGG my_eggs[1] = {
- { "first egg", 1, my_spams }
+ { "first egg", 1, my_spams }
};
EXPORT(int) getSPAMANDEGGS(EGG **eggs)
{
- *eggs = my_eggs;
- return 1;
+ *eggs = my_eggs;
+ return 1;
}
typedef struct tagpoint {
- int x;
- int y;
+ int x;
+ int y;
} point;
EXPORT(int) _testfunc_byval(point in, point *pout)
{
- if (pout) {
- pout->x = in.x;
- pout->y = in.y;
- }
- return in.x + in.y;
+ if (pout) {
+ pout->x = in.x;
+ pout->y = in.y;
+ }
+ return in.x + in.y;
}
EXPORT (int) an_integer = 42;
EXPORT(int) get_an_integer(void)
{
- return an_integer;
+ return an_integer;
}
EXPORT(double)
integrate(double a, double b, double (*f)(double), long nstep)
{
- double x, sum=0.0, dx=(b-a)/(double)nstep;
- for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx)
- sum += f(x);
- return sum/(double)nstep;
+ double x, sum=0.0, dx=(b-a)/(double)nstep;
+ for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx)
+ sum += f(x);
+ return sum/(double)nstep;
}
typedef struct {
- void (*initialize)(void *(*)(int), void(*)(void *));
+ void (*initialize)(void *(*)(int), void(*)(void *));
} xxx_library;
static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *))
{
- void *ptr;
-
- printf("_xxx_init got %p %p\n", Xalloc, Xfree);
- printf("calling\n");
- ptr = Xalloc(32);
- Xfree(ptr);
- printf("calls done, ptr was %p\n", ptr);
+ void *ptr;
+
+ printf("_xxx_init got %p %p\n", Xalloc, Xfree);
+ printf("calling\n");
+ ptr = Xalloc(32);
+ Xfree(ptr);
+ printf("calls done, ptr was %p\n", ptr);
}
xxx_library _xxx_lib = {
- _xxx_init
+ _xxx_init
};
EXPORT(xxx_library) *library_get(void)
{
- return &_xxx_lib;
+ return &_xxx_lib;
}
#ifdef MS_WIN32
/* See Don Box (german), pp 79ff. */
EXPORT(void) GetString(BSTR *pbstr)
{
- *pbstr = SysAllocString(L"Goodbye!");
+ *pbstr = SysAllocString(L"Goodbye!");
}
#endif
@@ -330,12 +330,12 @@ EXPORT(void) GetString(BSTR *pbstr)
*/
PyObject *py_func_si(PyObject *self, PyObject *args)
{
- char *name;
- int i;
- if (!PyArg_ParseTuple(args, "si", &name, &i))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ char *name;
+ int i;
+ if (!PyArg_ParseTuple(args, "si", &name, &i))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
EXPORT(void) _py_func_si(char *s, int i)
@@ -344,8 +344,8 @@ EXPORT(void) _py_func_si(char *s, int i)
PyObject *py_func(PyObject *self, PyObject *args)
{
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
EXPORT(void) _py_func(void)
@@ -356,64 +356,64 @@ EXPORT(PY_LONG_LONG) last_tf_arg_s;
EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u;
struct BITS {
- int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9;
- short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7;
+ int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9;
+ short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7;
};
EXPORT(void) set_bitfields(struct BITS *bits, char name, int value)
{
- switch (name) {
- case 'A': bits->A = value; break;
- case 'B': bits->B = value; break;
- case 'C': bits->C = value; break;
- case 'D': bits->D = value; break;
- case 'E': bits->E = value; break;
- case 'F': bits->F = value; break;
- case 'G': bits->G = value; break;
- case 'H': bits->H = value; break;
- case 'I': bits->I = value; break;
-
- case 'M': bits->M = value; break;
- case 'N': bits->N = value; break;
- case 'O': bits->O = value; break;
- case 'P': bits->P = value; break;
- case 'Q': bits->Q = value; break;
- case 'R': bits->R = value; break;
- case 'S': bits->S = value; break;
- }
+ switch (name) {
+ case 'A': bits->A = value; break;
+ case 'B': bits->B = value; break;
+ case 'C': bits->C = value; break;
+ case 'D': bits->D = value; break;
+ case 'E': bits->E = value; break;
+ case 'F': bits->F = value; break;
+ case 'G': bits->G = value; break;
+ case 'H': bits->H = value; break;
+ case 'I': bits->I = value; break;
+
+ case 'M': bits->M = value; break;
+ case 'N': bits->N = value; break;
+ case 'O': bits->O = value; break;
+ case 'P': bits->P = value; break;
+ case 'Q': bits->Q = value; break;
+ case 'R': bits->R = value; break;
+ case 'S': bits->S = value; break;
+ }
}
EXPORT(int) unpack_bitfields(struct BITS *bits, char name)
{
- switch (name) {
- case 'A': return bits->A;
- case 'B': return bits->B;
- case 'C': return bits->C;
- case 'D': return bits->D;
- case 'E': return bits->E;
- case 'F': return bits->F;
- case 'G': return bits->G;
- case 'H': return bits->H;
- case 'I': return bits->I;
-
- case 'M': return bits->M;
- case 'N': return bits->N;
- case 'O': return bits->O;
- case 'P': return bits->P;
- case 'Q': return bits->Q;
- case 'R': return bits->R;
- case 'S': return bits->S;
- }
- return 0;
+ switch (name) {
+ case 'A': return bits->A;
+ case 'B': return bits->B;
+ case 'C': return bits->C;
+ case 'D': return bits->D;
+ case 'E': return bits->E;
+ case 'F': return bits->F;
+ case 'G': return bits->G;
+ case 'H': return bits->H;
+ case 'I': return bits->I;
+
+ case 'M': return bits->M;
+ case 'N': return bits->N;
+ case 'O': return bits->O;
+ case 'P': return bits->P;
+ case 'Q': return bits->Q;
+ case 'R': return bits->R;
+ case 'S': return bits->S;
+ }
+ return 0;
}
static PyMethodDef module_methods[] = {
-/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
- {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
+/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
+ {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
*/
- {"func_si", py_func_si, METH_VARARGS},
- {"func", py_func, METH_NOARGS},
- { NULL, NULL, 0, NULL},
+ {"func_si", py_func_si, METH_VARARGS},
+ {"func", py_func, METH_NOARGS},
+ { NULL, NULL, 0, NULL},
};
#define S last_tf_arg_s = (PY_LONG_LONG)c
@@ -483,80 +483,80 @@ EXPORT(void) __stdcall s_tv_i(int c) { S; return; }
#endif
/********/
-
+
#ifndef MS_WIN32
typedef struct {
- long x;
- long y;
+ long x;
+ long y;
} POINT;
typedef struct {
- long left;
- long top;
- long right;
- long bottom;
+ long left;
+ long top;
+ long right;
+ long bottom;
} RECT;
#endif
EXPORT(int) PointInRect(RECT *prc, POINT pt)
{
- if (pt.x < prc->left)
- return 0;
- if (pt.x > prc->right)
- return 0;
- if (pt.y < prc->top)
- return 0;
- if (pt.y > prc->bottom)
- return 0;
- return 1;
+ if (pt.x < prc->left)
+ return 0;
+ if (pt.x > prc->right)
+ return 0;
+ if (pt.y < prc->top)
+ return 0;
+ if (pt.y > prc->bottom)
+ return 0;
+ return 1;
}
typedef struct {
- short x;
- short y;
+ short x;
+ short y;
} S2H;
EXPORT(S2H) ret_2h_func(S2H inp)
{
- inp.x *= 2;
- inp.y *= 3;
- return inp;
+ inp.x *= 2;
+ inp.y *= 3;
+ return inp;
}
typedef struct {
- int a, b, c, d, e, f, g, h;
+ int a, b, c, d, e, f, g, h;
} S8I;
EXPORT(S8I) ret_8i_func(S8I inp)
{
- inp.a *= 2;
- inp.b *= 3;
- inp.c *= 4;
- inp.d *= 5;
- inp.e *= 6;
- inp.f *= 7;
- inp.g *= 8;
- inp.h *= 9;
- return inp;
+ inp.a *= 2;
+ inp.b *= 3;
+ inp.c *= 4;
+ inp.d *= 5;
+ inp.e *= 6;
+ inp.f *= 7;
+ inp.g *= 8;
+ inp.h *= 9;
+ return inp;
}
EXPORT(int) GetRectangle(int flag, RECT *prect)
{
- if (flag == 0)
- return 0;
- prect->left = (int)flag;
- prect->top = (int)flag + 1;
- prect->right = (int)flag + 2;
- prect->bottom = (int)flag + 3;
- return 1;
+ if (flag == 0)
+ return 0;
+ prect->left = (int)flag;
+ prect->top = (int)flag + 1;
+ prect->right = (int)flag + 2;
+ prect->bottom = (int)flag + 3;
+ return 1;
}
EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj)
{
- *pi += a;
- *pj += b;
+ *pi += a;
+ *pj += b;
}
#ifdef MS_WIN32
@@ -571,32 +571,32 @@ EXPORT(S8I) __stdcall s_ret_8i_func(S8I inp) { return ret_8i_func(inp); }
EXPORT (HRESULT) KeepObject(IUnknown *punk)
{
- static IUnknown *pobj;
- if (punk)
- punk->lpVtbl->AddRef(punk);
- if (pobj)
- pobj->lpVtbl->Release(pobj);
- pobj = punk;
- return S_OK;
+ static IUnknown *pobj;
+ if (punk)
+ punk->lpVtbl->AddRef(punk);
+ if (pobj)
+ pobj->lpVtbl->Release(pobj);
+ pobj = punk;
+ return S_OK;
}
#endif
static struct PyModuleDef _ctypes_testmodule = {
- PyModuleDef_HEAD_INIT,
- "_ctypes_test",
- NULL,
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_ctypes_test",
+ NULL,
+ -1,
+ module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__ctypes_test(void)
{
- return PyModule_Create(&_ctypes_testmodule);
+ return PyModule_Create(&_ctypes_testmodule);
}
diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c
index 5cf0441..4c9c013 100644
--- a/Modules/_ctypes/callbacks.c
+++ b/Modules/_ctypes/callbacks.c
@@ -12,65 +12,65 @@
static void
CThunkObject_dealloc(PyObject *_self)
{
- CThunkObject *self = (CThunkObject *)_self;
- Py_XDECREF(self->converters);
- Py_XDECREF(self->callable);
- Py_XDECREF(self->restype);
- if (self->pcl)
- _ctypes_free_closure(self->pcl);
- PyObject_GC_Del(self);
+ CThunkObject *self = (CThunkObject *)_self;
+ Py_XDECREF(self->converters);
+ Py_XDECREF(self->callable);
+ Py_XDECREF(self->restype);
+ if (self->pcl)
+ _ctypes_free_closure(self->pcl);
+ PyObject_GC_Del(self);
}
static int
CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg)
{
- CThunkObject *self = (CThunkObject *)_self;
- Py_VISIT(self->converters);
- Py_VISIT(self->callable);
- Py_VISIT(self->restype);
- return 0;
+ CThunkObject *self = (CThunkObject *)_self;
+ Py_VISIT(self->converters);
+ Py_VISIT(self->callable);
+ Py_VISIT(self->restype);
+ return 0;
}
static int
CThunkObject_clear(PyObject *_self)
{
- CThunkObject *self = (CThunkObject *)_self;
- Py_CLEAR(self->converters);
- Py_CLEAR(self->callable);
- Py_CLEAR(self->restype);
- return 0;
+ CThunkObject *self = (CThunkObject *)_self;
+ Py_CLEAR(self->converters);
+ Py_CLEAR(self->callable);
+ Py_CLEAR(self->restype);
+ return 0;
}
PyTypeObject PyCThunk_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CThunkObject",
- sizeof(CThunkObject), /* tp_basicsize */
- sizeof(ffi_type), /* tp_itemsize */
- CThunkObject_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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_HAVE_GC, /* tp_flags */
- "CThunkObject", /* tp_doc */
- CThunkObject_traverse, /* tp_traverse */
- CThunkObject_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CThunkObject",
+ sizeof(CThunkObject), /* tp_basicsize */
+ sizeof(ffi_type), /* tp_itemsize */
+ CThunkObject_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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_HAVE_GC, /* tp_flags */
+ "CThunkObject", /* tp_doc */
+ CThunkObject_traverse, /* tp_traverse */
+ CThunkObject_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
};
/**************************************************************/
@@ -78,43 +78,43 @@ PyTypeObject PyCThunk_Type = {
static void
PrintError(char *msg, ...)
{
- char buf[512];
- PyObject *f = PySys_GetObject("stderr");
- va_list marker;
-
- va_start(marker, msg);
- vsnprintf(buf, sizeof(buf), msg, marker);
- va_end(marker);
- if (f != NULL && f != Py_None)
- PyFile_WriteString(buf, f);
- PyErr_Print();
+ char buf[512];
+ PyObject *f = PySys_GetObject("stderr");
+ va_list marker;
+
+ va_start(marker, msg);
+ vsnprintf(buf, sizeof(buf), msg, marker);
+ va_end(marker);
+ if (f != NULL && f != Py_None)
+ PyFile_WriteString(buf, f);
+ PyErr_Print();
}
/* after code that pyrex generates */
void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
{
- PyObject *py_globals = 0;
- PyCodeObject *py_code = 0;
- PyFrameObject *py_frame = 0;
-
- py_globals = PyDict_New();
- if (!py_globals) goto bad;
- py_code = PyCode_NewEmpty(filename, funcname, lineno);
- if (!py_code) goto bad;
- py_frame = PyFrame_New(
- PyThreadState_Get(), /*PyThreadState *tstate,*/
- py_code, /*PyCodeObject *code,*/
- py_globals, /*PyObject *globals,*/
- 0 /*PyObject *locals*/
- );
- if (!py_frame) goto bad;
- py_frame->f_lineno = lineno;
- PyTraceBack_Here(py_frame);
+ PyObject *py_globals = 0;
+ PyCodeObject *py_code = 0;
+ PyFrameObject *py_frame = 0;
+
+ py_globals = PyDict_New();
+ if (!py_globals) goto bad;
+ py_code = PyCode_NewEmpty(filename, funcname, lineno);
+ if (!py_code) goto bad;
+ py_frame = PyFrame_New(
+ PyThreadState_Get(), /*PyThreadState *tstate,*/
+ py_code, /*PyCodeObject *code,*/
+ py_globals, /*PyObject *globals,*/
+ 0 /*PyObject *locals*/
+ );
+ if (!py_frame) goto bad;
+ py_frame->f_lineno = lineno;
+ PyTraceBack_Here(py_frame);
bad:
- Py_XDECREF(py_globals);
- Py_XDECREF(py_code);
- Py_XDECREF(py_frame);
+ Py_XDECREF(py_globals);
+ Py_XDECREF(py_code);
+ Py_XDECREF(py_frame);
}
#ifdef MS_WIN32
@@ -131,15 +131,15 @@ void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
static void
TryAddRef(StgDictObject *dict, CDataObject *obj)
{
- IUnknown *punk;
+ IUnknown *punk;
- if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
- return;
+ if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
+ return;
- punk = *(IUnknown **)obj->b_ptr;
- if (punk)
- punk->lpVtbl->AddRef(punk);
- return;
+ punk = *(IUnknown **)obj->b_ptr;
+ if (punk)
+ punk->lpVtbl->AddRef(punk);
+ return;
}
#endif
@@ -149,421 +149,421 @@ TryAddRef(StgDictObject *dict, CDataObject *obj)
*
*/
static void _CallPythonObject(void *mem,
- ffi_type *restype,
- SETFUNC setfunc,
- PyObject *callable,
- PyObject *converters,
- int flags,
- void **pArgs)
+ ffi_type *restype,
+ SETFUNC setfunc,
+ PyObject *callable,
+ PyObject *converters,
+ int flags,
+ void **pArgs)
{
- Py_ssize_t i;
- PyObject *result;
- PyObject *arglist = NULL;
- Py_ssize_t nArgs;
- PyObject *error_object = NULL;
- int *space;
+ Py_ssize_t i;
+ PyObject *result;
+ PyObject *arglist = NULL;
+ Py_ssize_t nArgs;
+ PyObject *error_object = NULL;
+ int *space;
#ifdef WITH_THREAD
- PyGILState_STATE state = PyGILState_Ensure();
+ PyGILState_STATE state = PyGILState_Ensure();
#endif
- nArgs = PySequence_Length(converters);
- /* Hm. What to return in case of error?
- For COM, 0xFFFFFFFF seems better than 0.
- */
- if (nArgs < 0) {
- PrintError("BUG: PySequence_Length");
- goto Done;
- }
-
- arglist = PyTuple_New(nArgs);
- if (!arglist) {
- PrintError("PyTuple_New()");
- goto Done;
- }
- for (i = 0; i < nArgs; ++i) {
- /* Note: new reference! */
- PyObject *cnv = PySequence_GetItem(converters, i);
- StgDictObject *dict;
- if (cnv)
- dict = PyType_stgdict(cnv);
- else {
- PrintError("Getting argument converter %d\n", i);
- goto Done;
- }
-
- if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
- PyObject *v = dict->getfunc(*pArgs, dict->size);
- if (!v) {
- PrintError("create argument %d:\n", i);
- Py_DECREF(cnv);
- goto Done;
- }
- PyTuple_SET_ITEM(arglist, i, v);
- /* XXX XXX XX
- We have the problem that c_byte or c_short have dict->size of
- 1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
- BTW, the same problem occurrs when they are pushed as parameters
- */
- } else if (dict) {
- /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
- CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
- if (!obj) {
- PrintError("create argument %d:\n", i);
- Py_DECREF(cnv);
- goto Done;
- }
- if (!CDataObject_Check(obj)) {
- Py_DECREF(obj);
- Py_DECREF(cnv);
- PrintError("unexpected result of create argument %d:\n", i);
- goto Done;
- }
- memcpy(obj->b_ptr, *pArgs, dict->size);
- PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
+ nArgs = PySequence_Length(converters);
+ /* Hm. What to return in case of error?
+ For COM, 0xFFFFFFFF seems better than 0.
+ */
+ if (nArgs < 0) {
+ PrintError("BUG: PySequence_Length");
+ goto Done;
+ }
+
+ arglist = PyTuple_New(nArgs);
+ if (!arglist) {
+ PrintError("PyTuple_New()");
+ goto Done;
+ }
+ for (i = 0; i < nArgs; ++i) {
+ /* Note: new reference! */
+ PyObject *cnv = PySequence_GetItem(converters, i);
+ StgDictObject *dict;
+ if (cnv)
+ dict = PyType_stgdict(cnv);
+ else {
+ PrintError("Getting argument converter %d\n", i);
+ goto Done;
+ }
+
+ if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
+ PyObject *v = dict->getfunc(*pArgs, dict->size);
+ if (!v) {
+ PrintError("create argument %d:\n", i);
+ Py_DECREF(cnv);
+ goto Done;
+ }
+ PyTuple_SET_ITEM(arglist, i, v);
+ /* XXX XXX XX
+ We have the problem that c_byte or c_short have dict->size of
+ 1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
+ BTW, the same problem occurrs when they are pushed as parameters
+ */
+ } else if (dict) {
+ /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
+ CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
+ if (!obj) {
+ PrintError("create argument %d:\n", i);
+ Py_DECREF(cnv);
+ goto Done;
+ }
+ if (!CDataObject_Check(obj)) {
+ Py_DECREF(obj);
+ Py_DECREF(cnv);
+ PrintError("unexpected result of create argument %d:\n", i);
+ goto Done;
+ }
+ memcpy(obj->b_ptr, *pArgs, dict->size);
+ PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
#ifdef MS_WIN32
- TryAddRef(dict, obj);
+ TryAddRef(dict, obj);
#endif
- } else {
- PyErr_SetString(PyExc_TypeError,
- "cannot build parameter");
- PrintError("Parsing argument %d\n", i);
- Py_DECREF(cnv);
- goto Done;
- }
- Py_DECREF(cnv);
- /* XXX error handling! */
- pArgs++;
- }
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot build parameter");
+ PrintError("Parsing argument %d\n", i);
+ Py_DECREF(cnv);
+ goto Done;
+ }
+ Py_DECREF(cnv);
+ /* XXX error handling! */
+ pArgs++;
+ }
#define CHECK(what, x) \
if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print()
- if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
- error_object = _ctypes_get_errobj(&space);
- if (error_object == NULL)
- goto Done;
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
+ if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
+ error_object = _ctypes_get_errobj(&space);
+ if (error_object == NULL)
+ goto Done;
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
#ifdef MS_WIN32
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#endif
- }
+ }
- result = PyObject_CallObject(callable, arglist);
- CHECK("'calling callback function'", result);
+ result = PyObject_CallObject(callable, arglist);
+ CHECK("'calling callback function'", result);
#ifdef MS_WIN32
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#endif
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
- Py_XDECREF(error_object);
-
- if ((restype != &ffi_type_void) && result) {
- PyObject *keep;
- assert(setfunc);
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
+ Py_XDECREF(error_object);
+
+ if ((restype != &ffi_type_void) && result) {
+ PyObject *keep;
+ assert(setfunc);
#ifdef WORDS_BIGENDIAN
- /* See the corresponding code in callproc.c, around line 961 */
- if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
- mem = (char *)mem + sizeof(ffi_arg) - restype->size;
+ /* See the corresponding code in callproc.c, around line 961 */
+ if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
+ mem = (char *)mem + sizeof(ffi_arg) - restype->size;
#endif
- keep = setfunc(mem, result, 0);
- CHECK("'converting callback result'", keep);
- /* keep is an object we have to keep alive so that the result
- stays valid. If there is no such object, the setfunc will
- have returned Py_None.
-
- If there is such an object, we have no choice than to keep
- it alive forever - but a refcount and/or memory leak will
- be the result. EXCEPT when restype is py_object - Python
- itself knows how to manage the refcount of these objects.
- */
- if (keep == NULL) /* Could not convert callback result. */
- PyErr_WriteUnraisable(callable);
- else if (keep == Py_None) /* Nothing to keep */
- Py_DECREF(keep);
- else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
- if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning,
- "memory leak in callback function.",
- 1))
- PyErr_WriteUnraisable(callable);
- }
- }
- Py_XDECREF(result);
+ keep = setfunc(mem, result, 0);
+ CHECK("'converting callback result'", keep);
+ /* keep is an object we have to keep alive so that the result
+ stays valid. If there is no such object, the setfunc will
+ have returned Py_None.
+
+ If there is such an object, we have no choice than to keep
+ it alive forever - but a refcount and/or memory leak will
+ be the result. EXCEPT when restype is py_object - Python
+ itself knows how to manage the refcount of these objects.
+ */
+ if (keep == NULL) /* Could not convert callback result. */
+ PyErr_WriteUnraisable(callable);
+ else if (keep == Py_None) /* Nothing to keep */
+ Py_DECREF(keep);
+ else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
+ if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning,
+ "memory leak in callback function.",
+ 1))
+ PyErr_WriteUnraisable(callable);
+ }
+ }
+ Py_XDECREF(result);
Done:
- Py_XDECREF(arglist);
+ Py_XDECREF(arglist);
#ifdef WITH_THREAD
- PyGILState_Release(state);
+ PyGILState_Release(state);
#endif
}
static void closure_fcn(ffi_cif *cif,
- void *resp,
- void **args,
- void *userdata)
+ void *resp,
+ void **args,
+ void *userdata)
{
- CThunkObject *p = (CThunkObject *)userdata;
-
- _CallPythonObject(resp,
- p->ffi_restype,
- p->setfunc,
- p->callable,
- p->converters,
- p->flags,
- args);
+ CThunkObject *p = (CThunkObject *)userdata;
+
+ _CallPythonObject(resp,
+ p->ffi_restype,
+ p->setfunc,
+ p->callable,
+ p->converters,
+ p->flags,
+ args);
}
static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
{
- CThunkObject *p;
- int i;
-
- p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
- if (p == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
-
- p->pcl = NULL;
- memset(&p->cif, 0, sizeof(p->cif));
- p->converters = NULL;
- p->callable = NULL;
- p->setfunc = NULL;
- p->ffi_restype = NULL;
-
- for (i = 0; i < nArgs + 1; ++i)
- p->atypes[i] = NULL;
- PyObject_GC_Track((PyObject *)p);
- return p;
+ CThunkObject *p;
+ int i;
+
+ p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
+ if (p == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ p->pcl = NULL;
+ memset(&p->cif, 0, sizeof(p->cif));
+ p->converters = NULL;
+ p->callable = NULL;
+ p->setfunc = NULL;
+ p->ffi_restype = NULL;
+
+ for (i = 0; i < nArgs + 1; ++i)
+ p->atypes[i] = NULL;
+ PyObject_GC_Track((PyObject *)p);
+ return p;
}
CThunkObject *_ctypes_alloc_callback(PyObject *callable,
- PyObject *converters,
- PyObject *restype,
- int flags)
+ PyObject *converters,
+ PyObject *restype,
+ int flags)
{
- int result;
- CThunkObject *p;
- Py_ssize_t nArgs, i;
- ffi_abi cc;
-
- nArgs = PySequence_Size(converters);
- p = CThunkObject_new(nArgs);
- if (p == NULL)
- return NULL;
-
- assert(CThunk_CheckExact((PyObject *)p));
-
- p->pcl = _ctypes_alloc_closure();
- if (p->pcl == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- p->flags = flags;
- for (i = 0; i < nArgs; ++i) {
- PyObject *cnv = PySequence_GetItem(converters, i);
- if (cnv == NULL)
- goto error;
- p->atypes[i] = _ctypes_get_ffi_type(cnv);
- Py_DECREF(cnv);
- }
- p->atypes[i] = NULL;
-
- Py_INCREF(restype);
- p->restype = restype;
- if (restype == Py_None) {
- p->setfunc = NULL;
- p->ffi_restype = &ffi_type_void;
- } else {
- StgDictObject *dict = PyType_stgdict(restype);
- if (dict == NULL || dict->setfunc == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "invalid result type for callback function");
- goto error;
- }
- p->setfunc = dict->setfunc;
- p->ffi_restype = &dict->ffi_type_pointer;
- }
-
- cc = FFI_DEFAULT_ABI;
+ int result;
+ CThunkObject *p;
+ Py_ssize_t nArgs, i;
+ ffi_abi cc;
+
+ nArgs = PySequence_Size(converters);
+ p = CThunkObject_new(nArgs);
+ if (p == NULL)
+ return NULL;
+
+ assert(CThunk_CheckExact((PyObject *)p));
+
+ p->pcl = _ctypes_alloc_closure();
+ if (p->pcl == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ p->flags = flags;
+ for (i = 0; i < nArgs; ++i) {
+ PyObject *cnv = PySequence_GetItem(converters, i);
+ if (cnv == NULL)
+ goto error;
+ p->atypes[i] = _ctypes_get_ffi_type(cnv);
+ Py_DECREF(cnv);
+ }
+ p->atypes[i] = NULL;
+
+ Py_INCREF(restype);
+ p->restype = restype;
+ if (restype == Py_None) {
+ p->setfunc = NULL;
+ p->ffi_restype = &ffi_type_void;
+ } else {
+ StgDictObject *dict = PyType_stgdict(restype);
+ if (dict == NULL || dict->setfunc == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid result type for callback function");
+ goto error;
+ }
+ p->setfunc = dict->setfunc;
+ p->ffi_restype = &dict->ffi_type_pointer;
+ }
+
+ cc = FFI_DEFAULT_ABI;
#if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64)
- if ((flags & FUNCFLAG_CDECL) == 0)
- cc = FFI_STDCALL;
+ if ((flags & FUNCFLAG_CDECL) == 0)
+ cc = FFI_STDCALL;
#endif
- result = ffi_prep_cif(&p->cif, cc,
- Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
- _ctypes_get_ffi_type(restype),
- &p->atypes[0]);
- if (result != FFI_OK) {
- PyErr_Format(PyExc_RuntimeError,
- "ffi_prep_cif failed with %d", result);
- goto error;
- }
- result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
- if (result != FFI_OK) {
- PyErr_Format(PyExc_RuntimeError,
- "ffi_prep_closure failed with %d", result);
- goto error;
- }
-
- Py_INCREF(converters);
- p->converters = converters;
- Py_INCREF(callable);
- p->callable = callable;
- return p;
+ result = ffi_prep_cif(&p->cif, cc,
+ Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
+ _ctypes_get_ffi_type(restype),
+ &p->atypes[0]);
+ if (result != FFI_OK) {
+ PyErr_Format(PyExc_RuntimeError,
+ "ffi_prep_cif failed with %d", result);
+ goto error;
+ }
+ result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
+ if (result != FFI_OK) {
+ PyErr_Format(PyExc_RuntimeError,
+ "ffi_prep_closure failed with %d", result);
+ goto error;
+ }
+
+ Py_INCREF(converters);
+ p->converters = converters;
+ Py_INCREF(callable);
+ p->callable = callable;
+ return p;
error:
- Py_XDECREF(p);
- return NULL;
+ Py_XDECREF(p);
+ return NULL;
}
#ifdef MS_WIN32
static void LoadPython(void)
{
- if (!Py_IsInitialized()) {
+ if (!Py_IsInitialized()) {
#ifdef WITH_THREAD
- PyEval_InitThreads();
+ PyEval_InitThreads();
#endif
- Py_Initialize();
- }
+ Py_Initialize();
+ }
}
/******************************************************************/
long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
- PyObject *mod, *func, *result;
- long retval;
- static PyObject *context;
-
- if (context == NULL)
- context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");
-
- mod = PyImport_ImportModuleNoBlock("ctypes");
- if (!mod) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- /* There has been a warning before about this already */
- return E_FAIL;
- }
-
- func = PyObject_GetAttrString(mod, "DllGetClassObject");
- Py_DECREF(mod);
- if (!func) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- {
- PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
- PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
- PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
- if (!py_rclsid || !py_riid || !py_ppv) {
- Py_XDECREF(py_rclsid);
- Py_XDECREF(py_riid);
- Py_XDECREF(py_ppv);
- Py_DECREF(func);
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
- result = PyObject_CallFunctionObjArgs(func,
- py_rclsid,
- py_riid,
- py_ppv,
- NULL);
- Py_DECREF(py_rclsid);
- Py_DECREF(py_riid);
- Py_DECREF(py_ppv);
- }
- Py_DECREF(func);
- if (!result) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- retval = PyLong_AsLong(result);
- if (PyErr_Occurred()) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- retval = E_FAIL;
- }
- Py_DECREF(result);
- return retval;
+ PyObject *mod, *func, *result;
+ long retval;
+ static PyObject *context;
+
+ if (context == NULL)
+ context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");
+
+ mod = PyImport_ImportModuleNoBlock("ctypes");
+ if (!mod) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ /* There has been a warning before about this already */
+ return E_FAIL;
+ }
+
+ func = PyObject_GetAttrString(mod, "DllGetClassObject");
+ Py_DECREF(mod);
+ if (!func) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ {
+ PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
+ PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
+ PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
+ if (!py_rclsid || !py_riid || !py_ppv) {
+ Py_XDECREF(py_rclsid);
+ Py_XDECREF(py_riid);
+ Py_XDECREF(py_ppv);
+ Py_DECREF(func);
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+ result = PyObject_CallFunctionObjArgs(func,
+ py_rclsid,
+ py_riid,
+ py_ppv,
+ NULL);
+ Py_DECREF(py_rclsid);
+ Py_DECREF(py_riid);
+ Py_DECREF(py_ppv);
+ }
+ Py_DECREF(func);
+ if (!result) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ retval = PyLong_AsLong(result);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ retval = E_FAIL;
+ }
+ Py_DECREF(result);
+ return retval;
}
STDAPI DllGetClassObject(REFCLSID rclsid,
- REFIID riid,
- LPVOID *ppv)
+ REFIID riid,
+ LPVOID *ppv)
{
- long result;
+ long result;
#ifdef WITH_THREAD
- PyGILState_STATE state;
+ PyGILState_STATE state;
#endif
- LoadPython();
+ LoadPython();
#ifdef WITH_THREAD
- state = PyGILState_Ensure();
+ state = PyGILState_Ensure();
#endif
- result = Call_GetClassObject(rclsid, riid, ppv);
+ result = Call_GetClassObject(rclsid, riid, ppv);
#ifdef WITH_THREAD
- PyGILState_Release(state);
+ PyGILState_Release(state);
#endif
- return result;
+ return result;
}
long Call_CanUnloadNow(void)
{
- PyObject *mod, *func, *result;
- long retval;
- static PyObject *context;
-
- if (context == NULL)
- context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");
-
- mod = PyImport_ImportModuleNoBlock("ctypes");
- if (!mod) {
-/* OutputDebugString("Could not import ctypes"); */
- /* We assume that this error can only occur when shutting
- down, so we silently ignore it */
- PyErr_Clear();
- return E_FAIL;
- }
- /* Other errors cannot be raised, but are printed to stderr */
- func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
- Py_DECREF(mod);
- if (!func) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- result = PyObject_CallFunction(func, NULL);
- Py_DECREF(func);
- if (!result) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- retval = PyLong_AsLong(result);
- if (PyErr_Occurred()) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- retval = E_FAIL;
- }
- Py_DECREF(result);
- return retval;
+ PyObject *mod, *func, *result;
+ long retval;
+ static PyObject *context;
+
+ if (context == NULL)
+ context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");
+
+ mod = PyImport_ImportModuleNoBlock("ctypes");
+ if (!mod) {
+/* OutputDebugString("Could not import ctypes"); */
+ /* We assume that this error can only occur when shutting
+ down, so we silently ignore it */
+ PyErr_Clear();
+ return E_FAIL;
+ }
+ /* Other errors cannot be raised, but are printed to stderr */
+ func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
+ Py_DECREF(mod);
+ if (!func) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ result = PyObject_CallFunction(func, NULL);
+ Py_DECREF(func);
+ if (!result) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ retval = PyLong_AsLong(result);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ retval = E_FAIL;
+ }
+ Py_DECREF(result);
+ return retval;
}
/*
@@ -572,26 +572,26 @@ long Call_CanUnloadNow(void)
STDAPI DllCanUnloadNow(void)
{
- long result;
+ long result;
#ifdef WITH_THREAD
- PyGILState_STATE state = PyGILState_Ensure();
+ PyGILState_STATE state = PyGILState_Ensure();
#endif
- result = Call_CanUnloadNow();
+ result = Call_CanUnloadNow();
#ifdef WITH_THREAD
- PyGILState_Release(state);
+ PyGILState_Release(state);
#endif
- return result;
+ return result;
}
#ifndef Py_NO_ENABLE_SHARED
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes)
{
- switch(fdwReason) {
- case DLL_PROCESS_ATTACH:
- DisableThreadLibraryCalls(hinstDLL);
- break;
- }
- return TRUE;
+ switch(fdwReason) {
+ case DLL_PROCESS_ATTACH:
+ DisableThreadLibraryCalls(hinstDLL);
+ break;
+ }
+ return TRUE;
}
#endif
diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c
index 57ff1e8..6e0e224 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -4,9 +4,9 @@
*/
/*
* Related Work:
- * - calldll http://www.nightmare.com/software.html
- * - libffi http://sourceware.cygnus.com/libffi/
- * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
+ * - calldll http://www.nightmare.com/software.html
+ * - libffi http://sourceware.cygnus.com/libffi/
+ * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
* and, of course, Don Beaudry's MESS package, but this is more ctypes
* related.
*/
@@ -82,17 +82,17 @@
static void pymem_destructor(PyObject *ptr)
{
- void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
- if (p) {
- PyMem_Free(p);
- }
+ void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
+ if (p) {
+ PyMem_Free(p);
+ }
}
/*
ctypes maintains thread-local storage that has space for two error numbers:
private copies of the system 'errno' value and, on Windows, the system error code
accessed by the GetLastError() and SetLastError() api functions.
-
+
Foreign functions created with CDLL(..., use_errno=True), when called, swap
the system 'errno' value with the private copy just before the actual
function call, and swapped again immediately afterwards. The 'use_errno'
@@ -125,88 +125,88 @@ static void pymem_destructor(PyObject *ptr)
PyObject *
_ctypes_get_errobj(int **pspace)
{
- PyObject *dict = PyThreadState_GetDict();
- PyObject *errobj;
- static PyObject *error_object_name;
- if (dict == 0) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot get thread state");
- return NULL;
- }
- if (error_object_name == NULL) {
- error_object_name = PyUnicode_InternFromString("ctypes.error_object");
- if (error_object_name == NULL)
- return NULL;
- }
- errobj = PyDict_GetItem(dict, error_object_name);
- if (errobj) {
- if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
- PyErr_SetString(PyExc_RuntimeError,
- "ctypes.error_object is an invalid capsule");
- return NULL;
- }
- Py_INCREF(errobj);
- }
- else {
- void *space = PyMem_Malloc(sizeof(int) * 2);
- if (space == NULL)
- return NULL;
- memset(space, 0, sizeof(int) * 2);
- errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
- if (errobj == NULL)
- return NULL;
- if (-1 == PyDict_SetItem(dict, error_object_name,
- errobj)) {
- Py_DECREF(errobj);
- return NULL;
- }
- }
- *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
- return errobj;
+ PyObject *dict = PyThreadState_GetDict();
+ PyObject *errobj;
+ static PyObject *error_object_name;
+ if (dict == 0) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot get thread state");
+ return NULL;
+ }
+ if (error_object_name == NULL) {
+ error_object_name = PyUnicode_InternFromString("ctypes.error_object");
+ if (error_object_name == NULL)
+ return NULL;
+ }
+ errobj = PyDict_GetItem(dict, error_object_name);
+ if (errobj) {
+ if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "ctypes.error_object is an invalid capsule");
+ return NULL;
+ }
+ Py_INCREF(errobj);
+ }
+ else {
+ void *space = PyMem_Malloc(sizeof(int) * 2);
+ if (space == NULL)
+ return NULL;
+ memset(space, 0, sizeof(int) * 2);
+ errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
+ if (errobj == NULL)
+ return NULL;
+ if (-1 == PyDict_SetItem(dict, error_object_name,
+ errobj)) {
+ Py_DECREF(errobj);
+ return NULL;
+ }
+ }
+ *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
+ return errobj;
}
static PyObject *
get_error_internal(PyObject *self, PyObject *args, int index)
{
- int *space;
- PyObject *errobj = _ctypes_get_errobj(&space);
- PyObject *result;
-
- if (errobj == NULL)
- return NULL;
- result = PyLong_FromLong(space[index]);
- Py_DECREF(errobj);
- return result;
+ int *space;
+ PyObject *errobj = _ctypes_get_errobj(&space);
+ PyObject *result;
+
+ if (errobj == NULL)
+ return NULL;
+ result = PyLong_FromLong(space[index]);
+ Py_DECREF(errobj);
+ return result;
}
static PyObject *
set_error_internal(PyObject *self, PyObject *args, int index)
{
- int new_errno, old_errno;
- PyObject *errobj;
- int *space;
-
- if (!PyArg_ParseTuple(args, "i", &new_errno))
- return NULL;
- errobj = _ctypes_get_errobj(&space);
- if (errobj == NULL)
- return NULL;
- old_errno = space[index];
- space[index] = new_errno;
- Py_DECREF(errobj);
- return PyLong_FromLong(old_errno);
+ int new_errno, old_errno;
+ PyObject *errobj;
+ int *space;
+
+ if (!PyArg_ParseTuple(args, "i", &new_errno))
+ return NULL;
+ errobj = _ctypes_get_errobj(&space);
+ if (errobj == NULL)
+ return NULL;
+ old_errno = space[index];
+ space[index] = new_errno;
+ Py_DECREF(errobj);
+ return PyLong_FromLong(old_errno);
}
static PyObject *
get_errno(PyObject *self, PyObject *args)
{
- return get_error_internal(self, args, 0);
+ return get_error_internal(self, args, 0);
}
static PyObject *
set_errno(PyObject *self, PyObject *args)
{
- return set_error_internal(self, args, 0);
+ return set_error_internal(self, args, 0);
}
#ifdef MS_WIN32
@@ -214,202 +214,202 @@ set_errno(PyObject *self, PyObject *args)
static PyObject *
get_last_error(PyObject *self, PyObject *args)
{
- return get_error_internal(self, args, 1);
+ return get_error_internal(self, args, 1);
}
static PyObject *
set_last_error(PyObject *self, PyObject *args)
{
- return set_error_internal(self, args, 1);
+ return set_error_internal(self, args, 1);
}
PyObject *ComError;
static WCHAR *FormatError(DWORD code)
{
- WCHAR *lpMsgBuf;
- DWORD n;
- n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- code,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
- (LPWSTR) &lpMsgBuf,
- 0,
- NULL);
- if (n) {
- while (iswspace(lpMsgBuf[n-1]))
- --n;
- lpMsgBuf[n] = L'\0'; /* rstrip() */
- }
- return lpMsgBuf;
+ WCHAR *lpMsgBuf;
+ DWORD n;
+ n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL,
+ code,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
+ (LPWSTR) &lpMsgBuf,
+ 0,
+ NULL);
+ if (n) {
+ while (iswspace(lpMsgBuf[n-1]))
+ --n;
+ lpMsgBuf[n] = L'\0'; /* rstrip() */
+ }
+ return lpMsgBuf;
}
#ifndef DONT_USE_SEH
static void SetException(DWORD code, EXCEPTION_RECORD *pr)
{
- /* The 'code' is a normal win32 error code so it could be handled by
- PyErr_SetFromWindowsErr(). However, for some errors, we have additional
- information not included in the error code. We handle those here and
- delegate all others to the generic function. */
- switch (code) {
- case EXCEPTION_ACCESS_VIOLATION:
- /* The thread attempted to read from or write
- to a virtual address for which it does not
- have the appropriate access. */
- if (pr->ExceptionInformation[0] == 0)
- PyErr_Format(PyExc_WindowsError,
- "exception: access violation reading %p",
- pr->ExceptionInformation[1]);
- else
- PyErr_Format(PyExc_WindowsError,
- "exception: access violation writing %p",
- pr->ExceptionInformation[1]);
- break;
-
- case EXCEPTION_BREAKPOINT:
- /* A breakpoint was encountered. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: breakpoint encountered");
- break;
-
- case EXCEPTION_DATATYPE_MISALIGNMENT:
- /* The thread attempted to read or write data that is
- misaligned on hardware that does not provide
- alignment. For example, 16-bit values must be
- aligned on 2-byte boundaries, 32-bit values on
- 4-byte boundaries, and so on. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: datatype misalignment");
- break;
-
- case EXCEPTION_SINGLE_STEP:
- /* A trace trap or other single-instruction mechanism
- signaled that one instruction has been executed. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: single step");
- break;
-
- case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
- /* The thread attempted to access an array element
- that is out of bounds, and the underlying hardware
- supports bounds checking. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: array bounds exceeded");
- break;
-
- case EXCEPTION_FLT_DENORMAL_OPERAND:
- /* One of the operands in a floating-point operation
- is denormal. A denormal value is one that is too
- small to represent as a standard floating-point
- value. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: floating-point operand denormal");
- break;
-
- case EXCEPTION_FLT_DIVIDE_BY_ZERO:
- /* The thread attempted to divide a floating-point
- value by a floating-point divisor of zero. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float divide by zero");
- break;
-
- case EXCEPTION_FLT_INEXACT_RESULT:
- /* The result of a floating-point operation cannot be
- represented exactly as a decimal fraction. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float inexact");
- break;
-
- case EXCEPTION_FLT_INVALID_OPERATION:
- /* This exception represents any floating-point
- exception not included in this list. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float invalid operation");
- break;
-
- case EXCEPTION_FLT_OVERFLOW:
- /* The exponent of a floating-point operation is
- greater than the magnitude allowed by the
- corresponding type. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float overflow");
- break;
-
- case EXCEPTION_FLT_STACK_CHECK:
- /* The stack overflowed or underflowed as the result
- of a floating-point operation. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: stack over/underflow");
- break;
-
- case EXCEPTION_STACK_OVERFLOW:
- /* The stack overflowed or underflowed as the result
- of a floating-point operation. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: stack overflow");
- break;
-
- case EXCEPTION_FLT_UNDERFLOW:
- /* The exponent of a floating-point operation is less
- than the magnitude allowed by the corresponding
- type. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float underflow");
- break;
-
- case EXCEPTION_INT_DIVIDE_BY_ZERO:
- /* The thread attempted to divide an integer value by
- an integer divisor of zero. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: integer divide by zero");
- break;
-
- case EXCEPTION_INT_OVERFLOW:
- /* The result of an integer operation caused a carry
- out of the most significant bit of the result. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: integer overflow");
- break;
-
- case EXCEPTION_PRIV_INSTRUCTION:
- /* The thread attempted to execute an instruction
- whose operation is not allowed in the current
- machine mode. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: priviledged instruction");
- break;
-
- case EXCEPTION_NONCONTINUABLE_EXCEPTION:
- /* The thread attempted to continue execution after a
- noncontinuable exception occurred. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: nocontinuable");
- break;
-
- default:
- PyErr_SetFromWindowsErr(code);
- break;
- }
+ /* The 'code' is a normal win32 error code so it could be handled by
+ PyErr_SetFromWindowsErr(). However, for some errors, we have additional
+ information not included in the error code. We handle those here and
+ delegate all others to the generic function. */
+ switch (code) {
+ case EXCEPTION_ACCESS_VIOLATION:
+ /* The thread attempted to read from or write
+ to a virtual address for which it does not
+ have the appropriate access. */
+ if (pr->ExceptionInformation[0] == 0)
+ PyErr_Format(PyExc_WindowsError,
+ "exception: access violation reading %p",
+ pr->ExceptionInformation[1]);
+ else
+ PyErr_Format(PyExc_WindowsError,
+ "exception: access violation writing %p",
+ pr->ExceptionInformation[1]);
+ break;
+
+ case EXCEPTION_BREAKPOINT:
+ /* A breakpoint was encountered. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: breakpoint encountered");
+ break;
+
+ case EXCEPTION_DATATYPE_MISALIGNMENT:
+ /* The thread attempted to read or write data that is
+ misaligned on hardware that does not provide
+ alignment. For example, 16-bit values must be
+ aligned on 2-byte boundaries, 32-bit values on
+ 4-byte boundaries, and so on. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: datatype misalignment");
+ break;
+
+ case EXCEPTION_SINGLE_STEP:
+ /* A trace trap or other single-instruction mechanism
+ signaled that one instruction has been executed. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: single step");
+ break;
+
+ case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
+ /* The thread attempted to access an array element
+ that is out of bounds, and the underlying hardware
+ supports bounds checking. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: array bounds exceeded");
+ break;
+
+ case EXCEPTION_FLT_DENORMAL_OPERAND:
+ /* One of the operands in a floating-point operation
+ is denormal. A denormal value is one that is too
+ small to represent as a standard floating-point
+ value. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: floating-point operand denormal");
+ break;
+
+ case EXCEPTION_FLT_DIVIDE_BY_ZERO:
+ /* The thread attempted to divide a floating-point
+ value by a floating-point divisor of zero. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float divide by zero");
+ break;
+
+ case EXCEPTION_FLT_INEXACT_RESULT:
+ /* The result of a floating-point operation cannot be
+ represented exactly as a decimal fraction. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float inexact");
+ break;
+
+ case EXCEPTION_FLT_INVALID_OPERATION:
+ /* This exception represents any floating-point
+ exception not included in this list. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float invalid operation");
+ break;
+
+ case EXCEPTION_FLT_OVERFLOW:
+ /* The exponent of a floating-point operation is
+ greater than the magnitude allowed by the
+ corresponding type. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float overflow");
+ break;
+
+ case EXCEPTION_FLT_STACK_CHECK:
+ /* The stack overflowed or underflowed as the result
+ of a floating-point operation. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: stack over/underflow");
+ break;
+
+ case EXCEPTION_STACK_OVERFLOW:
+ /* The stack overflowed or underflowed as the result
+ of a floating-point operation. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: stack overflow");
+ break;
+
+ case EXCEPTION_FLT_UNDERFLOW:
+ /* The exponent of a floating-point operation is less
+ than the magnitude allowed by the corresponding
+ type. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float underflow");
+ break;
+
+ case EXCEPTION_INT_DIVIDE_BY_ZERO:
+ /* The thread attempted to divide an integer value by
+ an integer divisor of zero. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: integer divide by zero");
+ break;
+
+ case EXCEPTION_INT_OVERFLOW:
+ /* The result of an integer operation caused a carry
+ out of the most significant bit of the result. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: integer overflow");
+ break;
+
+ case EXCEPTION_PRIV_INSTRUCTION:
+ /* The thread attempted to execute an instruction
+ whose operation is not allowed in the current
+ machine mode. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: priviledged instruction");
+ break;
+
+ case EXCEPTION_NONCONTINUABLE_EXCEPTION:
+ /* The thread attempted to continue execution after a
+ noncontinuable exception occurred. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: nocontinuable");
+ break;
+
+ default:
+ PyErr_SetFromWindowsErr(code);
+ break;
+ }
}
static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
- DWORD *pdw, EXCEPTION_RECORD *record)
+ DWORD *pdw, EXCEPTION_RECORD *record)
{
- *pdw = ptrs->ExceptionRecord->ExceptionCode;
- *record = *ptrs->ExceptionRecord;
- return EXCEPTION_EXECUTE_HANDLER;
+ *pdw = ptrs->ExceptionRecord->ExceptionCode;
+ *record = *ptrs->ExceptionRecord;
+ return EXCEPTION_EXECUTE_HANDLER;
}
#endif
static PyObject *
check_hresult(PyObject *self, PyObject *args)
{
- HRESULT hr;
- if (!PyArg_ParseTuple(args, "i", &hr))
- return NULL;
- if (FAILED(hr))
- return PyErr_SetFromWindowsErr(hr);
- return PyLong_FromLong(hr);
+ HRESULT hr;
+ if (!PyArg_ParseTuple(args, "i", &hr))
+ return NULL;
+ if (FAILED(hr))
+ return PyErr_SetFromWindowsErr(hr);
+ return PyLong_FromLong(hr);
}
#endif
@@ -419,132 +419,132 @@ check_hresult(PyObject *self, PyObject *args)
PyCArgObject *
PyCArgObject_new(void)
{
- PyCArgObject *p;
- p = PyObject_New(PyCArgObject, &PyCArg_Type);
- if (p == NULL)
- return NULL;
- p->pffi_type = NULL;
- p->tag = '\0';
- p->obj = NULL;
- memset(&p->value, 0, sizeof(p->value));
- return p;
+ PyCArgObject *p;
+ p = PyObject_New(PyCArgObject, &PyCArg_Type);
+ if (p == NULL)
+ return NULL;
+ p->pffi_type = NULL;
+ p->tag = '\0';
+ p->obj = NULL;
+ memset(&p->value, 0, sizeof(p->value));
+ return p;
}
static void
PyCArg_dealloc(PyCArgObject *self)
{
- Py_XDECREF(self->obj);
- PyObject_Del(self);
+ Py_XDECREF(self->obj);
+ PyObject_Del(self);
}
static PyObject *
PyCArg_repr(PyCArgObject *self)
{
- char buffer[256];
- switch(self->tag) {
- case 'b':
- case 'B':
- sprintf(buffer, "<cparam '%c' (%d)>",
- self->tag, self->value.b);
- break;
- case 'h':
- case 'H':
- sprintf(buffer, "<cparam '%c' (%d)>",
- self->tag, self->value.h);
- break;
- case 'i':
- case 'I':
- sprintf(buffer, "<cparam '%c' (%d)>",
- self->tag, self->value.i);
- break;
- case 'l':
- case 'L':
- sprintf(buffer, "<cparam '%c' (%ld)>",
- self->tag, self->value.l);
- break;
-
+ char buffer[256];
+ switch(self->tag) {
+ case 'b':
+ case 'B':
+ sprintf(buffer, "<cparam '%c' (%d)>",
+ self->tag, self->value.b);
+ break;
+ case 'h':
+ case 'H':
+ sprintf(buffer, "<cparam '%c' (%d)>",
+ self->tag, self->value.h);
+ break;
+ case 'i':
+ case 'I':
+ sprintf(buffer, "<cparam '%c' (%d)>",
+ self->tag, self->value.i);
+ break;
+ case 'l':
+ case 'L':
+ sprintf(buffer, "<cparam '%c' (%ld)>",
+ self->tag, self->value.l);
+ break;
+
#ifdef HAVE_LONG_LONG
- case 'q':
- case 'Q':
- sprintf(buffer,
+ case 'q':
+ case 'Q':
+ sprintf(buffer,
#ifdef MS_WIN32
- "<cparam '%c' (%I64d)>",
+ "<cparam '%c' (%I64d)>",
#else
- "<cparam '%c' (%qd)>",
+ "<cparam '%c' (%qd)>",
#endif
- self->tag, self->value.q);
- break;
+ self->tag, self->value.q);
+ break;
#endif
- case 'd':
- sprintf(buffer, "<cparam '%c' (%f)>",
- self->tag, self->value.d);
- break;
- case 'f':
- sprintf(buffer, "<cparam '%c' (%f)>",
- self->tag, self->value.f);
- break;
-
- case 'c':
- sprintf(buffer, "<cparam '%c' (%c)>",
- self->tag, self->value.c);
- break;
+ case 'd':
+ sprintf(buffer, "<cparam '%c' (%f)>",
+ self->tag, self->value.d);
+ break;
+ case 'f':
+ sprintf(buffer, "<cparam '%c' (%f)>",
+ self->tag, self->value.f);
+ break;
+
+ case 'c':
+ sprintf(buffer, "<cparam '%c' (%c)>",
+ self->tag, self->value.c);
+ break;
/* Hm, are these 'z' and 'Z' codes useful at all?
Shouldn't they be replaced by the functionality of c_string
and c_wstring ?
*/
- case 'z':
- case 'Z':
- case 'P':
- sprintf(buffer, "<cparam '%c' (%p)>",
- self->tag, self->value.p);
- break;
-
- default:
- sprintf(buffer, "<cparam '%c' at %p>",
- self->tag, self);
- break;
- }
- return PyUnicode_FromString(buffer);
+ case 'z':
+ case 'Z':
+ case 'P':
+ sprintf(buffer, "<cparam '%c' (%p)>",
+ self->tag, self->value.p);
+ break;
+
+ default:
+ sprintf(buffer, "<cparam '%c' at %p>",
+ self->tag, self);
+ break;
+ }
+ return PyUnicode_FromString(buffer);
}
static PyMemberDef PyCArgType_members[] = {
- { "_obj", T_OBJECT,
- offsetof(PyCArgObject, obj), READONLY,
- "the wrapped object" },
- { NULL },
+ { "_obj", T_OBJECT,
+ offsetof(PyCArgObject, obj), READONLY,
+ "the wrapped object" },
+ { NULL },
};
PyTypeObject PyCArg_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "CArgObject",
- sizeof(PyCArgObject),
- 0,
- (destructor)PyCArg_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)PyCArg_repr, /* 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, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- PyCArgType_members, /* tp_members */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "CArgObject",
+ sizeof(PyCArgObject),
+ 0,
+ (destructor)PyCArg_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)PyCArg_repr, /* 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, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ PyCArgType_members, /* tp_members */
};
/****************************************************************/
@@ -577,24 +577,24 @@ PyTypeObject PyCArg_Type = {
*/
union result {
- char c;
- char b;
- short h;
- int i;
- long l;
+ char c;
+ char b;
+ short h;
+ int i;
+ long l;
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG q;
+ PY_LONG_LONG q;
#endif
- long double D;
- double d;
- float f;
- void *p;
+ long double D;
+ double d;
+ float f;
+ void *p;
};
struct argument {
- ffi_type *ffi_type;
- PyObject *keep;
- union result value;
+ ffi_type *ffi_type;
+ PyObject *keep;
+ union result value;
};
/*
@@ -602,134 +602,134 @@ struct argument {
*/
static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
{
- StgDictObject *dict;
- pa->keep = NULL; /* so we cannot forget it later */
-
- dict = PyObject_stgdict(obj);
- if (dict) {
- PyCArgObject *carg;
- assert(dict->paramfunc);
- /* If it has an stgdict, it is a CDataObject */
- carg = dict->paramfunc((CDataObject *)obj);
- pa->ffi_type = carg->pffi_type;
- memcpy(&pa->value, &carg->value, sizeof(pa->value));
- pa->keep = (PyObject *)carg;
- return 0;
- }
-
- if (PyCArg_CheckExact(obj)) {
- PyCArgObject *carg = (PyCArgObject *)obj;
- pa->ffi_type = carg->pffi_type;
- Py_INCREF(obj);
- pa->keep = obj;
- memcpy(&pa->value, &carg->value, sizeof(pa->value));
- return 0;
- }
-
- /* check for None, integer, string or unicode and use directly if successful */
- if (obj == Py_None) {
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = NULL;
- return 0;
- }
-
- if (PyLong_Check(obj)) {
- pa->ffi_type = &ffi_type_sint;
- pa->value.i = (long)PyLong_AsUnsignedLong(obj);
- if (pa->value.i == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- pa->value.i = PyLong_AsLong(obj);
- if (pa->value.i == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_OverflowError,
- "long int too long to convert");
- return -1;
- }
- }
- return 0;
- }
-
- if (PyBytes_Check(obj)) {
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = PyBytes_AsString(obj);
- Py_INCREF(obj);
- pa->keep = obj;
- return 0;
- }
+ StgDictObject *dict;
+ pa->keep = NULL; /* so we cannot forget it later */
+
+ dict = PyObject_stgdict(obj);
+ if (dict) {
+ PyCArgObject *carg;
+ assert(dict->paramfunc);
+ /* If it has an stgdict, it is a CDataObject */
+ carg = dict->paramfunc((CDataObject *)obj);
+ pa->ffi_type = carg->pffi_type;
+ memcpy(&pa->value, &carg->value, sizeof(pa->value));
+ pa->keep = (PyObject *)carg;
+ return 0;
+ }
+
+ if (PyCArg_CheckExact(obj)) {
+ PyCArgObject *carg = (PyCArgObject *)obj;
+ pa->ffi_type = carg->pffi_type;
+ Py_INCREF(obj);
+ pa->keep = obj;
+ memcpy(&pa->value, &carg->value, sizeof(pa->value));
+ return 0;
+ }
+
+ /* check for None, integer, string or unicode and use directly if successful */
+ if (obj == Py_None) {
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = NULL;
+ return 0;
+ }
+
+ if (PyLong_Check(obj)) {
+ pa->ffi_type = &ffi_type_sint;
+ pa->value.i = (long)PyLong_AsUnsignedLong(obj);
+ if (pa->value.i == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ pa->value.i = PyLong_AsLong(obj);
+ if (pa->value.i == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_OverflowError,
+ "long int too long to convert");
+ return -1;
+ }
+ }
+ return 0;
+ }
+
+ if (PyBytes_Check(obj)) {
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = PyBytes_AsString(obj);
+ Py_INCREF(obj);
+ pa->keep = obj;
+ return 0;
+ }
#ifdef CTYPES_UNICODE
- if (PyUnicode_Check(obj)) {
+ if (PyUnicode_Check(obj)) {
#ifdef HAVE_USABLE_WCHAR_T
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = PyUnicode_AS_UNICODE(obj);
- Py_INCREF(obj);
- pa->keep = obj;
- return 0;
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = PyUnicode_AS_UNICODE(obj);
+ Py_INCREF(obj);
+ pa->keep = obj;
+ return 0;
#else
- int size = PyUnicode_GET_SIZE(obj);
- pa->ffi_type = &ffi_type_pointer;
- size += 1; /* terminating NUL */
- size *= sizeof(wchar_t);
- pa->value.p = PyMem_Malloc(size);
- if (!pa->value.p) {
- PyErr_NoMemory();
- return -1;
- }
- memset(pa->value.p, 0, size);
- pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
- if (!pa->keep) {
- PyMem_Free(pa->value.p);
- return -1;
- }
- if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
- pa->value.p, PyUnicode_GET_SIZE(obj)))
- return -1;
- return 0;
+ int size = PyUnicode_GET_SIZE(obj);
+ pa->ffi_type = &ffi_type_pointer;
+ size += 1; /* terminating NUL */
+ size *= sizeof(wchar_t);
+ pa->value.p = PyMem_Malloc(size);
+ if (!pa->value.p) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memset(pa->value.p, 0, size);
+ pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
+ if (!pa->keep) {
+ PyMem_Free(pa->value.p);
+ return -1;
+ }
+ if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
+ pa->value.p, PyUnicode_GET_SIZE(obj)))
+ return -1;
+ return 0;
#endif
- }
+ }
#endif
- {
- PyObject *arg;
- arg = PyObject_GetAttrString(obj, "_as_parameter_");
- /* Which types should we exactly allow here?
- integers are required for using Python classes
- as parameters (they have to expose the '_as_parameter_'
- attribute)
- */
- if (arg) {
- int result;
- result = ConvParam(arg, index, pa);
- Py_DECREF(arg);
- return result;
- }
- PyErr_Format(PyExc_TypeError,
- "Don't know how to convert parameter %d",
- Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
- return -1;
- }
+ {
+ PyObject *arg;
+ arg = PyObject_GetAttrString(obj, "_as_parameter_");
+ /* Which types should we exactly allow here?
+ integers are required for using Python classes
+ as parameters (they have to expose the '_as_parameter_'
+ attribute)
+ */
+ if (arg) {
+ int result;
+ result = ConvParam(arg, index, pa);
+ Py_DECREF(arg);
+ return result;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "Don't know how to convert parameter %d",
+ Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
+ return -1;
+ }
}
ffi_type *_ctypes_get_ffi_type(PyObject *obj)
{
- StgDictObject *dict;
- if (obj == NULL)
- return &ffi_type_sint;
- dict = PyType_stgdict(obj);
- if (dict == NULL)
- return &ffi_type_sint;
+ StgDictObject *dict;
+ if (obj == NULL)
+ return &ffi_type_sint;
+ dict = PyType_stgdict(obj);
+ if (dict == NULL)
+ return &ffi_type_sint;
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
- /* This little trick works correctly with MSVC.
- It returns small structures in registers
- */
- if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
- if (dict->ffi_type_pointer.size <= 4)
- return &ffi_type_sint32;
- else if (dict->ffi_type_pointer.size <= 8)
- return &ffi_type_sint64;
- }
+ /* This little trick works correctly with MSVC.
+ It returns small structures in registers
+ */
+ if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
+ if (dict->ffi_type_pointer.size <= 4)
+ return &ffi_type_sint32;
+ else if (dict->ffi_type_pointer.size <= 8)
+ return &ffi_type_sint64;
+ }
#endif
- return &dict->ffi_type_pointer;
+ return &dict->ffi_type_pointer;
}
@@ -737,7 +737,7 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj)
* libffi uses:
*
* ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
- * unsigned int nargs,
+ * unsigned int nargs,
* ffi_type *rtype,
* ffi_type **atypes);
*
@@ -746,108 +746,108 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj)
* void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
*/
static int _call_function_pointer(int flags,
- PPROC pProc,
- void **avalues,
- ffi_type **atypes,
- ffi_type *restype,
- void *resmem,
- int argcount)
+ PPROC pProc,
+ void **avalues,
+ ffi_type **atypes,
+ ffi_type *restype,
+ void *resmem,
+ int argcount)
{
#ifdef WITH_THREAD
- PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
+ PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
#endif
- PyObject *error_object = NULL;
- int *space;
- ffi_cif cif;
- int cc;
+ PyObject *error_object = NULL;
+ int *space;
+ ffi_cif cif;
+ int cc;
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
- DWORD dwExceptionCode = 0;
- EXCEPTION_RECORD record;
+ DWORD dwExceptionCode = 0;
+ EXCEPTION_RECORD record;
#endif
#endif
- /* XXX check before here */
- if (restype == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "No ffi_type for result");
- return -1;
- }
-
- cc = FFI_DEFAULT_ABI;
+ /* XXX check before here */
+ if (restype == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "No ffi_type for result");
+ return -1;
+ }
+
+ cc = FFI_DEFAULT_ABI;
#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
- if ((flags & FUNCFLAG_CDECL) == 0)
- cc = FFI_STDCALL;
+ if ((flags & FUNCFLAG_CDECL) == 0)
+ cc = FFI_STDCALL;
#endif
- if (FFI_OK != ffi_prep_cif(&cif,
- cc,
- argcount,
- restype,
- atypes)) {
- PyErr_SetString(PyExc_RuntimeError,
- "ffi_prep_cif failed");
- return -1;
- }
-
- if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
- error_object = _ctypes_get_errobj(&space);
- if (error_object == NULL)
- return -1;
- }
+ if (FFI_OK != ffi_prep_cif(&cif,
+ cc,
+ argcount,
+ restype,
+ atypes)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "ffi_prep_cif failed");
+ return -1;
+ }
+
+ if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
+ error_object = _ctypes_get_errobj(&space);
+ if (error_object == NULL)
+ return -1;
+ }
#ifdef WITH_THREAD
- if ((flags & FUNCFLAG_PYTHONAPI) == 0)
- Py_UNBLOCK_THREADS
+ if ((flags & FUNCFLAG_PYTHONAPI) == 0)
+ Py_UNBLOCK_THREADS
#endif
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
#ifdef MS_WIN32
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#ifndef DONT_USE_SEH
- __try {
+ __try {
#endif
#endif
- ffi_call(&cif, (void *)pProc, resmem, avalues);
+ ffi_call(&cif, (void *)pProc, resmem, avalues);
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
- }
- __except (HandleException(GetExceptionInformation(),
- &dwExceptionCode, &record)) {
- ;
- }
+ }
+ __except (HandleException(GetExceptionInformation(),
+ &dwExceptionCode, &record)) {
+ ;
+ }
#endif
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#endif
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
- Py_XDECREF(error_object);
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
+ Py_XDECREF(error_object);
#ifdef WITH_THREAD
- if ((flags & FUNCFLAG_PYTHONAPI) == 0)
- Py_BLOCK_THREADS
+ if ((flags & FUNCFLAG_PYTHONAPI) == 0)
+ Py_BLOCK_THREADS
#endif
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
- if (dwExceptionCode) {
- SetException(dwExceptionCode, &record);
- return -1;
- }
+ if (dwExceptionCode) {
+ SetException(dwExceptionCode, &record);
+ return -1;
+ }
#endif
#endif
- if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
- return -1;
- return 0;
+ if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
+ return -1;
+ return 0;
}
/*
@@ -862,41 +862,41 @@ static int _call_function_pointer(int flags,
*/
static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
{
- StgDictObject *dict;
- PyObject *retval, *v;
-
- if (restype == NULL)
- return PyLong_FromLong(*(int *)result);
-
- if (restype == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- dict = PyType_stgdict(restype);
- if (dict == NULL)
- return PyObject_CallFunction(restype, "i", *(int *)result);
-
- if (dict->getfunc && !_ctypes_simple_instance(restype)) {
- retval = dict->getfunc(result, dict->size);
- /* If restype is py_object (detected by comparing getfunc with
- O_get), we have to call Py_DECREF because O_get has already
- called Py_INCREF.
- */
- if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
- Py_DECREF(retval);
- }
- } else
- retval = PyCData_FromBaseObj(restype, NULL, 0, result);
-
- if (!checker || !retval)
- return retval;
-
- v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
- if (v == NULL)
- _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
- Py_DECREF(retval);
- return v;
+ StgDictObject *dict;
+ PyObject *retval, *v;
+
+ if (restype == NULL)
+ return PyLong_FromLong(*(int *)result);
+
+ if (restype == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ dict = PyType_stgdict(restype);
+ if (dict == NULL)
+ return PyObject_CallFunction(restype, "i", *(int *)result);
+
+ if (dict->getfunc && !_ctypes_simple_instance(restype)) {
+ retval = dict->getfunc(result, dict->size);
+ /* If restype is py_object (detected by comparing getfunc with
+ O_get), we have to call Py_DECREF because O_get has already
+ called Py_INCREF.
+ */
+ if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
+ Py_DECREF(retval);
+ }
+ } else
+ retval = PyCData_FromBaseObj(restype, NULL, 0, result);
+
+ if (!checker || !retval)
+ return retval;
+
+ v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
+ if (v == NULL)
+ _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
+ Py_DECREF(retval);
+ return v;
}
/*
@@ -905,40 +905,40 @@ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
*/
void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
{
- va_list vargs;
- PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
-
- va_start(vargs, fmt);
- s = PyUnicode_FromFormatV(fmt, vargs);
- va_end(vargs);
- if (!s)
- return;
-
- PyErr_Fetch(&tp, &v, &tb);
- PyErr_NormalizeException(&tp, &v, &tb);
- cls_str = PyObject_Str(tp);
- if (cls_str) {
- PyUnicode_AppendAndDel(&s, cls_str);
- PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
- if (s == NULL)
- goto error;
- } else
- PyErr_Clear();
- msg_str = PyObject_Str(v);
- if (msg_str)
- PyUnicode_AppendAndDel(&s, msg_str);
- else {
- PyErr_Clear();
- PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
- if (s == NULL)
- goto error;
- }
- PyErr_SetObject(exc_class, s);
+ va_list vargs;
+ PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
+
+ va_start(vargs, fmt);
+ s = PyUnicode_FromFormatV(fmt, vargs);
+ va_end(vargs);
+ if (!s)
+ return;
+
+ PyErr_Fetch(&tp, &v, &tb);
+ PyErr_NormalizeException(&tp, &v, &tb);
+ cls_str = PyObject_Str(tp);
+ if (cls_str) {
+ PyUnicode_AppendAndDel(&s, cls_str);
+ PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
+ if (s == NULL)
+ goto error;
+ } else
+ PyErr_Clear();
+ msg_str = PyObject_Str(v);
+ if (msg_str)
+ PyUnicode_AppendAndDel(&s, msg_str);
+ else {
+ PyErr_Clear();
+ PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
+ if (s == NULL)
+ goto error;
+ }
+ PyErr_SetObject(exc_class, s);
error:
- Py_XDECREF(tp);
- Py_XDECREF(v);
- Py_XDECREF(tb);
- Py_XDECREF(s);
+ Py_XDECREF(tp);
+ Py_XDECREF(v);
+ Py_XDECREF(tb);
+ Py_XDECREF(s);
}
@@ -947,73 +947,73 @@ error:
static PyObject *
GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
{
- HRESULT hr;
- ISupportErrorInfo *psei = NULL;
- IErrorInfo *pei = NULL;
- BSTR descr=NULL, helpfile=NULL, source=NULL;
- GUID guid;
- DWORD helpcontext=0;
- LPOLESTR progid;
- PyObject *obj;
- LPOLESTR text;
-
- /* We absolutely have to release the GIL during COM method calls,
- otherwise we may get a deadlock!
- */
+ HRESULT hr;
+ ISupportErrorInfo *psei = NULL;
+ IErrorInfo *pei = NULL;
+ BSTR descr=NULL, helpfile=NULL, source=NULL;
+ GUID guid;
+ DWORD helpcontext=0;
+ LPOLESTR progid;
+ PyObject *obj;
+ LPOLESTR text;
+
+ /* We absolutely have to release the GIL during COM method calls,
+ otherwise we may get a deadlock!
+ */
#ifdef WITH_THREAD
- Py_BEGIN_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
#endif
- hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
- if (FAILED(hr))
- goto failed;
+ hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
+ if (FAILED(hr))
+ goto failed;
- hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
- psei->lpVtbl->Release(psei);
- if (FAILED(hr))
- goto failed;
+ hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
+ psei->lpVtbl->Release(psei);
+ if (FAILED(hr))
+ goto failed;
- hr = GetErrorInfo(0, &pei);
- if (hr != S_OK)
- goto failed;
+ hr = GetErrorInfo(0, &pei);
+ if (hr != S_OK)
+ goto failed;
- pei->lpVtbl->GetDescription(pei, &descr);
- pei->lpVtbl->GetGUID(pei, &guid);
- pei->lpVtbl->GetHelpContext(pei, &helpcontext);
- pei->lpVtbl->GetHelpFile(pei, &helpfile);
- pei->lpVtbl->GetSource(pei, &source);
+ pei->lpVtbl->GetDescription(pei, &descr);
+ pei->lpVtbl->GetGUID(pei, &guid);
+ pei->lpVtbl->GetHelpContext(pei, &helpcontext);
+ pei->lpVtbl->GetHelpFile(pei, &helpfile);
+ pei->lpVtbl->GetSource(pei, &source);
- pei->lpVtbl->Release(pei);
+ pei->lpVtbl->Release(pei);
failed:
#ifdef WITH_THREAD
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
#endif
- progid = NULL;
- ProgIDFromCLSID(&guid, &progid);
-
- text = FormatError(errcode);
- obj = Py_BuildValue(
- "iu(uuuiu)",
- errcode,
- text,
- descr, source, helpfile, helpcontext,
- progid);
- if (obj) {
- PyErr_SetObject(ComError, obj);
- Py_DECREF(obj);
- }
- LocalFree(text);
-
- if (descr)
- SysFreeString(descr);
- if (helpfile)
- SysFreeString(helpfile);
- if (source)
- SysFreeString(source);
-
- return NULL;
+ progid = NULL;
+ ProgIDFromCLSID(&guid, &progid);
+
+ text = FormatError(errcode);
+ obj = Py_BuildValue(
+ "iu(uuuiu)",
+ errcode,
+ text,
+ descr, source, helpfile, helpcontext,
+ progid);
+ if (obj) {
+ PyErr_SetObject(ComError, obj);
+ Py_DECREF(obj);
+ }
+ LocalFree(text);
+
+ if (descr)
+ SysFreeString(descr);
+ if (helpfile)
+ SysFreeString(helpfile);
+ if (source)
+ SysFreeString(source);
+
+ return NULL;
}
#endif
@@ -1025,154 +1025,154 @@ GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
* - XXX various requirements for restype, not yet collected
*/
PyObject *_ctypes_callproc(PPROC pProc,
- PyObject *argtuple,
+ PyObject *argtuple,
#ifdef MS_WIN32
- IUnknown *pIunk,
- GUID *iid,
+ IUnknown *pIunk,
+ GUID *iid,
#endif
- int flags,
- PyObject *argtypes, /* misleading name: This is a tuple of
- methods, not types: the .from_param
- class methods of the types */
- PyObject *restype,
- PyObject *checker)
+ int flags,
+ PyObject *argtypes, /* misleading name: This is a tuple of
+ methods, not types: the .from_param
+ class methods of the types */
+ PyObject *restype,
+ PyObject *checker)
{
- Py_ssize_t i, n, argcount, argtype_count;
- void *resbuf;
- struct argument *args, *pa;
- ffi_type **atypes;
- ffi_type *rtype;
- void **avalues;
- PyObject *retval = NULL;
-
- n = argcount = PyTuple_GET_SIZE(argtuple);
+ Py_ssize_t i, n, argcount, argtype_count;
+ void *resbuf;
+ struct argument *args, *pa;
+ ffi_type **atypes;
+ ffi_type *rtype;
+ void **avalues;
+ PyObject *retval = NULL;
+
+ n = argcount = PyTuple_GET_SIZE(argtuple);
#ifdef MS_WIN32
- /* an optional COM object this pointer */
- if (pIunk)
- ++argcount;
+ /* an optional COM object this pointer */
+ if (pIunk)
+ ++argcount;
#endif
- args = (struct argument *)alloca(sizeof(struct argument) * argcount);
- if (!args) {
- PyErr_NoMemory();
- return NULL;
- }
- memset(args, 0, sizeof(struct argument) * argcount);
- argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
+ args = (struct argument *)alloca(sizeof(struct argument) * argcount);
+ if (!args) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(args, 0, sizeof(struct argument) * argcount);
+ argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
#ifdef MS_WIN32
- if (pIunk) {
- args[0].ffi_type = &ffi_type_pointer;
- args[0].value.p = pIunk;
- pa = &args[1];
- } else
+ if (pIunk) {
+ args[0].ffi_type = &ffi_type_pointer;
+ args[0].value.p = pIunk;
+ pa = &args[1];
+ } else
#endif
- pa = &args[0];
-
- /* Convert the arguments */
- for (i = 0; i < n; ++i, ++pa) {
- PyObject *converter;
- PyObject *arg;
- int err;
-
- arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
- /* For cdecl functions, we allow more actual arguments
- than the length of the argtypes tuple.
- This is checked in _ctypes::PyCFuncPtr_Call
- */
- if (argtypes && argtype_count > i) {
- PyObject *v;
- converter = PyTuple_GET_ITEM(argtypes, i);
- v = PyObject_CallFunctionObjArgs(converter,
- arg,
- NULL);
- if (v == NULL) {
- _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup;
- }
-
- err = ConvParam(v, i+1, pa);
- Py_DECREF(v);
- if (-1 == err) {
- _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup;
- }
- } else {
- err = ConvParam(arg, i+1, pa);
- if (-1 == err) {
- _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup; /* leaking ? */
- }
- }
- }
-
- rtype = _ctypes_get_ffi_type(restype);
- resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
-
- avalues = (void **)alloca(sizeof(void *) * argcount);
- atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
- if (!resbuf || !avalues || !atypes) {
- PyErr_NoMemory();
- goto cleanup;
- }
- for (i = 0; i < argcount; ++i) {
- atypes[i] = args[i].ffi_type;
- if (atypes[i]->type == FFI_TYPE_STRUCT)
- avalues[i] = (void *)args[i].value.p;
- else
- avalues[i] = (void *)&args[i].value;
- }
-
- if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
- rtype, resbuf,
- Py_SAFE_DOWNCAST(argcount,
- Py_ssize_t,
- int)))
- goto cleanup;
+ pa = &args[0];
+
+ /* Convert the arguments */
+ for (i = 0; i < n; ++i, ++pa) {
+ PyObject *converter;
+ PyObject *arg;
+ int err;
+
+ arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
+ /* For cdecl functions, we allow more actual arguments
+ than the length of the argtypes tuple.
+ This is checked in _ctypes::PyCFuncPtr_Call
+ */
+ if (argtypes && argtype_count > i) {
+ PyObject *v;
+ converter = PyTuple_GET_ITEM(argtypes, i);
+ v = PyObject_CallFunctionObjArgs(converter,
+ arg,
+ NULL);
+ if (v == NULL) {
+ _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup;
+ }
+
+ err = ConvParam(v, i+1, pa);
+ Py_DECREF(v);
+ if (-1 == err) {
+ _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup;
+ }
+ } else {
+ err = ConvParam(arg, i+1, pa);
+ if (-1 == err) {
+ _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup; /* leaking ? */
+ }
+ }
+ }
+
+ rtype = _ctypes_get_ffi_type(restype);
+ resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
+
+ avalues = (void **)alloca(sizeof(void *) * argcount);
+ atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
+ if (!resbuf || !avalues || !atypes) {
+ PyErr_NoMemory();
+ goto cleanup;
+ }
+ for (i = 0; i < argcount; ++i) {
+ atypes[i] = args[i].ffi_type;
+ if (atypes[i]->type == FFI_TYPE_STRUCT)
+ avalues[i] = (void *)args[i].value.p;
+ else
+ avalues[i] = (void *)&args[i].value;
+ }
+
+ if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
+ rtype, resbuf,
+ Py_SAFE_DOWNCAST(argcount,
+ Py_ssize_t,
+ int)))
+ goto cleanup;
#ifdef WORDS_BIGENDIAN
- /* libffi returns the result in a buffer with sizeof(ffi_arg). This
- causes problems on big endian machines, since the result buffer
- address cannot simply be used as result pointer, instead we must
- adjust the pointer value:
- */
- /*
- XXX I should find out and clarify why this is needed at all,
- especially why adjusting for ffi_type_float must be avoided on
- 64-bit platforms.
- */
- if (rtype->type != FFI_TYPE_FLOAT
- && rtype->type != FFI_TYPE_STRUCT
- && rtype->size < sizeof(ffi_arg))
- resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
+ /* libffi returns the result in a buffer with sizeof(ffi_arg). This
+ causes problems on big endian machines, since the result buffer
+ address cannot simply be used as result pointer, instead we must
+ adjust the pointer value:
+ */
+ /*
+ XXX I should find out and clarify why this is needed at all,
+ especially why adjusting for ffi_type_float must be avoided on
+ 64-bit platforms.
+ */
+ if (rtype->type != FFI_TYPE_FLOAT
+ && rtype->type != FFI_TYPE_STRUCT
+ && rtype->size < sizeof(ffi_arg))
+ resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
#endif
#ifdef MS_WIN32
- if (iid && pIunk) {
- if (*(int *)resbuf & 0x80000000)
- retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
- else
- retval = PyLong_FromLong(*(int *)resbuf);
- } else if (flags & FUNCFLAG_HRESULT) {
- if (*(int *)resbuf & 0x80000000)
- retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
- else
- retval = PyLong_FromLong(*(int *)resbuf);
- } else
+ if (iid && pIunk) {
+ if (*(int *)resbuf & 0x80000000)
+ retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
+ else
+ retval = PyLong_FromLong(*(int *)resbuf);
+ } else if (flags & FUNCFLAG_HRESULT) {
+ if (*(int *)resbuf & 0x80000000)
+ retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
+ else
+ retval = PyLong_FromLong(*(int *)resbuf);
+ } else
#endif
- retval = GetResult(restype, resbuf, checker);
+ retval = GetResult(restype, resbuf, checker);
cleanup:
- for (i = 0; i < argcount; ++i)
- Py_XDECREF(args[i].keep);
- return retval;
+ for (i = 0; i < argcount; ++i)
+ Py_XDECREF(args[i].keep);
+ return retval;
}
static int
_parse_voidp(PyObject *obj, void **address)
{
- *address = PyLong_AsVoidPtr(obj);
- if (*address == NULL)
- return 0;
- return 1;
+ *address = PyLong_AsVoidPtr(obj);
+ if (*address == NULL)
+ return 0;
+ return 1;
}
#ifdef MS_WIN32
@@ -1184,21 +1184,21 @@ Convert a win32 error code into a string. If the error code is not\n\
given, the return value of a call to GetLastError() is used.\n";
static PyObject *format_error(PyObject *self, PyObject *args)
{
- PyObject *result;
- wchar_t *lpMsgBuf;
- DWORD code = 0;
- if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
- return NULL;
- if (code == 0)
- code = GetLastError();
- lpMsgBuf = FormatError(code);
- if (lpMsgBuf) {
- result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
- LocalFree(lpMsgBuf);
- } else {
- result = PyUnicode_FromString("<no description>");
- }
- return result;
+ PyObject *result;
+ wchar_t *lpMsgBuf;
+ DWORD code = 0;
+ if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
+ return NULL;
+ if (code == 0)
+ code = GetLastError();
+ lpMsgBuf = FormatError(code);
+ if (lpMsgBuf) {
+ result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
+ LocalFree(lpMsgBuf);
+ } else {
+ result = PyUnicode_FromString("<no description>");
+ }
+ return result;
}
static char load_library_doc[] =
@@ -1209,24 +1209,24 @@ The handle may be used to locate exported functions in this\n\
module.\n";
static PyObject *load_library(PyObject *self, PyObject *args)
{
- WCHAR *name;
- PyObject *nameobj;
- PyObject *ignored;
- HMODULE hMod;
- if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
- return NULL;
-
- name = PyUnicode_AsUnicode(nameobj);
- if (!name)
- return NULL;
-
- hMod = LoadLibraryW(name);
- if (!hMod)
- return PyErr_SetFromWindowsErr(GetLastError());
+ WCHAR *name;
+ PyObject *nameobj;
+ PyObject *ignored;
+ HMODULE hMod;
+ if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
+ return NULL;
+
+ name = PyUnicode_AsUnicode(nameobj);
+ if (!name)
+ return NULL;
+
+ hMod = LoadLibraryW(name);
+ if (!hMod)
+ return PyErr_SetFromWindowsErr(GetLastError());
#ifdef _WIN64
- return PyLong_FromVoidPtr(hMod);
+ return PyLong_FromVoidPtr(hMod);
#else
- return Py_BuildValue("i", hMod);
+ return Py_BuildValue("i", hMod);
#endif
}
@@ -1236,13 +1236,13 @@ static char free_library_doc[] =
Free the handle of an executable previously loaded by LoadLibrary.\n";
static PyObject *free_library(PyObject *self, PyObject *args)
{
- void *hMod;
- if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
- return NULL;
- if (!FreeLibrary((HMODULE)hMod))
- return PyErr_SetFromWindowsErr(GetLastError());
- Py_INCREF(Py_None);
- return Py_None;
+ void *hMod;
+ if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
+ return NULL;
+ if (!FreeLibrary((HMODULE)hMod))
+ return PyErr_SetFromWindowsErr(GetLastError());
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* obsolete, should be removed */
@@ -1250,55 +1250,55 @@ static PyObject *free_library(PyObject *self, PyObject *args)
static PyObject *
call_commethod(PyObject *self, PyObject *args)
{
- IUnknown *pIunk;
- int index;
- PyObject *arguments;
- PPROC *lpVtbl;
- PyObject *result;
- CDataObject *pcom;
- PyObject *argtypes = NULL;
-
- if (!PyArg_ParseTuple(args,
- "OiO!|O!",
- &pcom, &index,
- &PyTuple_Type, &arguments,
- &PyTuple_Type, &argtypes))
- return NULL;
-
- if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
- PyErr_Format(PyExc_TypeError,
- "Method takes %d arguments (%d given)",
- PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
- return NULL;
- }
-
- if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
- PyErr_Format(PyExc_TypeError,
- "COM Pointer expected instead of %s instance",
- Py_TYPE(pcom)->tp_name);
- return NULL;
- }
-
- if ((*(void **)(pcom->b_ptr)) == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "The COM 'this' pointer is NULL");
- return NULL;
- }
-
- pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
- lpVtbl = (PPROC *)(pIunk->lpVtbl);
-
- result = _ctypes_callproc(lpVtbl[index],
- arguments,
+ IUnknown *pIunk;
+ int index;
+ PyObject *arguments;
+ PPROC *lpVtbl;
+ PyObject *result;
+ CDataObject *pcom;
+ PyObject *argtypes = NULL;
+
+ if (!PyArg_ParseTuple(args,
+ "OiO!|O!",
+ &pcom, &index,
+ &PyTuple_Type, &arguments,
+ &PyTuple_Type, &argtypes))
+ return NULL;
+
+ if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
+ PyErr_Format(PyExc_TypeError,
+ "Method takes %d arguments (%d given)",
+ PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
+ return NULL;
+ }
+
+ if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
+ PyErr_Format(PyExc_TypeError,
+ "COM Pointer expected instead of %s instance",
+ Py_TYPE(pcom)->tp_name);
+ return NULL;
+ }
+
+ if ((*(void **)(pcom->b_ptr)) == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "The COM 'this' pointer is NULL");
+ return NULL;
+ }
+
+ pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
+ lpVtbl = (PPROC *)(pIunk->lpVtbl);
+
+ result = _ctypes_callproc(lpVtbl[index],
+ arguments,
#ifdef MS_WIN32
- pIunk,
- NULL,
+ pIunk,
+ NULL,
#endif
- FUNCFLAG_HRESULT, /* flags */
- argtypes, /* self->argtypes */
- NULL, /* self->restype */
- NULL); /* checker */
- return result;
+ FUNCFLAG_HRESULT, /* flags */
+ argtypes, /* self->argtypes */
+ NULL, /* self->restype */
+ NULL); /* checker */
+ return result;
}
static char copy_com_pointer_doc[] =
@@ -1307,102 +1307,102 @@ static char copy_com_pointer_doc[] =
static PyObject *
copy_com_pointer(PyObject *self, PyObject *args)
{
- PyObject *p1, *p2, *r = NULL;
- struct argument a, b;
- IUnknown *src, **pdst;
- if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
- return NULL;
- a.keep = b.keep = NULL;
-
- if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
- goto done;
- src = (IUnknown *)a.value.p;
- pdst = (IUnknown **)b.value.p;
-
- if (pdst == NULL)
- r = PyLong_FromLong(E_POINTER);
- else {
- if (src)
- src->lpVtbl->AddRef(src);
- *pdst = src;
- r = PyLong_FromLong(S_OK);
- }
+ PyObject *p1, *p2, *r = NULL;
+ struct argument a, b;
+ IUnknown *src, **pdst;
+ if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
+ return NULL;
+ a.keep = b.keep = NULL;
+
+ if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
+ goto done;
+ src = (IUnknown *)a.value.p;
+ pdst = (IUnknown **)b.value.p;
+
+ if (pdst == NULL)
+ r = PyLong_FromLong(E_POINTER);
+ else {
+ if (src)
+ src->lpVtbl->AddRef(src);
+ *pdst = src;
+ r = PyLong_FromLong(S_OK);
+ }
done:
- Py_XDECREF(a.keep);
- Py_XDECREF(b.keep);
- return r;
+ Py_XDECREF(a.keep);
+ Py_XDECREF(b.keep);
+ return r;
}
#else
static PyObject *py_dl_open(PyObject *self, PyObject *args)
{
- PyObject *name, *name2;
- char *name_str;
- void * handle;
-#ifdef RTLD_LOCAL
- int mode = RTLD_NOW | RTLD_LOCAL;
+ PyObject *name, *name2;
+ char *name_str;
+ void * handle;
+#ifdef RTLD_LOCAL
+ int mode = RTLD_NOW | RTLD_LOCAL;
#else
- /* cygwin doesn't define RTLD_LOCAL */
- int mode = RTLD_NOW;
+ /* cygwin doesn't define RTLD_LOCAL */
+ int mode = RTLD_NOW;
#endif
- if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
- return NULL;
- mode |= RTLD_NOW;
- if (name != Py_None) {
- if (PyUnicode_FSConverter(name, &name2) == 0)
- return NULL;
- if (PyBytes_Check(name2))
- name_str = PyBytes_AS_STRING(name2);
- else
- name_str = PyByteArray_AS_STRING(name2);
- } else {
- name_str = NULL;
- name2 = NULL;
- }
- handle = ctypes_dlopen(name_str, mode);
- Py_XDECREF(name2);
- if (!handle) {
- char *errmsg = ctypes_dlerror();
- if (!errmsg)
- errmsg = "dlopen() error";
- PyErr_SetString(PyExc_OSError,
- errmsg);
- return NULL;
- }
- return PyLong_FromVoidPtr(handle);
+ if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
+ return NULL;
+ mode |= RTLD_NOW;
+ if (name != Py_None) {
+ if (PyUnicode_FSConverter(name, &name2) == 0)
+ return NULL;
+ if (PyBytes_Check(name2))
+ name_str = PyBytes_AS_STRING(name2);
+ else
+ name_str = PyByteArray_AS_STRING(name2);
+ } else {
+ name_str = NULL;
+ name2 = NULL;
+ }
+ handle = ctypes_dlopen(name_str, mode);
+ Py_XDECREF(name2);
+ if (!handle) {
+ char *errmsg = ctypes_dlerror();
+ if (!errmsg)
+ errmsg = "dlopen() error";
+ PyErr_SetString(PyExc_OSError,
+ errmsg);
+ return NULL;
+ }
+ return PyLong_FromVoidPtr(handle);
}
static PyObject *py_dl_close(PyObject *self, PyObject *args)
{
- void *handle;
-
- if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
- return NULL;
- if (dlclose(handle)) {
- PyErr_SetString(PyExc_OSError,
- ctypes_dlerror());
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ void *handle;
+
+ if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
+ return NULL;
+ if (dlclose(handle)) {
+ PyErr_SetString(PyExc_OSError,
+ ctypes_dlerror());
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *py_dl_sym(PyObject *self, PyObject *args)
{
- char *name;
- void *handle;
- void *ptr;
-
- if (!PyArg_ParseTuple(args, "O&s:dlsym",
- &_parse_voidp, &handle, &name))
- return NULL;
- ptr = ctypes_dlsym((void*)handle, name);
- if (!ptr) {
- PyErr_SetString(PyExc_OSError,
- ctypes_dlerror());
- return NULL;
- }
- return PyLong_FromVoidPtr(ptr);
+ char *name;
+ void *handle;
+ void *ptr;
+
+ if (!PyArg_ParseTuple(args, "O&s:dlsym",
+ &_parse_voidp, &handle, &name))
+ return NULL;
+ ptr = ctypes_dlsym((void*)handle, name);
+ if (!ptr) {
+ PyErr_SetString(PyExc_OSError,
+ ctypes_dlerror());
+ return NULL;
+ }
+ return PyLong_FromVoidPtr(ptr);
}
#endif
@@ -1414,27 +1414,27 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args)
static PyObject *
call_function(PyObject *self, PyObject *args)
{
- void *func;
- PyObject *arguments;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args,
- "O&O!",
- &_parse_voidp, &func,
- &PyTuple_Type, &arguments))
- return NULL;
-
- result = _ctypes_callproc((PPROC)func,
- arguments,
+ void *func;
+ PyObject *arguments;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args,
+ "O&O!",
+ &_parse_voidp, &func,
+ &PyTuple_Type, &arguments))
+ return NULL;
+
+ result = _ctypes_callproc((PPROC)func,
+ arguments,
#ifdef MS_WIN32
- NULL,
- NULL,
+ NULL,
+ NULL,
#endif
- 0, /* flags */
- NULL, /* self->argtypes */
- NULL, /* self->restype */
- NULL); /* checker */
- return result;
+ 0, /* flags */
+ NULL, /* self->argtypes */
+ NULL, /* self->restype */
+ NULL); /* checker */
+ return result;
}
/*
@@ -1445,27 +1445,27 @@ call_function(PyObject *self, PyObject *args)
static PyObject *
call_cdeclfunction(PyObject *self, PyObject *args)
{
- void *func;
- PyObject *arguments;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args,
- "O&O!",
- &_parse_voidp, &func,
- &PyTuple_Type, &arguments))
- return NULL;
-
- result = _ctypes_callproc((PPROC)func,
- arguments,
+ void *func;
+ PyObject *arguments;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args,
+ "O&O!",
+ &_parse_voidp, &func,
+ &PyTuple_Type, &arguments))
+ return NULL;
+
+ result = _ctypes_callproc((PPROC)func,
+ arguments,
#ifdef MS_WIN32
- NULL,
- NULL,
+ NULL,
+ NULL,
#endif
- FUNCFLAG_CDECL, /* flags */
- NULL, /* self->argtypes */
- NULL, /* self->restype */
- NULL); /* checker */
- return result;
+ FUNCFLAG_CDECL, /* flags */
+ NULL, /* self->argtypes */
+ NULL, /* self->restype */
+ NULL); /* checker */
+ return result;
}
/*****************************************************************
@@ -1479,17 +1479,17 @@ static char sizeof_doc[] =
static PyObject *
sizeof_func(PyObject *self, PyObject *obj)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict(obj);
- if (dict)
- return PyLong_FromSsize_t(dict->size);
+ dict = PyType_stgdict(obj);
+ if (dict)
+ return PyLong_FromSsize_t(dict->size);
- if (CDataObject_Check(obj))
- return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
- PyErr_SetString(PyExc_TypeError,
- "this type has no size");
- return NULL;
+ if (CDataObject_Check(obj))
+ return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
+ PyErr_SetString(PyExc_TypeError,
+ "this type has no size");
+ return NULL;
}
static char alignment_doc[] =
@@ -1500,19 +1500,19 @@ static char alignment_doc[] =
static PyObject *
align_func(PyObject *self, PyObject *obj)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict(obj);
- if (dict)
- return PyLong_FromSsize_t(dict->align);
+ dict = PyType_stgdict(obj);
+ if (dict)
+ return PyLong_FromSsize_t(dict->align);
- dict = PyObject_stgdict(obj);
- if (dict)
- return PyLong_FromSsize_t(dict->align);
+ dict = PyObject_stgdict(obj);
+ if (dict)
+ return PyLong_FromSsize_t(dict->align);
- PyErr_SetString(PyExc_TypeError,
- "no alignment info");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "no alignment info");
+ return NULL;
}
static char byref_doc[] =
@@ -1527,36 +1527,36 @@ static char byref_doc[] =
static PyObject *
byref(PyObject *self, PyObject *args)
{
- PyCArgObject *parg;
- PyObject *obj;
- PyObject *pyoffset = NULL;
- Py_ssize_t offset = 0;
-
- if (!PyArg_UnpackTuple(args, "byref", 1, 2,
- &obj, &pyoffset))
- return NULL;
- if (pyoffset) {
- offset = PyNumber_AsSsize_t(pyoffset, NULL);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
- }
- if (!CDataObject_Check(obj)) {
- PyErr_Format(PyExc_TypeError,
- "byref() argument must be a ctypes instance, not '%s'",
- Py_TYPE(obj)->tp_name);
- return NULL;
- }
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- Py_INCREF(obj);
- parg->obj = obj;
- parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
- return (PyObject *)parg;
+ PyCArgObject *parg;
+ PyObject *obj;
+ PyObject *pyoffset = NULL;
+ Py_ssize_t offset = 0;
+
+ if (!PyArg_UnpackTuple(args, "byref", 1, 2,
+ &obj, &pyoffset))
+ return NULL;
+ if (pyoffset) {
+ offset = PyNumber_AsSsize_t(pyoffset, NULL);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ if (!CDataObject_Check(obj)) {
+ PyErr_Format(PyExc_TypeError,
+ "byref() argument must be a ctypes instance, not '%s'",
+ Py_TYPE(obj)->tp_name);
+ return NULL;
+ }
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ Py_INCREF(obj);
+ parg->obj = obj;
+ parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
+ return (PyObject *)parg;
}
static char addressof_doc[] =
@@ -1566,44 +1566,44 @@ static char addressof_doc[] =
static PyObject *
addressof(PyObject *self, PyObject *obj)
{
- if (CDataObject_Check(obj))
- return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
- PyErr_SetString(PyExc_TypeError,
- "invalid type");
- return NULL;
+ if (CDataObject_Check(obj))
+ return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
+ PyErr_SetString(PyExc_TypeError,
+ "invalid type");
+ return NULL;
}
static int
converter(PyObject *obj, void **address)
{
- *address = PyLong_AsVoidPtr(obj);
- return *address != NULL;
+ *address = PyLong_AsVoidPtr(obj);
+ return *address != NULL;
}
static PyObject *
My_PyObj_FromPtr(PyObject *self, PyObject *args)
{
- PyObject *ob;
- if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
- return NULL;
- Py_INCREF(ob);
- return ob;
+ PyObject *ob;
+ if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
+ return NULL;
+ Py_INCREF(ob);
+ return ob;
}
static PyObject *
My_Py_INCREF(PyObject *self, PyObject *arg)
{
- Py_INCREF(arg); /* that's what this function is for */
- Py_INCREF(arg); /* that for returning it */
- return arg;
+ Py_INCREF(arg); /* that's what this function is for */
+ Py_INCREF(arg); /* that for returning it */
+ return arg;
}
static PyObject *
My_Py_DECREF(PyObject *self, PyObject *arg)
{
- Py_DECREF(arg); /* that's what this function is for */
- Py_INCREF(arg); /* that's for returning it */
- return arg;
+ Py_DECREF(arg); /* that's what this function is for */
+ Py_INCREF(arg); /* that's for returning it */
+ return arg;
}
#ifdef CTYPES_UNICODE
@@ -1617,234 +1617,234 @@ between unicode and strings. Returns the previous values.\n";
static PyObject *
set_conversion_mode(PyObject *self, PyObject *args)
{
- char *coding, *mode;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
- return NULL;
- result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
- if (coding) {
- PyMem_Free(_ctypes_conversion_encoding);
- _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
- strcpy(_ctypes_conversion_encoding, coding);
- } else {
- _ctypes_conversion_encoding = NULL;
- }
- PyMem_Free(_ctypes_conversion_errors);
- _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
- strcpy(_ctypes_conversion_errors, mode);
- return result;
+ char *coding, *mode;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
+ return NULL;
+ result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
+ if (coding) {
+ PyMem_Free(_ctypes_conversion_encoding);
+ _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
+ strcpy(_ctypes_conversion_encoding, coding);
+ } else {
+ _ctypes_conversion_encoding = NULL;
+ }
+ PyMem_Free(_ctypes_conversion_errors);
+ _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
+ strcpy(_ctypes_conversion_errors, mode);
+ return result;
}
#endif
static PyObject *
resize(PyObject *self, PyObject *args)
{
- CDataObject *obj;
- StgDictObject *dict;
- Py_ssize_t size;
-
- if (!PyArg_ParseTuple(args,
- "On:resize",
- &obj, &size))
- return NULL;
-
- dict = PyObject_stgdict((PyObject *)obj);
- if (dict == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "excepted ctypes instance");
- return NULL;
- }
- if (size < dict->size) {
- PyErr_Format(PyExc_ValueError,
- "minimum size is %zd",
- dict->size);
- return NULL;
- }
- if (obj->b_needsfree == 0) {
- PyErr_Format(PyExc_ValueError,
- "Memory cannot be resized because this object doesn't own it");
- return NULL;
- }
- if (size <= sizeof(obj->b_value)) {
- /* internal default buffer is large enough */
- obj->b_size = size;
- goto done;
- }
- if (obj->b_size <= sizeof(obj->b_value)) {
- /* We are currently using the objects default buffer, but it
- isn't large enough any more. */
- void *ptr = PyMem_Malloc(size);
- if (ptr == NULL)
- return PyErr_NoMemory();
- memset(ptr, 0, size);
- memmove(ptr, obj->b_ptr, obj->b_size);
- obj->b_ptr = ptr;
- obj->b_size = size;
- } else {
- void * ptr = PyMem_Realloc(obj->b_ptr, size);
- if (ptr == NULL)
- return PyErr_NoMemory();
- obj->b_ptr = ptr;
- obj->b_size = size;
- }
+ CDataObject *obj;
+ StgDictObject *dict;
+ Py_ssize_t size;
+
+ if (!PyArg_ParseTuple(args,
+ "On:resize",
+ &obj, &size))
+ return NULL;
+
+ dict = PyObject_stgdict((PyObject *)obj);
+ if (dict == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "excepted ctypes instance");
+ return NULL;
+ }
+ if (size < dict->size) {
+ PyErr_Format(PyExc_ValueError,
+ "minimum size is %zd",
+ dict->size);
+ return NULL;
+ }
+ if (obj->b_needsfree == 0) {
+ PyErr_Format(PyExc_ValueError,
+ "Memory cannot be resized because this object doesn't own it");
+ return NULL;
+ }
+ if (size <= sizeof(obj->b_value)) {
+ /* internal default buffer is large enough */
+ obj->b_size = size;
+ goto done;
+ }
+ if (obj->b_size <= sizeof(obj->b_value)) {
+ /* We are currently using the objects default buffer, but it
+ isn't large enough any more. */
+ void *ptr = PyMem_Malloc(size);
+ if (ptr == NULL)
+ return PyErr_NoMemory();
+ memset(ptr, 0, size);
+ memmove(ptr, obj->b_ptr, obj->b_size);
+ obj->b_ptr = ptr;
+ obj->b_size = size;
+ } else {
+ void * ptr = PyMem_Realloc(obj->b_ptr, size);
+ if (ptr == NULL)
+ return PyErr_NoMemory();
+ obj->b_ptr = ptr;
+ obj->b_size = size;
+ }
done:
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
unpickle(PyObject *self, PyObject *args)
{
- PyObject *typ;
- PyObject *state;
- PyObject *result;
- PyObject *tmp;
-
- if (!PyArg_ParseTuple(args, "OO", &typ, &state))
- return NULL;
- result = PyObject_CallMethod(typ, "__new__", "O", typ);
- if (result == NULL)
- return NULL;
- tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
- if (tmp == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(tmp);
- return result;
+ PyObject *typ;
+ PyObject *state;
+ PyObject *result;
+ PyObject *tmp;
+
+ if (!PyArg_ParseTuple(args, "OO", &typ, &state))
+ return NULL;
+ result = PyObject_CallMethod(typ, "__new__", "O", typ);
+ if (result == NULL)
+ return NULL;
+ tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
+ if (tmp == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(tmp);
+ return result;
}
static PyObject *
POINTER(PyObject *self, PyObject *cls)
{
- PyObject *result;
- PyTypeObject *typ;
- PyObject *key;
- char *buf;
-
- result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
- if (result) {
- Py_INCREF(result);
- return result;
- }
- if (PyUnicode_CheckExact(cls)) {
- char *name = _PyUnicode_AsString(cls);
- buf = alloca(strlen(name) + 3 + 1);
- sprintf(buf, "LP_%s", name);
- result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
- "s(O){}",
- buf,
- &PyCPointer_Type);
- if (result == NULL)
- return result;
- key = PyLong_FromVoidPtr(result);
- } else if (PyType_Check(cls)) {
- typ = (PyTypeObject *)cls;
- buf = alloca(strlen(typ->tp_name) + 3 + 1);
- sprintf(buf, "LP_%s", typ->tp_name);
- result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
- "s(O){sO}",
- buf,
- &PyCPointer_Type,
- "_type_", cls);
- if (result == NULL)
- return result;
- Py_INCREF(cls);
- key = cls;
- } else {
- PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
- return NULL;
- }
- if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
- Py_DECREF(result);
- Py_DECREF(key);
- return NULL;
- }
- Py_DECREF(key);
- return result;
+ PyObject *result;
+ PyTypeObject *typ;
+ PyObject *key;
+ char *buf;
+
+ result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
+ if (result) {
+ Py_INCREF(result);
+ return result;
+ }
+ if (PyUnicode_CheckExact(cls)) {
+ char *name = _PyUnicode_AsString(cls);
+ buf = alloca(strlen(name) + 3 + 1);
+ sprintf(buf, "LP_%s", name);
+ result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
+ "s(O){}",
+ buf,
+ &PyCPointer_Type);
+ if (result == NULL)
+ return result;
+ key = PyLong_FromVoidPtr(result);
+ } else if (PyType_Check(cls)) {
+ typ = (PyTypeObject *)cls;
+ buf = alloca(strlen(typ->tp_name) + 3 + 1);
+ sprintf(buf, "LP_%s", typ->tp_name);
+ result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
+ "s(O){sO}",
+ buf,
+ &PyCPointer_Type,
+ "_type_", cls);
+ if (result == NULL)
+ return result;
+ Py_INCREF(cls);
+ key = cls;
+ } else {
+ PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
+ return NULL;
+ }
+ if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
+ Py_DECREF(result);
+ Py_DECREF(key);
+ return NULL;
+ }
+ Py_DECREF(key);
+ return result;
}
static PyObject *
pointer(PyObject *self, PyObject *arg)
{
- PyObject *result;
- PyObject *typ;
-
- typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
- if (typ)
- return PyObject_CallFunctionObjArgs(typ, arg, NULL);
- typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
- if (typ == NULL)
- return NULL;
- result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
- Py_DECREF(typ);
- return result;
+ PyObject *result;
+ PyObject *typ;
+
+ typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
+ if (typ)
+ return PyObject_CallFunctionObjArgs(typ, arg, NULL);
+ typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
+ if (typ == NULL)
+ return NULL;
+ result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
+ Py_DECREF(typ);
+ return result;
}
static PyObject *
buffer_info(PyObject *self, PyObject *arg)
{
- StgDictObject *dict = PyType_stgdict(arg);
- PyObject *shape;
- Py_ssize_t i;
-
- if (dict == NULL)
- dict = PyObject_stgdict(arg);
- if (dict == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "not a ctypes type or object");
- return NULL;
- }
- shape = PyTuple_New(dict->ndim);
- if (shape == NULL)
- return NULL;
- for (i = 0; i < (int)dict->ndim; ++i)
- PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
-
- if (PyErr_Occurred()) {
- Py_DECREF(shape);
- return NULL;
- }
- return Py_BuildValue("siN", dict->format, dict->ndim, shape);
+ StgDictObject *dict = PyType_stgdict(arg);
+ PyObject *shape;
+ Py_ssize_t i;
+
+ if (dict == NULL)
+ dict = PyObject_stgdict(arg);
+ if (dict == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "not a ctypes type or object");
+ return NULL;
+ }
+ shape = PyTuple_New(dict->ndim);
+ if (shape == NULL)
+ return NULL;
+ for (i = 0; i < (int)dict->ndim; ++i)
+ PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(shape);
+ return NULL;
+ }
+ return Py_BuildValue("siN", dict->format, dict->ndim, shape);
}
PyMethodDef _ctypes_module_methods[] = {
- {"get_errno", get_errno, METH_NOARGS},
- {"set_errno", set_errno, METH_VARARGS},
- {"POINTER", POINTER, METH_O },
- {"pointer", pointer, METH_O },
- {"_unpickle", unpickle, METH_VARARGS },
- {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
- {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
+ {"get_errno", get_errno, METH_NOARGS},
+ {"set_errno", set_errno, METH_VARARGS},
+ {"POINTER", POINTER, METH_O },
+ {"pointer", pointer, METH_O },
+ {"_unpickle", unpickle, METH_VARARGS },
+ {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
+ {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
#ifdef CTYPES_UNICODE
- {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
+ {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
#endif
#ifdef MS_WIN32
- {"get_last_error", get_last_error, METH_NOARGS},
- {"set_last_error", set_last_error, METH_VARARGS},
- {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
- {"FormatError", format_error, METH_VARARGS, format_error_doc},
- {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
- {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
- {"call_commethod", call_commethod, METH_VARARGS },
- {"_check_HRESULT", check_hresult, METH_VARARGS},
+ {"get_last_error", get_last_error, METH_NOARGS},
+ {"set_last_error", set_last_error, METH_VARARGS},
+ {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
+ {"FormatError", format_error, METH_VARARGS, format_error_doc},
+ {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
+ {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
+ {"call_commethod", call_commethod, METH_VARARGS },
+ {"_check_HRESULT", check_hresult, METH_VARARGS},
#else
- {"dlopen", py_dl_open, METH_VARARGS,
- "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
- {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
- {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
+ {"dlopen", py_dl_open, METH_VARARGS,
+ "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
+ {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
+ {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
#endif
- {"alignment", align_func, METH_O, alignment_doc},
- {"sizeof", sizeof_func, METH_O, sizeof_doc},
- {"byref", byref, METH_VARARGS, byref_doc},
- {"addressof", addressof, METH_O, addressof_doc},
- {"call_function", call_function, METH_VARARGS },
- {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
- {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
- {"Py_INCREF", My_Py_INCREF, METH_O },
- {"Py_DECREF", My_Py_DECREF, METH_O },
- {NULL, NULL} /* Sentinel */
+ {"alignment", align_func, METH_O, alignment_doc},
+ {"sizeof", sizeof_func, METH_O, sizeof_doc},
+ {"byref", byref, METH_VARARGS, byref_doc},
+ {"addressof", addressof, METH_O, addressof_doc},
+ {"call_function", call_function, METH_VARARGS },
+ {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
+ {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
+ {"Py_INCREF", My_Py_INCREF, METH_O },
+ {"Py_DECREF", My_Py_DECREF, METH_O },
+ {NULL, NULL} /* Sentinel */
};
/*
diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c
index f7fd7fa..441ed9e 100644
--- a/Modules/_ctypes/cfield.c
+++ b/Modules/_ctypes/cfield.c
@@ -11,10 +11,10 @@
static void pymem_destructor(PyObject *ptr)
{
- void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM);
- if (p) {
- PyMem_Free(p);
- }
+ void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM);
+ if (p) {
+ PyMem_Free(p);
+ }
}
@@ -25,9 +25,9 @@ static void pymem_destructor(PyObject *ptr)
static PyObject *
PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- CFieldObject *obj;
- obj = (CFieldObject *)type->tp_alloc(type, 0);
- return (PyObject *)obj;
+ CFieldObject *obj;
+ obj = (CFieldObject *)type->tp_alloc(type, 0);
+ return (PyObject *)obj;
}
/*
@@ -44,297 +44,297 @@ PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
*/
PyObject *
PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
- Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
- Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
- int pack, int big_endian)
-{
- CFieldObject *self;
- PyObject *proto;
- Py_ssize_t size, align, length;
- SETFUNC setfunc = NULL;
- GETFUNC getfunc = NULL;
- StgDictObject *dict;
- int fieldtype;
+ Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
+ Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
+ int pack, int big_endian)
+{
+ CFieldObject *self;
+ PyObject *proto;
+ Py_ssize_t size, align, length;
+ SETFUNC setfunc = NULL;
+ GETFUNC getfunc = NULL;
+ StgDictObject *dict;
+ int fieldtype;
#define NO_BITFIELD 0
#define NEW_BITFIELD 1
#define CONT_BITFIELD 2
#define EXPAND_BITFIELD 3
- self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type,
- NULL);
- if (self == NULL)
- return NULL;
- dict = PyType_stgdict(desc);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "has no _stginfo_");
- Py_DECREF(self);
- return NULL;
- }
- if (bitsize /* this is a bitfield request */
- && *pfield_size /* we have a bitfield open */
+ self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type,
+ NULL);
+ if (self == NULL)
+ return NULL;
+ dict = PyType_stgdict(desc);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "has no _stginfo_");
+ Py_DECREF(self);
+ return NULL;
+ }
+ if (bitsize /* this is a bitfield request */
+ && *pfield_size /* we have a bitfield open */
#ifdef MS_WIN32
- /* MSVC, GCC with -mms-bitfields */
- && dict->size * 8 == *pfield_size
+ /* MSVC, GCC with -mms-bitfields */
+ && dict->size * 8 == *pfield_size
#else
- /* GCC */
- && dict->size * 8 <= *pfield_size
+ /* GCC */
+ && dict->size * 8 <= *pfield_size
#endif
- && (*pbitofs + bitsize) <= *pfield_size) {
- /* continue bit field */
- fieldtype = CONT_BITFIELD;
+ && (*pbitofs + bitsize) <= *pfield_size) {
+ /* continue bit field */
+ fieldtype = CONT_BITFIELD;
#ifndef MS_WIN32
- } else if (bitsize /* this is a bitfield request */
- && *pfield_size /* we have a bitfield open */
- && dict->size * 8 >= *pfield_size
- && (*pbitofs + bitsize) <= dict->size * 8) {
- /* expand bit field */
- fieldtype = EXPAND_BITFIELD;
+ } else if (bitsize /* this is a bitfield request */
+ && *pfield_size /* we have a bitfield open */
+ && dict->size * 8 >= *pfield_size
+ && (*pbitofs + bitsize) <= dict->size * 8) {
+ /* expand bit field */
+ fieldtype = EXPAND_BITFIELD;
#endif
- } else if (bitsize) {
- /* start new bitfield */
- fieldtype = NEW_BITFIELD;
- *pbitofs = 0;
- *pfield_size = dict->size * 8;
- } else {
- /* not a bit field */
- fieldtype = NO_BITFIELD;
- *pbitofs = 0;
- *pfield_size = 0;
- }
-
- size = dict->size;
- length = dict->length;
- proto = desc;
-
- /* Field descriptors for 'c_char * n' are be scpecial cased to
- return a Python string instead of an Array object instance...
- */
- if (PyCArrayTypeObject_Check(proto)) {
- StgDictObject *adict = PyType_stgdict(proto);
- StgDictObject *idict;
- if (adict && adict->proto) {
- idict = PyType_stgdict(adict->proto);
- if (!idict) {
- PyErr_SetString(PyExc_TypeError,
- "has no _stginfo_");
- Py_DECREF(self);
- return NULL;
- }
- if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- struct fielddesc *fd = _ctypes_get_fielddesc("s");
- getfunc = fd->getfunc;
- setfunc = fd->setfunc;
- }
+ } else if (bitsize) {
+ /* start new bitfield */
+ fieldtype = NEW_BITFIELD;
+ *pbitofs = 0;
+ *pfield_size = dict->size * 8;
+ } else {
+ /* not a bit field */
+ fieldtype = NO_BITFIELD;
+ *pbitofs = 0;
+ *pfield_size = 0;
+ }
+
+ size = dict->size;
+ length = dict->length;
+ proto = desc;
+
+ /* Field descriptors for 'c_char * n' are be scpecial cased to
+ return a Python string instead of an Array object instance...
+ */
+ if (PyCArrayTypeObject_Check(proto)) {
+ StgDictObject *adict = PyType_stgdict(proto);
+ StgDictObject *idict;
+ if (adict && adict->proto) {
+ idict = PyType_stgdict(adict->proto);
+ if (!idict) {
+ PyErr_SetString(PyExc_TypeError,
+ "has no _stginfo_");
+ Py_DECREF(self);
+ return NULL;
+ }
+ if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ struct fielddesc *fd = _ctypes_get_fielddesc("s");
+ getfunc = fd->getfunc;
+ setfunc = fd->setfunc;
+ }
#ifdef CTYPES_UNICODE
- if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- struct fielddesc *fd = _ctypes_get_fielddesc("U");
- getfunc = fd->getfunc;
- setfunc = fd->setfunc;
- }
+ if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ struct fielddesc *fd = _ctypes_get_fielddesc("U");
+ getfunc = fd->getfunc;
+ setfunc = fd->setfunc;
+ }
#endif
- }
- }
-
- self->setfunc = setfunc;
- self->getfunc = getfunc;
- self->index = index;
-
- Py_INCREF(proto);
- self->proto = proto;
-
- switch (fieldtype) {
- case NEW_BITFIELD:
- if (big_endian)
- self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
- else
- self->size = (bitsize << 16) + *pbitofs;
- *pbitofs = bitsize;
- /* fall through */
- case NO_BITFIELD:
- if (pack)
- align = min(pack, dict->align);
- else
- align = dict->align;
- if (align && *poffset % align) {
- Py_ssize_t delta = align - (*poffset % align);
- *psize += delta;
- *poffset += delta;
- }
-
- if (bitsize == 0)
- self->size = size;
- *psize += size;
-
- self->offset = *poffset;
- *poffset += size;
-
- *palign = align;
- break;
-
- case EXPAND_BITFIELD:
- *poffset += dict->size - *pfield_size/8;
- *psize += dict->size - *pfield_size/8;
-
- *pfield_size = dict->size * 8;
-
- if (big_endian)
- self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
- else
- self->size = (bitsize << 16) + *pbitofs;
-
- self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
- *pbitofs += bitsize;
- break;
-
- case CONT_BITFIELD:
- if (big_endian)
- self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
- else
- self->size = (bitsize << 16) + *pbitofs;
-
- self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
- *pbitofs += bitsize;
- break;
- }
-
- return (PyObject *)self;
+ }
+ }
+
+ self->setfunc = setfunc;
+ self->getfunc = getfunc;
+ self->index = index;
+
+ Py_INCREF(proto);
+ self->proto = proto;
+
+ switch (fieldtype) {
+ case NEW_BITFIELD:
+ if (big_endian)
+ self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
+ else
+ self->size = (bitsize << 16) + *pbitofs;
+ *pbitofs = bitsize;
+ /* fall through */
+ case NO_BITFIELD:
+ if (pack)
+ align = min(pack, dict->align);
+ else
+ align = dict->align;
+ if (align && *poffset % align) {
+ Py_ssize_t delta = align - (*poffset % align);
+ *psize += delta;
+ *poffset += delta;
+ }
+
+ if (bitsize == 0)
+ self->size = size;
+ *psize += size;
+
+ self->offset = *poffset;
+ *poffset += size;
+
+ *palign = align;
+ break;
+
+ case EXPAND_BITFIELD:
+ *poffset += dict->size - *pfield_size/8;
+ *psize += dict->size - *pfield_size/8;
+
+ *pfield_size = dict->size * 8;
+
+ if (big_endian)
+ self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
+ else
+ self->size = (bitsize << 16) + *pbitofs;
+
+ self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
+ *pbitofs += bitsize;
+ break;
+
+ case CONT_BITFIELD:
+ if (big_endian)
+ self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
+ else
+ self->size = (bitsize << 16) + *pbitofs;
+
+ self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
+ *pbitofs += bitsize;
+ break;
+ }
+
+ return (PyObject *)self;
}
static int
PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value)
{
- CDataObject *dst;
- char *ptr;
- assert(CDataObject_Check(inst));
- dst = (CDataObject *)inst;
- ptr = dst->b_ptr + self->offset;
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
- return PyCData_set(inst, self->proto, self->setfunc, value,
- self->index, self->size, ptr);
+ CDataObject *dst;
+ char *ptr;
+ assert(CDataObject_Check(inst));
+ dst = (CDataObject *)inst;
+ ptr = dst->b_ptr + self->offset;
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+ return PyCData_set(inst, self->proto, self->setfunc, value,
+ self->index, self->size, ptr);
}
static PyObject *
PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type)
{
- CDataObject *src;
- if (inst == NULL) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- assert(CDataObject_Check(inst));
- src = (CDataObject *)inst;
- return PyCData_get(self->proto, self->getfunc, inst,
- self->index, self->size, src->b_ptr + self->offset);
+ CDataObject *src;
+ if (inst == NULL) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ assert(CDataObject_Check(inst));
+ src = (CDataObject *)inst;
+ return PyCData_get(self->proto, self->getfunc, inst,
+ self->index, self->size, src->b_ptr + self->offset);
}
static PyObject *
PyCField_get_offset(PyObject *self, void *data)
{
- return PyLong_FromSsize_t(((CFieldObject *)self)->offset);
+ return PyLong_FromSsize_t(((CFieldObject *)self)->offset);
}
static PyObject *
PyCField_get_size(PyObject *self, void *data)
{
- return PyLong_FromSsize_t(((CFieldObject *)self)->size);
+ return PyLong_FromSsize_t(((CFieldObject *)self)->size);
}
static PyGetSetDef PyCField_getset[] = {
- { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" },
- { "size", PyCField_get_size, NULL, "size in bytes of this field" },
- { NULL, NULL, NULL, NULL },
+ { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" },
+ { "size", PyCField_get_size, NULL, "size in bytes of this field" },
+ { NULL, NULL, NULL, NULL },
};
static int
PyCField_traverse(CFieldObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->proto);
- return 0;
+ Py_VISIT(self->proto);
+ return 0;
}
static int
PyCField_clear(CFieldObject *self)
{
- Py_CLEAR(self->proto);
- return 0;
+ Py_CLEAR(self->proto);
+ return 0;
}
static void
PyCField_dealloc(PyObject *self)
{
- PyCField_clear((CFieldObject *)self);
- self->ob_type->tp_free((PyObject *)self);
+ PyCField_clear((CFieldObject *)self);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *
PyCField_repr(CFieldObject *self)
{
- PyObject *result;
- Py_ssize_t bits = self->size >> 16;
- Py_ssize_t size = self->size & 0xFFFF;
- const char *name;
+ PyObject *result;
+ Py_ssize_t bits = self->size >> 16;
+ Py_ssize_t size = self->size & 0xFFFF;
+ const char *name;
- name = ((PyTypeObject *)self->proto)->tp_name;
+ name = ((PyTypeObject *)self->proto)->tp_name;
- if (bits)
- result = PyUnicode_FromFormat(
- "<Field type=%s, ofs=%zd:%zd, bits=%zd>",
- name, self->offset, size, bits);
- else
- result = PyUnicode_FromFormat(
- "<Field type=%s, ofs=%zd, size=%zd>",
- name, self->offset, size);
- return result;
+ if (bits)
+ result = PyUnicode_FromFormat(
+ "<Field type=%s, ofs=%zd:%zd, bits=%zd>",
+ name, self->offset, size, bits);
+ else
+ result = PyUnicode_FromFormat(
+ "<Field type=%s, ofs=%zd, size=%zd>",
+ name, self->offset, size);
+ return result;
}
PyTypeObject PyCField_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CField", /* tp_name */
- sizeof(CFieldObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- PyCField_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)PyCField_repr, /* 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_HAVE_GC, /* tp_flags */
- "Structure/Union member", /* tp_doc */
- (traverseproc)PyCField_traverse, /* tp_traverse */
- (inquiry)PyCField_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- PyCField_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)PyCField_get, /* tp_descr_get */
- (descrsetfunc)PyCField_set, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCField_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CField", /* tp_name */
+ sizeof(CFieldObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ PyCField_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)PyCField_repr, /* 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_HAVE_GC, /* tp_flags */
+ "Structure/Union member", /* tp_doc */
+ (traverseproc)PyCField_traverse, /* tp_traverse */
+ (inquiry)PyCField_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ PyCField_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)PyCField_get, /* tp_descr_get */
+ (descrsetfunc)PyCField_set, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCField_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
Accessor functions
@@ -347,18 +347,18 @@ PyTypeObject PyCField_Type = {
static int
get_long(PyObject *v, long *p)
{
- long x;
+ long x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyLong_AsUnsignedLongMask(v);
- if (x == -1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyLong_AsUnsignedLongMask(v);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling unsigned long */
@@ -366,18 +366,18 @@ get_long(PyObject *v, long *p)
static int
get_ulong(PyObject *v, unsigned long *p)
{
- unsigned long x;
+ unsigned long x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyLong_AsUnsignedLongMask(v);
- if (x == (unsigned long)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyLong_AsUnsignedLongMask(v);
+ if (x == (unsigned long)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -387,17 +387,17 @@ get_ulong(PyObject *v, unsigned long *p)
static int
get_longlong(PyObject *v, PY_LONG_LONG *p)
{
- PY_LONG_LONG x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyLong_AsUnsignedLongLongMask(v);
- if (x == -1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ PY_LONG_LONG x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyLong_AsUnsignedLongLongMask(v);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling native unsigned long long. */
@@ -405,17 +405,17 @@ get_longlong(PyObject *v, PY_LONG_LONG *p)
static int
get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
{
- unsigned PY_LONG_LONG x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyLong_AsUnsignedLongLongMask(v);
- if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ unsigned PY_LONG_LONG x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyLong_AsUnsignedLongLongMask(v);
+ if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#endif
@@ -438,49 +438,49 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
/* This macro CHANGES the first parameter IN PLACE. For proper sign handling,
we must first shift left, then right.
*/
-#define GET_BITFIELD(v, size) \
- if (NUM_BITS(size)) { \
- v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
- v >>= (sizeof(v)*8 - NUM_BITS(size)); \
- }
+#define GET_BITFIELD(v, size) \
+ if (NUM_BITS(size)) { \
+ v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
+ v >>= (sizeof(v)*8 - NUM_BITS(size)); \
+ }
/* This macro RETURNS the first parameter with the bit field CHANGED. */
-#define SET(x, v, size) \
- (NUM_BITS(size) ? \
- ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \
- : v)
+#define SET(x, v, size) \
+ (NUM_BITS(size) ? \
+ ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \
+ : v)
/* byte swapping macros */
-#define SWAP_2(v) \
- ( ( (v >> 8) & 0x00FF) | \
- ( (v << 8) & 0xFF00) )
+#define SWAP_2(v) \
+ ( ( (v >> 8) & 0x00FF) | \
+ ( (v << 8) & 0xFF00) )
-#define SWAP_4(v) \
- ( ( (v & 0x000000FF) << 24 ) | \
- ( (v & 0x0000FF00) << 8 ) | \
- ( (v & 0x00FF0000) >> 8 ) | \
- ( ((v >> 24) & 0xFF)) )
+#define SWAP_4(v) \
+ ( ( (v & 0x000000FF) << 24 ) | \
+ ( (v & 0x0000FF00) << 8 ) | \
+ ( (v & 0x00FF0000) >> 8 ) | \
+ ( ((v >> 24) & 0xFF)) )
#ifdef _MSC_VER
-#define SWAP_8(v) \
- ( ( (v & 0x00000000000000FFL) << 56 ) | \
- ( (v & 0x000000000000FF00L) << 40 ) | \
- ( (v & 0x0000000000FF0000L) << 24 ) | \
- ( (v & 0x00000000FF000000L) << 8 ) | \
- ( (v & 0x000000FF00000000L) >> 8 ) | \
- ( (v & 0x0000FF0000000000L) >> 24 ) | \
- ( (v & 0x00FF000000000000L) >> 40 ) | \
- ( ((v >> 56) & 0xFF)) )
+#define SWAP_8(v) \
+ ( ( (v & 0x00000000000000FFL) << 56 ) | \
+ ( (v & 0x000000000000FF00L) << 40 ) | \
+ ( (v & 0x0000000000FF0000L) << 24 ) | \
+ ( (v & 0x00000000FF000000L) << 8 ) | \
+ ( (v & 0x000000FF00000000L) >> 8 ) | \
+ ( (v & 0x0000FF0000000000L) >> 24 ) | \
+ ( (v & 0x00FF000000000000L) >> 40 ) | \
+ ( ((v >> 56) & 0xFF)) )
#else
-#define SWAP_8(v) \
- ( ( (v & 0x00000000000000FFLL) << 56 ) | \
- ( (v & 0x000000000000FF00LL) << 40 ) | \
- ( (v & 0x0000000000FF0000LL) << 24 ) | \
- ( (v & 0x00000000FF000000LL) << 8 ) | \
- ( (v & 0x000000FF00000000LL) >> 8 ) | \
- ( (v & 0x0000FF0000000000LL) >> 24 ) | \
- ( (v & 0x00FF000000000000LL) >> 40 ) | \
- ( ((v >> 56) & 0xFF)) )
+#define SWAP_8(v) \
+ ( ( (v & 0x00000000000000FFLL) << 56 ) | \
+ ( (v & 0x000000000000FF00LL) << 40 ) | \
+ ( (v & 0x0000000000FF0000LL) << 24 ) | \
+ ( (v & 0x00000000FF000000LL) << 8 ) | \
+ ( (v & 0x000000FF00000000LL) >> 8 ) | \
+ ( (v & 0x0000FF0000000000LL) >> 24 ) | \
+ ( (v & 0x00FF000000000000LL) >> 40 ) | \
+ ( ((v >> 56) & 0xFF)) )
#endif
#define SWAP_INT SWAP_4
@@ -517,184 +517,184 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
static PyObject *
b_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- if (get_long(value, &val) < 0)
- return NULL;
- *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size);
- _RET(value);
+ long val;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size);
+ _RET(value);
}
static PyObject *
b_get(void *ptr, Py_ssize_t size)
{
- signed char val = *(signed char *)ptr;
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ signed char val = *(signed char *)ptr;
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
B_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- if (get_ulong(value, &val) < 0)
- return NULL;
- *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr,
- (unsigned short)val, size);
- _RET(value);
+ unsigned long val;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr,
+ (unsigned short)val, size);
+ _RET(value);
}
static PyObject *
B_get(void *ptr, Py_ssize_t size)
{
- unsigned char val = *(unsigned char *)ptr;
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ unsigned char val = *(unsigned char *)ptr;
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
h_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- short x;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (short)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ long val;
+ short x;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (short)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
h_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- short field;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_2(field);
- field = SET(field, (short)val, size);
- field = SWAP_2(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ long val;
+ short field;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_2(field);
+ field = SET(field, (short)val, size);
+ field = SWAP_2(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
h_get(void *ptr, Py_ssize_t size)
{
- short val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromLong((long)val);
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong((long)val);
}
static PyObject *
h_get_sw(void *ptr, Py_ssize_t size)
{
- short val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_2(val);
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
H_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned short x;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (unsigned short)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned long val;
+ unsigned short x;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (unsigned short)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
H_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned short field;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_2(field);
- field = SET(field, (unsigned short)val, size);
- field = SWAP_2(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned long val;
+ unsigned short field;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_2(field);
+ field = SET(field, (unsigned short)val, size);
+ field = SWAP_2(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
H_get(void *ptr, Py_ssize_t size)
{
- unsigned short val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
H_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned short val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_2(val);
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
i_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- int x;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (int)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ long val;
+ int x;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (int)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
i_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- int field;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_INT(field);
- field = SET(field, (int)val, size);
- field = SWAP_INT(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ long val;
+ int field;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_INT(field);
+ field = SET(field, (int)val, size);
+ field = SWAP_INT(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
i_get(void *ptr, Py_ssize_t size)
{
- int val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ int val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
i_get_sw(void *ptr, Py_ssize_t size)
{
- int val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_INT(val);
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ int val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_INT(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
#ifdef MS_WIN32
@@ -702,22 +702,22 @@ i_get_sw(void *ptr, Py_ssize_t size)
static PyObject *
vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- switch (PyObject_IsTrue(value)) {
- case -1:
- return NULL;
- case 0:
- *(short int *)ptr = VARIANT_FALSE;
- _RET(value);
- default:
- *(short int *)ptr = VARIANT_TRUE;
- _RET(value);
- }
+ switch (PyObject_IsTrue(value)) {
+ case -1:
+ return NULL;
+ case 0:
+ *(short int *)ptr = VARIANT_FALSE;
+ _RET(value);
+ default:
+ *(short int *)ptr = VARIANT_TRUE;
+ _RET(value);
+ }
}
static PyObject *
vBOOL_get(void *ptr, Py_ssize_t size)
{
- return PyBool_FromLong((long)*(short int *)ptr);
+ return PyBool_FromLong((long)*(short int *)ptr);
}
#endif
@@ -732,260 +732,260 @@ vBOOL_get(void *ptr, Py_ssize_t size)
static PyObject *
bool_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- switch (PyObject_IsTrue(value)) {
- case -1:
- return NULL;
- case 0:
- *(BOOL_TYPE *)ptr = 0;
- _RET(value);
- default:
- *(BOOL_TYPE *)ptr = 1;
- _RET(value);
- }
+ switch (PyObject_IsTrue(value)) {
+ case -1:
+ return NULL;
+ case 0:
+ *(BOOL_TYPE *)ptr = 0;
+ _RET(value);
+ default:
+ *(BOOL_TYPE *)ptr = 1;
+ _RET(value);
+ }
}
static PyObject *
bool_get(void *ptr, Py_ssize_t size)
{
- return PyBool_FromLong((long)*(BOOL_TYPE *)ptr);
+ return PyBool_FromLong((long)*(BOOL_TYPE *)ptr);
}
static PyObject *
I_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned int x;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (unsigned int)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned long val;
+ unsigned int x;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (unsigned int)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
I_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned int field;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = (unsigned int)SET(field, (unsigned int)val, size);
- field = SWAP_INT(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned long val;
+ unsigned int field;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = (unsigned int)SET(field, (unsigned int)val, size);
+ field = SWAP_INT(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
I_get(void *ptr, Py_ssize_t size)
{
- unsigned int val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned int val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
static PyObject *
I_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned int val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_INT(val);
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned int val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_INT(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
static PyObject *
l_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- long x;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ long val;
+ long x;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
l_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- long field;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_LONG(field);
- field = (long)SET(field, val, size);
- field = SWAP_LONG(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ long val;
+ long field;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_LONG(field);
+ field = (long)SET(field, val, size);
+ field = SWAP_LONG(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
l_get(void *ptr, Py_ssize_t size)
{
- long val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ long val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
l_get_sw(void *ptr, Py_ssize_t size)
{
- long val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_LONG(val);
- GET_BITFIELD(val, size);
- return PyLong_FromLong(val);
+ long val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_LONG(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromLong(val);
}
static PyObject *
L_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned long x;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned long val;
+ unsigned long x;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
L_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned long field;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_LONG(field);
- field = (unsigned long)SET(field, val, size);
- field = SWAP_LONG(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned long val;
+ unsigned long field;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_LONG(field);
+ field = (unsigned long)SET(field, val, size);
+ field = SWAP_LONG(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
L_get(void *ptr, Py_ssize_t size)
{
- unsigned long val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned long val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
static PyObject *
L_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned long val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_LONG(val);
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned long val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_LONG(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
#ifdef HAVE_LONG_LONG
static PyObject *
q_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- PY_LONG_LONG val;
- PY_LONG_LONG x;
- if (get_longlong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ PY_LONG_LONG val;
+ PY_LONG_LONG x;
+ if (get_longlong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- PY_LONG_LONG val;
- PY_LONG_LONG field;
- if (get_longlong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_8(field);
- field = (PY_LONG_LONG)SET(field, val, size);
- field = SWAP_8(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ PY_LONG_LONG val;
+ PY_LONG_LONG field;
+ if (get_longlong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_8(field);
+ field = (PY_LONG_LONG)SET(field, val, size);
+ field = SWAP_8(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
q_get(void *ptr, Py_ssize_t size)
{
- PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromLongLong(val);
+ PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromLongLong(val);
}
static PyObject *
q_get_sw(void *ptr, Py_ssize_t size)
{
- PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_8(val);
- GET_BITFIELD(val, size);
- return PyLong_FromLongLong(val);
+ PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_8(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromLongLong(val);
}
static PyObject *
Q_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- unsigned PY_LONG_LONG x;
- if (get_ulonglong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned PY_LONG_LONG val;
+ unsigned PY_LONG_LONG x;
+ if (get_ulonglong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- unsigned PY_LONG_LONG field;
- if (get_ulonglong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_8(field);
- field = (unsigned PY_LONG_LONG)SET(field, val, size);
- field = SWAP_8(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned PY_LONG_LONG val;
+ unsigned PY_LONG_LONG field;
+ if (get_ulonglong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_8(field);
+ field = (unsigned PY_LONG_LONG)SET(field, val, size);
+ field = SWAP_8(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
Q_get(void *ptr, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLongLong(val);
+ unsigned PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLongLong(val);
}
static PyObject *
Q_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_8(val);
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLongLong(val);
+ unsigned PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_8(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLongLong(val);
}
#endif
@@ -997,136 +997,136 @@ Q_get_sw(void *ptr, Py_ssize_t size)
static PyObject *
g_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long double x;
+ long double x;
- x = PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
- memcpy(ptr, &x, sizeof(long double));
- _RET(value);
+ x = PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+ memcpy(ptr, &x, sizeof(long double));
+ _RET(value);
}
static PyObject *
g_get(void *ptr, Py_ssize_t size)
{
- long double val;
- memcpy(&val, ptr, sizeof(long double));
- return PyFloat_FromDouble(val);
+ long double val;
+ memcpy(&val, ptr, sizeof(long double));
+ return PyFloat_FromDouble(val);
}
static PyObject *
d_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- double x;
+ double x;
- x = PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
- memcpy(ptr, &x, sizeof(double));
- _RET(value);
+ x = PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+ memcpy(ptr, &x, sizeof(double));
+ _RET(value);
}
static PyObject *
d_get(void *ptr, Py_ssize_t size)
{
- double val;
- memcpy(&val, ptr, sizeof(val));
- return PyFloat_FromDouble(val);
+ double val;
+ memcpy(&val, ptr, sizeof(val));
+ return PyFloat_FromDouble(val);
}
static PyObject *
d_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- double x;
+ double x;
- x = PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
+ x = PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
#ifdef WORDS_BIGENDIAN
- if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1))
- return NULL;
+ if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1))
+ return NULL;
#else
- if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0))
- return NULL;
+ if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0))
+ return NULL;
#endif
- _RET(value);
+ _RET(value);
}
static PyObject *
d_get_sw(void *ptr, Py_ssize_t size)
{
#ifdef WORDS_BIGENDIAN
- return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1));
+ return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1));
#else
- return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0));
+ return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0));
#endif
}
static PyObject *
f_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- float x;
+ float x;
- x = (float)PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ x = (float)PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
f_get(void *ptr, Py_ssize_t size)
{
- float val;
- memcpy(&val, ptr, sizeof(val));
- return PyFloat_FromDouble(val);
+ float val;
+ memcpy(&val, ptr, sizeof(val));
+ return PyFloat_FromDouble(val);
}
static PyObject *
f_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- float x;
+ float x;
- x = (float)PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
+ x = (float)PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
#ifdef WORDS_BIGENDIAN
- if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1))
- return NULL;
+ if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1))
+ return NULL;
#else
- if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0))
- return NULL;
+ if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0))
+ return NULL;
#endif
- _RET(value);
+ _RET(value);
}
static PyObject *
f_get_sw(void *ptr, Py_ssize_t size)
{
#ifdef WORDS_BIGENDIAN
- return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1));
+ return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1));
#else
- return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0));
+ return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0));
#endif
}
@@ -1143,72 +1143,72 @@ f_get_sw(void *ptr, Py_ssize_t size)
static PyObject *
O_get(void *ptr, Py_ssize_t size)
{
- PyObject *ob = *(PyObject **)ptr;
- if (ob == NULL) {
- if (!PyErr_Occurred())
- /* Set an error if not yet set */
- PyErr_SetString(PyExc_ValueError,
- "PyObject is NULL");
- return NULL;
- }
- Py_INCREF(ob);
- return ob;
+ PyObject *ob = *(PyObject **)ptr;
+ if (ob == NULL) {
+ if (!PyErr_Occurred())
+ /* Set an error if not yet set */
+ PyErr_SetString(PyExc_ValueError,
+ "PyObject is NULL");
+ return NULL;
+ }
+ Py_INCREF(ob);
+ return ob;
}
static PyObject *
O_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- /* Hm, does the memory block need it's own refcount or not? */
- *(PyObject **)ptr = value;
- Py_INCREF(value);
- return value;
+ /* Hm, does the memory block need it's own refcount or not? */
+ *(PyObject **)ptr = value;
+ Py_INCREF(value);
+ return value;
}
static PyObject *
c_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- if (PyUnicode_Check(value)) {
- value = PyUnicode_AsEncodedString(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (value == NULL)
- return NULL;
- if (PyBytes_GET_SIZE(value) != 1) {
- Py_DECREF(value);
- goto error;
- }
- *(char *)ptr = PyBytes_AS_STRING(value)[0];
- Py_DECREF(value);
- _RET(value);
- }
- if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) {
- *(char *)ptr = PyBytes_AS_STRING(value)[0];
- _RET(value);
- }
- if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) {
- *(char *)ptr = PyByteArray_AS_STRING(value)[0];
- _RET(value);
- }
- if (PyLong_Check(value))
- {
- long longval = PyLong_AS_LONG(value);
- if (longval < 0 || longval >= 256)
- goto error;
- *(char *)ptr = (char)longval;
- _RET(value);
- }
+ if (PyUnicode_Check(value)) {
+ value = PyUnicode_AsEncodedString(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (value == NULL)
+ return NULL;
+ if (PyBytes_GET_SIZE(value) != 1) {
+ Py_DECREF(value);
+ goto error;
+ }
+ *(char *)ptr = PyBytes_AS_STRING(value)[0];
+ Py_DECREF(value);
+ _RET(value);
+ }
+ if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) {
+ *(char *)ptr = PyBytes_AS_STRING(value)[0];
+ _RET(value);
+ }
+ if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) {
+ *(char *)ptr = PyByteArray_AS_STRING(value)[0];
+ _RET(value);
+ }
+ if (PyLong_Check(value))
+ {
+ long longval = PyLong_AS_LONG(value);
+ if (longval < 0 || longval >= 256)
+ goto error;
+ *(char *)ptr = (char)longval;
+ _RET(value);
+ }
error:
- PyErr_Format(PyExc_TypeError,
- "one character string expected");
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "one character string expected");
+ return NULL;
}
static PyObject *
c_get(void *ptr, Py_ssize_t size)
{
- return PyBytes_FromStringAndSize((char *)ptr, 1);
+ return PyBytes_FromStringAndSize((char *)ptr, 1);
}
#ifdef CTYPES_UNICODE
@@ -1216,107 +1216,107 @@ c_get(void *ptr, Py_ssize_t size)
static PyObject *
u_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- Py_ssize_t len;
- if (PyBytes_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- } else
- Py_INCREF(value);
+ Py_ssize_t len;
+ if (PyBytes_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ } else
+ Py_INCREF(value);
- len = PyUnicode_GET_SIZE(value);
- if (len != 1) {
- Py_DECREF(value);
- PyErr_SetString(PyExc_TypeError,
- "one character unicode string expected");
- return NULL;
- }
+ len = PyUnicode_GET_SIZE(value);
+ if (len != 1) {
+ Py_DECREF(value);
+ PyErr_SetString(PyExc_TypeError,
+ "one character unicode string expected");
+ return NULL;
+ }
- *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0];
- Py_DECREF(value);
+ *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0];
+ Py_DECREF(value);
- _RET(value);
+ _RET(value);
}
static PyObject *
u_get(void *ptr, Py_ssize_t size)
{
- return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
+ return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
}
/* U - a unicode string */
static PyObject *
U_get(void *ptr, Py_ssize_t size)
{
- PyObject *result;
- Py_ssize_t len;
- Py_UNICODE *p;
+ PyObject *result;
+ Py_ssize_t len;
+ Py_UNICODE *p;
- size /= sizeof(wchar_t); /* we count character units here, not bytes */
+ size /= sizeof(wchar_t); /* we count character units here, not bytes */
- result = PyUnicode_FromWideChar((wchar_t *)ptr, size);
- if (!result)
- return NULL;
- /* We need 'result' to be able to count the characters with wcslen,
- since ptr may not be NUL terminated. If the length is smaller (if
- it was actually NUL terminated, we construct a new one and throw
- away the result.
- */
- /* chop off at the first NUL character, if any. */
- p = PyUnicode_AS_UNICODE(result);
- for (len = 0; len < size; ++len)
- if (!p[len])
- break;
+ result = PyUnicode_FromWideChar((wchar_t *)ptr, size);
+ if (!result)
+ return NULL;
+ /* We need 'result' to be able to count the characters with wcslen,
+ since ptr may not be NUL terminated. If the length is smaller (if
+ it was actually NUL terminated, we construct a new one and throw
+ away the result.
+ */
+ /* chop off at the first NUL character, if any. */
+ p = PyUnicode_AS_UNICODE(result);
+ for (len = 0; len < size; ++len)
+ if (!p[len])
+ break;
- if (len < size) {
- PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len);
- Py_DECREF(result);
- return ob;
- }
- return result;
+ if (len < size) {
+ PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len);
+ Py_DECREF(result);
+ return ob;
+ }
+ return result;
}
static PyObject *
U_set(void *ptr, PyObject *value, Py_ssize_t length)
{
- Py_ssize_t size;
-
- /* It's easier to calculate in characters than in bytes */
- length /= sizeof(wchar_t);
-
- if (PyBytes_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- } else
- Py_INCREF(value);
- size = PyUnicode_GET_SIZE(value);
- if (size > length) {
- PyErr_Format(PyExc_ValueError,
- "string too long (%zd, maximum length %zd)",
- size, length);
- Py_DECREF(value);
- return NULL;
- } else if (size < length-1)
- /* copy terminating NUL character if there is space */
- size += 1;
- PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
- return value;
+ Py_ssize_t size;
+
+ /* It's easier to calculate in characters than in bytes */
+ length /= sizeof(wchar_t);
+
+ if (PyBytes_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ } else
+ Py_INCREF(value);
+ size = PyUnicode_GET_SIZE(value);
+ if (size > length) {
+ PyErr_Format(PyExc_ValueError,
+ "string too long (%zd, maximum length %zd)",
+ size, length);
+ Py_DECREF(value);
+ return NULL;
+ } else if (size < length-1)
+ /* copy terminating NUL character if there is space */
+ size += 1;
+ PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
+ return value;
}
#endif
@@ -1324,210 +1324,210 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
static PyObject *
s_get(void *ptr, Py_ssize_t size)
{
- Py_ssize_t i;
- char *p;
+ Py_ssize_t i;
+ char *p;
- p = (char *)ptr;
- for (i = 0; i < size; ++i) {
- if (*p++ == '\0')
- break;
- }
+ p = (char *)ptr;
+ for (i = 0; i < size; ++i) {
+ if (*p++ == '\0')
+ break;
+ }
- return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i);
+ return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i);
}
static PyObject *
s_set(void *ptr, PyObject *value, Py_ssize_t length)
{
- char *data;
- Py_ssize_t size;
-
- if (PyUnicode_Check(value)) {
- value = PyUnicode_AsEncodedString(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (value == NULL)
- return NULL;
- assert(PyBytes_Check(value));
- } else if(PyBytes_Check(value)) {
- Py_INCREF(value);
- } else {
- PyErr_Format(PyExc_TypeError,
- "expected string, %s found",
- value->ob_type->tp_name);
- return NULL;
- }
-
- data = PyBytes_AS_STRING(value);
- if (!data)
- return NULL;
- size = strlen(data); /* XXX Why not Py_SIZE(value)? */
- if (size < length) {
- /* This will copy the leading NUL character
- * if there is space for it.
- */
- ++size;
- } else if (size > length) {
- PyErr_Format(PyExc_ValueError,
- "string too long (%zd, maximum length %zd)",
- size, length);
- Py_DECREF(value);
- return NULL;
- }
- /* Also copy the terminating NUL character if there is space */
- memcpy((char *)ptr, data, size);
-
- Py_DECREF(value);
- _RET(value);
+ char *data;
+ Py_ssize_t size;
+
+ if (PyUnicode_Check(value)) {
+ value = PyUnicode_AsEncodedString(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (value == NULL)
+ return NULL;
+ assert(PyBytes_Check(value));
+ } else if(PyBytes_Check(value)) {
+ Py_INCREF(value);
+ } else {
+ PyErr_Format(PyExc_TypeError,
+ "expected string, %s found",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+
+ data = PyBytes_AS_STRING(value);
+ if (!data)
+ return NULL;
+ size = strlen(data); /* XXX Why not Py_SIZE(value)? */
+ if (size < length) {
+ /* This will copy the leading NUL character
+ * if there is space for it.
+ */
+ ++size;
+ } else if (size > length) {
+ PyErr_Format(PyExc_ValueError,
+ "string too long (%zd, maximum length %zd)",
+ size, length);
+ Py_DECREF(value);
+ return NULL;
+ }
+ /* Also copy the terminating NUL character if there is space */
+ memcpy((char *)ptr, data, size);
+
+ Py_DECREF(value);
+ _RET(value);
}
static PyObject *
z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- if (value == Py_None) {
- *(char **)ptr = NULL;
- Py_INCREF(value);
- return value;
- }
- if (PyBytes_Check(value)) {
- *(char **)ptr = PyBytes_AsString(value);
- Py_INCREF(value);
- return value;
- } else if (PyUnicode_Check(value)) {
- PyObject *str = PyUnicode_AsEncodedString(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (str == NULL)
- return NULL;
- *(char **)ptr = PyBytes_AS_STRING(str);
- return str;
- } else if (PyLong_Check(value)) {
+ if (value == Py_None) {
+ *(char **)ptr = NULL;
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyBytes_Check(value)) {
+ *(char **)ptr = PyBytes_AsString(value);
+ Py_INCREF(value);
+ return value;
+ } else if (PyUnicode_Check(value)) {
+ PyObject *str = PyUnicode_AsEncodedString(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (str == NULL)
+ return NULL;
+ *(char **)ptr = PyBytes_AS_STRING(str);
+ return str;
+ } else if (PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
- *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value);
+ *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value);
#else
- *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value);
+ *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value);
#endif
- _RET(value);
- }
- PyErr_Format(PyExc_TypeError,
- "string or integer address expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
+ _RET(value);
+ }
+ PyErr_Format(PyExc_TypeError,
+ "string or integer address expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
}
static PyObject *
z_get(void *ptr, Py_ssize_t size)
{
- /* XXX What about invalid pointers ??? */
- if (*(void **)ptr) {
+ /* XXX What about invalid pointers ??? */
+ if (*(void **)ptr) {
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
- if (IsBadStringPtrA(*(char **)ptr, -1)) {
- PyErr_Format(PyExc_ValueError,
- "invalid string pointer %p",
- *(char **)ptr);
- return NULL;
- }
+ if (IsBadStringPtrA(*(char **)ptr, -1)) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid string pointer %p",
+ *(char **)ptr);
+ return NULL;
+ }
#endif
- return PyBytes_FromStringAndSize(*(char **)ptr,
- strlen(*(char **)ptr));
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ return PyBytes_FromStringAndSize(*(char **)ptr,
+ strlen(*(char **)ptr));
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
#ifdef CTYPES_UNICODE
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- if (value == Py_None) {
- *(wchar_t **)ptr = NULL;
- Py_INCREF(value);
- return value;
- }
- if (PyLong_Check(value) || PyLong_Check(value)) {
+ if (value == Py_None) {
+ *(wchar_t **)ptr = NULL;
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyLong_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
- *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value);
+ *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value);
#else
- *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value);
+ *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value);
#endif
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyBytes_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string or integer address expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- } else
- Py_INCREF(value);
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyBytes_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string or integer address expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ } else
+ Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
- /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
- type. So we can copy directly. Hm, are unicode objects always NUL
- terminated in Python, internally?
- */
- *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
- return value;
+ /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
+ type. So we can copy directly. Hm, are unicode objects always NUL
+ terminated in Python, internally?
+ */
+ *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
+ return value;
#else
- {
- /* We must create a wchar_t* buffer from the unicode object,
- and keep it alive */
- PyObject *keep;
- wchar_t *buffer;
-
- int size = PyUnicode_GET_SIZE(value);
- size += 1; /* terminating NUL */
- size *= sizeof(wchar_t);
- buffer = (wchar_t *)PyMem_Malloc(size);
- if (!buffer) {
- Py_DECREF(value);
- return PyErr_NoMemory();
- }
- memset(buffer, 0, size);
- keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);
- if (!keep) {
- Py_DECREF(value);
- PyMem_Free(buffer);
- return NULL;
- }
- *(wchar_t **)ptr = (wchar_t *)buffer;
- if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
- buffer, PyUnicode_GET_SIZE(value))) {
- Py_DECREF(value);
- Py_DECREF(keep);
- return NULL;
- }
- Py_DECREF(value);
- return keep;
- }
+ {
+ /* We must create a wchar_t* buffer from the unicode object,
+ and keep it alive */
+ PyObject *keep;
+ wchar_t *buffer;
+
+ int size = PyUnicode_GET_SIZE(value);
+ size += 1; /* terminating NUL */
+ size *= sizeof(wchar_t);
+ buffer = (wchar_t *)PyMem_Malloc(size);
+ if (!buffer) {
+ Py_DECREF(value);
+ return PyErr_NoMemory();
+ }
+ memset(buffer, 0, size);
+ keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);
+ if (!keep) {
+ Py_DECREF(value);
+ PyMem_Free(buffer);
+ return NULL;
+ }
+ *(wchar_t **)ptr = (wchar_t *)buffer;
+ if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
+ buffer, PyUnicode_GET_SIZE(value))) {
+ Py_DECREF(value);
+ Py_DECREF(keep);
+ return NULL;
+ }
+ Py_DECREF(value);
+ return keep;
+ }
#endif
}
static PyObject *
Z_get(void *ptr, Py_ssize_t size)
{
- wchar_t *p;
- p = *(wchar_t **)ptr;
- if (p) {
+ wchar_t *p;
+ p = *(wchar_t **)ptr;
+ if (p) {
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
- if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) {
- PyErr_Format(PyExc_ValueError,
- "invalid string pointer %p",
- *(wchar_t **)ptr);
- return NULL;
- }
+ if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid string pointer %p",
+ *(wchar_t **)ptr);
+ return NULL;
+ }
#endif
- return PyUnicode_FromWideChar(p, wcslen(p));
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ return PyUnicode_FromWideChar(p, wcslen(p));
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
#endif
@@ -1535,166 +1535,166 @@ Z_get(void *ptr, Py_ssize_t size)
static PyObject *
BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- BSTR bstr;
-
- /* convert value into a PyUnicodeObject or NULL */
- if (Py_None == value) {
- value = NULL;
- } else if (PyBytes_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (PyUnicode_Check(value)) {
- Py_INCREF(value); /* for the descref below */
- } else {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
-
- /* create a BSTR from value */
- if (value) {
- Py_ssize_t size = PyUnicode_GET_SIZE(value);
- if ((unsigned) size != size) {
- PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
- return NULL;
- }
- bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
- (unsigned)size);
- Py_DECREF(value);
- } else
- bstr = NULL;
-
- /* free the previous contents, if any */
- if (*(BSTR *)ptr)
- SysFreeString(*(BSTR *)ptr);
-
- /* and store it */
- *(BSTR *)ptr = bstr;
-
- /* We don't need to keep any other object */
- _RET(value);
+ BSTR bstr;
+
+ /* convert value into a PyUnicodeObject or NULL */
+ if (Py_None == value) {
+ value = NULL;
+ } else if (PyBytes_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (PyUnicode_Check(value)) {
+ Py_INCREF(value); /* for the descref below */
+ } else {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+
+ /* create a BSTR from value */
+ if (value) {
+ Py_ssize_t size = PyUnicode_GET_SIZE(value);
+ if ((unsigned) size != size) {
+ PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
+ return NULL;
+ }
+ bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
+ (unsigned)size);
+ Py_DECREF(value);
+ } else
+ bstr = NULL;
+
+ /* free the previous contents, if any */
+ if (*(BSTR *)ptr)
+ SysFreeString(*(BSTR *)ptr);
+
+ /* and store it */
+ *(BSTR *)ptr = bstr;
+
+ /* We don't need to keep any other object */
+ _RET(value);
}
static PyObject *
BSTR_get(void *ptr, Py_ssize_t size)
{
- BSTR p;
- p = *(BSTR *)ptr;
- if (p)
- return PyUnicode_FromWideChar(p, SysStringLen(p));
- else {
- /* Hm, it seems NULL pointer and zero length string are the
- same in BSTR, see Don Box, p 81
- */
- Py_INCREF(Py_None);
- return Py_None;
- }
+ BSTR p;
+ p = *(BSTR *)ptr;
+ if (p)
+ return PyUnicode_FromWideChar(p, SysStringLen(p));
+ else {
+ /* Hm, it seems NULL pointer and zero length string are the
+ same in BSTR, see Don Box, p 81
+ */
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
#endif
static PyObject *
P_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- void *v;
- if (value == Py_None) {
- *(void **)ptr = NULL;
- _RET(value);
- }
+ void *v;
+ if (value == Py_None) {
+ *(void **)ptr = NULL;
+ _RET(value);
+ }
- if (!PyLong_Check(value) && !PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "cannot be converted to pointer");
- return NULL;
- }
+ if (!PyLong_Check(value) && !PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot be converted to pointer");
+ return NULL;
+ }
#if SIZEOF_VOID_P <= SIZEOF_LONG
- v = (void *)PyLong_AsUnsignedLongMask(value);
+ v = (void *)PyLong_AsUnsignedLongMask(value);
#else
#ifndef HAVE_LONG_LONG
# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
#elif SIZEOF_LONG_LONG < SIZEOF_VOID_P
# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
#endif
- v = (void *)PyLong_AsUnsignedLongLongMask(value);
+ v = (void *)PyLong_AsUnsignedLongLongMask(value);
#endif
- if (PyErr_Occurred())
- return NULL;
+ if (PyErr_Occurred())
+ return NULL;
- *(void **)ptr = v;
- _RET(value);
+ *(void **)ptr = v;
+ _RET(value);
}
static PyObject *
P_get(void *ptr, Py_ssize_t size)
{
- if (*(void **)ptr == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyLong_FromVoidPtr(*(void **)ptr);
+ if (*(void **)ptr == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyLong_FromVoidPtr(*(void **)ptr);
}
static struct fielddesc formattable[] = {
- { 's', s_set, s_get, &ffi_type_pointer},
- { 'b', b_set, b_get, &ffi_type_schar},
- { 'B', B_set, B_get, &ffi_type_uchar},
- { 'c', c_set, c_get, &ffi_type_schar},
- { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw},
- { 'g', g_set, g_get, &ffi_type_longdouble},
- { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw},
- { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw},
- { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw},
- { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw},
- { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw},
+ { 's', s_set, s_get, &ffi_type_pointer},
+ { 'b', b_set, b_get, &ffi_type_schar},
+ { 'B', B_set, B_get, &ffi_type_uchar},
+ { 'c', c_set, c_get, &ffi_type_schar},
+ { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw},
+ { 'g', g_set, g_get, &ffi_type_longdouble},
+ { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw},
+ { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw},
+ { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw},
+ { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw},
+ { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw},
/* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */
/* As soon as we can get rid of the type codes, this is no longer a problem */
#if SIZEOF_LONG == 4
- { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw},
- { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw},
+ { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw},
+ { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw},
#elif SIZEOF_LONG == 8
- { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw},
- { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw},
+ { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw},
+ { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw},
#else
# error
#endif
#ifdef HAVE_LONG_LONG
#if SIZEOF_LONG_LONG == 8
- { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw},
- { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw},
+ { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw},
+ { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw},
#else
# error
#endif
#endif
- { 'P', P_set, P_get, &ffi_type_pointer},
- { 'z', z_set, z_get, &ffi_type_pointer},
+ { 'P', P_set, P_get, &ffi_type_pointer},
+ { 'z', z_set, z_get, &ffi_type_pointer},
#ifdef CTYPES_UNICODE
- { 'u', u_set, u_get, NULL}, /* ffi_type set later */
- { 'U', U_set, U_get, &ffi_type_pointer},
- { 'Z', Z_set, Z_get, &ffi_type_pointer},
+ { 'u', u_set, u_get, NULL}, /* ffi_type set later */
+ { 'U', U_set, U_get, &ffi_type_pointer},
+ { 'Z', Z_set, Z_get, &ffi_type_pointer},
#endif
#ifdef MS_WIN32
- { 'X', BSTR_set, BSTR_get, &ffi_type_pointer},
- { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort},
+ { 'X', BSTR_set, BSTR_get, &ffi_type_pointer},
+ { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort},
#endif
#if SIZEOF__BOOL == 1
- { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */
+ { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */
#elif SIZEOF__BOOL == SIZEOF_SHORT
- { '?', bool_set, bool_get, &ffi_type_ushort},
+ { '?', bool_set, bool_get, &ffi_type_ushort},
#elif SIZEOF__BOOL == SIZEOF_INT
- { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw},
+ { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw},
#elif SIZEOF__BOOL == SIZEOF_LONG
- { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw},
+ { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw},
#elif SIZEOF__BOOL == SIZEOF_LONG_LONG
- { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw},
+ { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw},
#endif /* SIZEOF__BOOL */
- { 'O', O_set, O_get, &ffi_type_pointer},
- { 0, NULL, NULL, NULL},
+ { 'O', O_set, O_get, &ffi_type_pointer},
+ { 0, NULL, NULL, NULL},
};
/*
@@ -1705,26 +1705,26 @@ static struct fielddesc formattable[] = {
struct fielddesc *
_ctypes_get_fielddesc(const char *fmt)
{
- static int initialized = 0;
- struct fielddesc *table = formattable;
+ static int initialized = 0;
+ struct fielddesc *table = formattable;
- if (!initialized) {
- initialized = 1;
+ if (!initialized) {
+ initialized = 1;
#ifdef CTYPES_UNICODE
- if (sizeof(wchar_t) == sizeof(short))
- _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort;
- else if (sizeof(wchar_t) == sizeof(int))
- _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint;
- else if (sizeof(wchar_t) == sizeof(long))
- _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong;
+ if (sizeof(wchar_t) == sizeof(short))
+ _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort;
+ else if (sizeof(wchar_t) == sizeof(int))
+ _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint;
+ else if (sizeof(wchar_t) == sizeof(long))
+ _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong;
#endif
- }
+ }
- for (; table->code; ++table) {
- if (table->code == fmt[0])
- return table;
- }
- return NULL;
+ for (; table->code; ++table) {
+ if (table->code == fmt[0])
+ return table;
+ }
+ return NULL;
}
typedef struct { char c; char x; } s_char;
@@ -1768,10 +1768,10 @@ typedef struct { char c; PY_LONG_LONG x; } s_long_long;
/* from ffi.h:
typedef struct _ffi_type
{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
} ffi_type;
*/
@@ -1798,7 +1798,7 @@ ffi_type ffi_type_double = { sizeof(double), DOUBLE_ALIGN, FFI_TYPE_DOUBLE };
#endif
/* This is already defined on OSX */
ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN,
- FFI_TYPE_LONGDOUBLE };
+ FFI_TYPE_LONGDOUBLE };
ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER };
diff --git a/Modules/_ctypes/ctypes.h b/Modules/_ctypes/ctypes.h
index b4047a4..e0bad07 100644
--- a/Modules/_ctypes/ctypes.h
+++ b/Modules/_ctypes/ctypes.h
@@ -21,16 +21,16 @@ Making CDataObject a variable size object would be a better solution, but more
difficult in the presence of PyCFuncPtrObject. Maybe later.
*/
union value {
- char c[16];
- short s;
- int i;
- long l;
- float f;
- double d;
+ char c[16];
+ short s;
+ int i;
+ long l;
+ float f;
+ double d;
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG ll;
+ PY_LONG_LONG ll;
#endif
- long double D;
+ long double D;
};
/*
@@ -40,67 +40,67 @@ union value {
*/
struct tagCDataObject {
- PyObject_HEAD
- char *b_ptr; /* pointer to memory block */
- int b_needsfree; /* need _we_ free the memory? */
- CDataObject *b_base; /* pointer to base object or NULL */
- Py_ssize_t b_size; /* size of memory block in bytes */
- Py_ssize_t b_length; /* number of references we need */
- Py_ssize_t b_index; /* index of this object into base's
- b_object list */
- PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */
- union value b_value;
+ PyObject_HEAD
+ char *b_ptr; /* pointer to memory block */
+ int b_needsfree; /* need _we_ free the memory? */
+ CDataObject *b_base; /* pointer to base object or NULL */
+ Py_ssize_t b_size; /* size of memory block in bytes */
+ Py_ssize_t b_length; /* number of references we need */
+ Py_ssize_t b_index; /* index of this object into base's
+ b_object list */
+ PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */
+ union value b_value;
};
typedef struct {
- PyObject_VAR_HEAD
- ffi_closure *pcl; /* the C callable */
- ffi_cif cif;
- int flags;
- PyObject *converters;
- PyObject *callable;
- PyObject *restype;
- SETFUNC setfunc;
- ffi_type *ffi_restype;
- ffi_type *atypes[1];
+ PyObject_VAR_HEAD
+ ffi_closure *pcl; /* the C callable */
+ ffi_cif cif;
+ int flags;
+ PyObject *converters;
+ PyObject *callable;
+ PyObject *restype;
+ SETFUNC setfunc;
+ ffi_type *ffi_restype;
+ ffi_type *atypes[1];
} CThunkObject;
extern PyTypeObject PyCThunk_Type;
-#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type)
+#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type)
typedef struct {
- /* First part identical to tagCDataObject */
- PyObject_HEAD
- char *b_ptr; /* pointer to memory block */
- int b_needsfree; /* need _we_ free the memory? */
- CDataObject *b_base; /* pointer to base object or NULL */
- Py_ssize_t b_size; /* size of memory block in bytes */
- Py_ssize_t b_length; /* number of references we need */
- Py_ssize_t b_index; /* index of this object into base's
- b_object list */
- PyObject *b_objects; /* list of references we need to keep */
- union value b_value;
- /* end of tagCDataObject, additional fields follow */
-
- CThunkObject *thunk;
- PyObject *callable;
-
- /* These two fields will override the ones in the type's stgdict if
- they are set */
- PyObject *converters;
- PyObject *argtypes;
- PyObject *restype;
- PyObject *checker;
- PyObject *errcheck;
+ /* First part identical to tagCDataObject */
+ PyObject_HEAD
+ char *b_ptr; /* pointer to memory block */
+ int b_needsfree; /* need _we_ free the memory? */
+ CDataObject *b_base; /* pointer to base object or NULL */
+ Py_ssize_t b_size; /* size of memory block in bytes */
+ Py_ssize_t b_length; /* number of references we need */
+ Py_ssize_t b_index; /* index of this object into base's
+ b_object list */
+ PyObject *b_objects; /* list of references we need to keep */
+ union value b_value;
+ /* end of tagCDataObject, additional fields follow */
+
+ CThunkObject *thunk;
+ PyObject *callable;
+
+ /* These two fields will override the ones in the type's stgdict if
+ they are set */
+ PyObject *converters;
+ PyObject *argtypes;
+ PyObject *restype;
+ PyObject *checker;
+ PyObject *errcheck;
#ifdef MS_WIN32
- int index;
- GUID *iid;
+ int index;
+ GUID *iid;
#endif
- PyObject *paramflags;
+ PyObject *paramflags;
} PyCFuncPtrObject;
extern PyTypeObject PyCStgDict_Type;
-#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type)
-#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type)
+#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type)
+#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type)
extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct);
extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength);
@@ -109,12 +109,12 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig
extern PyTypeObject PyCData_Type;
-#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type)
-#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type)
+#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type)
+#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type)
extern PyTypeObject PyCSimpleType_Type;
-#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type)
-#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type)
+#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type)
+#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type)
extern PyTypeObject PyCField_Type;
extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt);
@@ -122,9 +122,9 @@ extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt);
extern PyObject *
PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
- Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
- Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
- int pack, int is_big_endian);
+ Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
+ Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
+ int pack, int is_big_endian);
extern PyObject *PyCData_AtAddress(PyObject *type, void *buf);
extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length);
@@ -137,13 +137,13 @@ extern PyTypeObject PyCFuncPtr_Type;
extern PyTypeObject PyCFuncPtrType_Type;
extern PyTypeObject PyCStructType_Type;
-#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type)
-#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type)
-#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type)
-#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type)
-#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type)
-#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type)
-#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type)
+#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type)
+#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type)
+#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type)
+#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type)
+#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type)
+#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type)
+#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type)
extern PyObject *
PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length);
@@ -151,35 +151,35 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length);
extern PyMethodDef _ctypes_module_methods[];
extern CThunkObject *_ctypes_alloc_callback(PyObject *callable,
- PyObject *converters,
- PyObject *restype,
- int flags);
+ PyObject *converters,
+ PyObject *restype,
+ int flags);
/* a table entry describing a predefined ctypes type */
struct fielddesc {
- char code;
- SETFUNC setfunc;
- GETFUNC getfunc;
- ffi_type *pffi_type; /* always statically allocated */
- SETFUNC setfunc_swapped;
- GETFUNC getfunc_swapped;
+ char code;
+ SETFUNC setfunc;
+ GETFUNC getfunc;
+ ffi_type *pffi_type; /* always statically allocated */
+ SETFUNC setfunc_swapped;
+ GETFUNC getfunc_swapped;
};
typedef struct {
- PyObject_HEAD
- Py_ssize_t offset;
- Py_ssize_t size;
- Py_ssize_t index; /* Index into CDataObject's
- object array */
- PyObject *proto; /* a type or NULL */
- GETFUNC getfunc; /* getter function if proto is NULL */
- SETFUNC setfunc; /* setter function if proto is NULL */
- int anonymous;
+ PyObject_HEAD
+ Py_ssize_t offset;
+ Py_ssize_t size;
+ Py_ssize_t index; /* Index into CDataObject's
+ object array */
+ PyObject *proto; /* a type or NULL */
+ GETFUNC getfunc; /* getter function if proto is NULL */
+ SETFUNC setfunc; /* setter function if proto is NULL */
+ int anonymous;
} CFieldObject;
/* A subclass of PyDictObject, used as the instance dictionary of ctypes
metatypes */
typedef struct {
- PyDictObject dict; /* first part identical to PyDictObject */
+ PyDictObject dict; /* first part identical to PyDictObject */
/* The size and align fields are unneeded, they are in ffi_type as well. As
an experiment shows, it's trivial to get rid of them, the only thing to
remember is that in PyCArrayType_new the ffi_type fields must be filled in -
@@ -188,28 +188,28 @@ typedef struct {
too much risk to change that now, and there are other fields which doen't
belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?)
*/
- Py_ssize_t size; /* number of bytes */
- Py_ssize_t align; /* alignment requirements */
- Py_ssize_t length; /* number of fields */
- ffi_type ffi_type_pointer;
- PyObject *proto; /* Only for Pointer/ArrayObject */
- SETFUNC setfunc; /* Only for simple objects */
- GETFUNC getfunc; /* Only for simple objects */
- PARAMFUNC paramfunc;
-
- /* Following fields only used by PyCFuncPtrType_Type instances */
- PyObject *argtypes; /* tuple of CDataObjects */
- PyObject *converters; /* tuple([t.from_param for t in argtypes]) */
- PyObject *restype; /* CDataObject or NULL */
- PyObject *checker;
- int flags; /* calling convention and such */
-
- /* pep3118 fields, pointers neeed PyMem_Free */
- char *format;
- int ndim;
- Py_ssize_t *shape;
-/* Py_ssize_t *strides; */ /* unused in ctypes */
-/* Py_ssize_t *suboffsets; */ /* unused in ctypes */
+ Py_ssize_t size; /* number of bytes */
+ Py_ssize_t align; /* alignment requirements */
+ Py_ssize_t length; /* number of fields */
+ ffi_type ffi_type_pointer;
+ PyObject *proto; /* Only for Pointer/ArrayObject */
+ SETFUNC setfunc; /* Only for simple objects */
+ GETFUNC getfunc; /* Only for simple objects */
+ PARAMFUNC paramfunc;
+
+ /* Following fields only used by PyCFuncPtrType_Type instances */
+ PyObject *argtypes; /* tuple of CDataObjects */
+ PyObject *converters; /* tuple([t.from_param for t in argtypes]) */
+ PyObject *restype; /* CDataObject or NULL */
+ PyObject *checker;
+ int flags; /* calling convention and such */
+
+ /* pep3118 fields, pointers neeed PyMem_Free */
+ char *format;
+ int ndim;
+ Py_ssize_t *shape;
+/* Py_ssize_t *strides; */ /* unused in ctypes */
+/* Py_ssize_t *suboffsets; */ /* unused in ctypes */
} StgDictObject;
@@ -264,16 +264,16 @@ extern int PyCStgDict_clone(StgDictObject *src, StgDictObject *dst);
typedef int(* PPROC)(void);
PyObject *_ctypes_callproc(PPROC pProc,
- PyObject *arguments,
+ PyObject *arguments,
#ifdef MS_WIN32
- IUnknown *pIUnk,
- GUID *iid,
+ IUnknown *pIUnk,
+ GUID *iid,
#endif
- int flags,
- PyObject *argtypes,
- PyObject *restype,
- PyObject *checker);
-
+ int flags,
+ PyObject *argtypes,
+ PyObject *restype,
+ PyObject *checker);
+
#define FUNCFLAG_STDCALL 0x0
#define FUNCFLAG_CDECL 0x1
@@ -288,45 +288,45 @@ PyObject *_ctypes_callproc(PPROC pProc,
#define DICTFLAG_FINAL 0x1000
struct tagPyCArgObject {
- PyObject_HEAD
- ffi_type *pffi_type;
- char tag;
- union {
- char c;
- char b;
- short h;
- int i;
- long l;
+ PyObject_HEAD
+ ffi_type *pffi_type;
+ char tag;
+ union {
+ char c;
+ char b;
+ short h;
+ int i;
+ long l;
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG q;
+ PY_LONG_LONG q;
#endif
- long double D;
- double d;
- float f;
- void *p;
- } value;
- PyObject *obj;
- Py_ssize_t size; /* for the 'V' tag */
+ long double D;
+ double d;
+ float f;
+ void *p;
+ } value;
+ PyObject *obj;
+ Py_ssize_t size; /* for the 'V' tag */
};
extern PyTypeObject PyCArg_Type;
-#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type)
+#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type)
extern PyCArgObject *PyCArgObject_new(void);
extern PyObject *
PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
- Py_ssize_t index, Py_ssize_t size, char *ptr);
+ Py_ssize_t index, Py_ssize_t size, char *ptr);
extern int
PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- Py_ssize_t index, Py_ssize_t size, char *ptr);
+ Py_ssize_t index, Py_ssize_t size, char *ptr);
extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...);
struct basespec {
- CDataObject *base;
- Py_ssize_t index;
- char *adr;
+ CDataObject *base;
+ Py_ssize_t index;
+ char *adr;
};
extern char basespec_string[];
diff --git a/Modules/_ctypes/darwin/dlfcn_simple.c b/Modules/_ctypes/darwin/dlfcn_simple.c
index 4b55323..2b293bb 100644
--- a/Modules/_ctypes/darwin/dlfcn_simple.c
+++ b/Modules/_ctypes/darwin/dlfcn_simple.c
@@ -81,167 +81,167 @@ static const char *error(int setget, const char *str, ...);
/* Set and get the error string for use by dlerror */
static const char *error(int setget, const char *str, ...)
{
- static char errstr[ERR_STR_LEN];
- static int err_filled = 0;
- const char *retval;
- va_list arg;
- if (setget == 0)
- {
- va_start(arg, str);
- strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
- vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg);
- va_end(arg);
- err_filled = 1;
- retval = NULL;
- }
- else
- {
- if (!err_filled)
- retval = NULL;
- else
- retval = errstr;
- err_filled = 0;
- }
- return retval;
+ static char errstr[ERR_STR_LEN];
+ static int err_filled = 0;
+ const char *retval;
+ va_list arg;
+ if (setget == 0)
+ {
+ va_start(arg, str);
+ strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
+ vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg);
+ va_end(arg);
+ err_filled = 1;
+ retval = NULL;
+ }
+ else
+ {
+ if (!err_filled)
+ retval = NULL;
+ else
+ retval = errstr;
+ err_filled = 0;
+ }
+ return retval;
}
/* darwin_dlopen */
static void *darwin_dlopen(const char *path, int mode)
{
- void *module = 0;
- NSObjectFileImage ofi = 0;
- NSObjectFileImageReturnCode ofirc;
+ void *module = 0;
+ NSObjectFileImage ofi = 0;
+ NSObjectFileImageReturnCode ofirc;
- /* If we got no path, the app wants the global namespace, use -1 as the marker
- in this case */
- if (!path)
- return (void *)-1;
+ /* If we got no path, the app wants the global namespace, use -1 as the marker
+ in this case */
+ if (!path)
+ return (void *)-1;
- /* Create the object file image, works for things linked with the -bundle arg to ld */
- ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
- switch (ofirc)
- {
- case NSObjectFileImageSuccess:
- /* It was okay, so use NSLinkModule to link in the image */
- module = NSLinkModule(ofi, path,
- NSLINKMODULE_OPTION_RETURN_ON_ERROR
- | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE
- | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW);
- NSDestroyObjectFileImage(ofi);
- break;
- case NSObjectFileImageInappropriateFile:
- /* It may have been a dynamic library rather than a bundle, try to load it */
- module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
- break;
- default:
- /* God knows what we got */
- error(0, "Can not open \"%s\"", path);
- return 0;
- }
- if (!module)
- error(0, "Can not open \"%s\"", path);
- return module;
+ /* Create the object file image, works for things linked with the -bundle arg to ld */
+ ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
+ switch (ofirc)
+ {
+ case NSObjectFileImageSuccess:
+ /* It was okay, so use NSLinkModule to link in the image */
+ module = NSLinkModule(ofi, path,
+ NSLINKMODULE_OPTION_RETURN_ON_ERROR
+ | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE
+ | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW);
+ NSDestroyObjectFileImage(ofi);
+ break;
+ case NSObjectFileImageInappropriateFile:
+ /* It may have been a dynamic library rather than a bundle, try to load it */
+ module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
+ break;
+ default:
+ /* God knows what we got */
+ error(0, "Can not open \"%s\"", path);
+ return 0;
+ }
+ if (!module)
+ error(0, "Can not open \"%s\"", path);
+ return module;
}
/* dlsymIntern is used by dlsym to find the symbol */
static void *dlsymIntern(void *handle, const char *symbol)
{
- NSSymbol nssym = 0;
- /* If the handle is -1, if is the app global context */
- if (handle == (void *)-1)
- {
- /* Global context, use NSLookupAndBindSymbol */
- if (NSIsSymbolNameDefined(symbol))
- {
- nssym = NSLookupAndBindSymbol(symbol);
- }
+ NSSymbol nssym = 0;
+ /* If the handle is -1, if is the app global context */
+ if (handle == (void *)-1)
+ {
+ /* Global context, use NSLookupAndBindSymbol */
+ if (NSIsSymbolNameDefined(symbol))
+ {
+ nssym = NSLookupAndBindSymbol(symbol);
+ }
- }
- /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image
- for libraries, and NSLookupSymbolInModule for bundles */
- else
- {
- /* Check for both possible magic numbers depending on x86/ppc byte order */
- if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
- (((struct mach_header *)handle)->magic == MH_CIGAM))
- {
- if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol))
- {
- nssym = NSLookupSymbolInImage((struct mach_header *)handle,
- symbol,
- NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
- | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
- }
+ }
+ /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image
+ for libraries, and NSLookupSymbolInModule for bundles */
+ else
+ {
+ /* Check for both possible magic numbers depending on x86/ppc byte order */
+ if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
+ (((struct mach_header *)handle)->magic == MH_CIGAM))
+ {
+ if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol))
+ {
+ nssym = NSLookupSymbolInImage((struct mach_header *)handle,
+ symbol,
+ NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
+ | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+ }
- }
- else
- {
- nssym = NSLookupSymbolInModule(handle, symbol);
- }
- }
- if (!nssym)
- {
- error(0, "Symbol \"%s\" Not found", symbol);
- return NULL;
- }
- return NSAddressOfSymbol(nssym);
+ }
+ else
+ {
+ nssym = NSLookupSymbolInModule(handle, symbol);
+ }
+ }
+ if (!nssym)
+ {
+ error(0, "Symbol \"%s\" Not found", symbol);
+ return NULL;
+ }
+ return NSAddressOfSymbol(nssym);
}
static const char *darwin_dlerror(void)
{
- return error(1, (char *)NULL);
+ return error(1, (char *)NULL);
}
static int darwin_dlclose(void *handle)
{
- if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
- (((struct mach_header *)handle)->magic == MH_CIGAM))
- {
- error(0, "Can't remove dynamic libraries on darwin");
- return 0;
- }
- if (!NSUnLinkModule(handle, 0))
- {
- error(0, "unable to unlink module %s", NSNameOfModule(handle));
- return 1;
- }
- return 0;
+ if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
+ (((struct mach_header *)handle)->magic == MH_CIGAM))
+ {
+ error(0, "Can't remove dynamic libraries on darwin");
+ return 0;
+ }
+ if (!NSUnLinkModule(handle, 0))
+ {
+ error(0, "unable to unlink module %s", NSNameOfModule(handle));
+ return 1;
+ }
+ return 0;
}
/* dlsym, prepend the underscore and call dlsymIntern */
static void *darwin_dlsym(void *handle, const char *symbol)
{
- static char undersym[257]; /* Saves calls to malloc(3) */
- int sym_len = strlen(symbol);
- void *value = NULL;
- char *malloc_sym = NULL;
+ static char undersym[257]; /* Saves calls to malloc(3) */
+ int sym_len = strlen(symbol);
+ void *value = NULL;
+ char *malloc_sym = NULL;
- if (sym_len < 256)
- {
- snprintf(undersym, 256, "_%s", symbol);
- value = dlsymIntern(handle, undersym);
- }
- else
- {
- malloc_sym = malloc(sym_len + 2);
- if (malloc_sym)
- {
- sprintf(malloc_sym, "_%s", symbol);
- value = dlsymIntern(handle, malloc_sym);
- free(malloc_sym);
- }
- else
- {
- error(0, "Unable to allocate memory");
- }
- }
- return value;
+ if (sym_len < 256)
+ {
+ snprintf(undersym, 256, "_%s", symbol);
+ value = dlsymIntern(handle, undersym);
+ }
+ else
+ {
+ malloc_sym = malloc(sym_len + 2);
+ if (malloc_sym)
+ {
+ sprintf(malloc_sym, "_%s", symbol);
+ value = dlsymIntern(handle, malloc_sym);
+ free(malloc_sym);
+ }
+ else
+ {
+ error(0, "Unable to allocate memory");
+ }
+ }
+ return value;
}
static int darwin_dladdr(const void *handle, Dl_info *info) {
- return 0;
+ return 0;
}
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
@@ -252,21 +252,21 @@ static void __attribute__ ((constructor)) ctypes_dlfcn_init(void);
static
#endif
void ctypes_dlfcn_init(void) {
- if (dlopen != NULL) {
- ctypes_dlsym = dlsym;
- ctypes_dlopen = dlopen;
- ctypes_dlerror = dlerror;
- ctypes_dlclose = dlclose;
- ctypes_dladdr = dladdr;
- } else {
+ if (dlopen != NULL) {
+ ctypes_dlsym = dlsym;
+ ctypes_dlopen = dlopen;
+ ctypes_dlerror = dlerror;
+ ctypes_dlclose = dlclose;
+ ctypes_dladdr = dladdr;
+ } else {
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
- ctypes_dlsym = darwin_dlsym;
- ctypes_dlopen = darwin_dlopen;
- ctypes_dlerror = darwin_dlerror;
- ctypes_dlclose = darwin_dlclose;
- ctypes_dladdr = darwin_dladdr;
+ ctypes_dlsym = darwin_dlsym;
+ ctypes_dlopen = darwin_dlopen;
+ ctypes_dlerror = darwin_dlerror;
+ ctypes_dlclose = darwin_dlclose;
+ ctypes_dladdr = darwin_dladdr;
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
- }
+ }
}
#endif /* CTYPES_DARWIN_DLFCN */
diff --git a/Modules/_ctypes/malloc_closure.c b/Modules/_ctypes/malloc_closure.c
index 9a5bfcf..ae857a2 100644
--- a/Modules/_ctypes/malloc_closure.c
+++ b/Modules/_ctypes/malloc_closure.c
@@ -23,8 +23,8 @@
/******************************************************************/
typedef union _tagITEM {
- ffi_closure closure;
- union _tagITEM *next;
+ ffi_closure closure;
+ union _tagITEM *next;
} ITEM;
static ITEM *free_list;
@@ -32,58 +32,58 @@ static int _pagesize;
static void more_core(void)
{
- ITEM *item;
- int count, i;
+ ITEM *item;
+ int count, i;
/* determine the pagesize */
#ifdef MS_WIN32
- if (!_pagesize) {
- SYSTEM_INFO systeminfo;
- GetSystemInfo(&systeminfo);
- _pagesize = systeminfo.dwPageSize;
- }
+ if (!_pagesize) {
+ SYSTEM_INFO systeminfo;
+ GetSystemInfo(&systeminfo);
+ _pagesize = systeminfo.dwPageSize;
+ }
#else
- if (!_pagesize) {
+ if (!_pagesize) {
#ifdef _SC_PAGESIZE
- _pagesize = sysconf(_SC_PAGESIZE);
+ _pagesize = sysconf(_SC_PAGESIZE);
#else
- _pagesize = getpagesize();
+ _pagesize = getpagesize();
#endif
- }
+ }
#endif
- /* calculate the number of nodes to allocate */
- count = BLOCKSIZE / sizeof(ITEM);
+ /* calculate the number of nodes to allocate */
+ count = BLOCKSIZE / sizeof(ITEM);
- /* allocate a memory block */
+ /* allocate a memory block */
#ifdef MS_WIN32
- item = (ITEM *)VirtualAlloc(NULL,
- count * sizeof(ITEM),
- MEM_COMMIT,
- PAGE_EXECUTE_READWRITE);
- if (item == NULL)
- return;
+ item = (ITEM *)VirtualAlloc(NULL,
+ count * sizeof(ITEM),
+ MEM_COMMIT,
+ PAGE_EXECUTE_READWRITE);
+ if (item == NULL)
+ return;
#else
- item = (ITEM *)mmap(NULL,
- count * sizeof(ITEM),
- PROT_READ | PROT_WRITE | PROT_EXEC,
- MAP_PRIVATE | MAP_ANONYMOUS,
- -1,
- 0);
- if (item == (void *)MAP_FAILED)
- return;
+ item = (ITEM *)mmap(NULL,
+ count * sizeof(ITEM),
+ PROT_READ | PROT_WRITE | PROT_EXEC,
+ MAP_PRIVATE | MAP_ANONYMOUS,
+ -1,
+ 0);
+ if (item == (void *)MAP_FAILED)
+ return;
#endif
#ifdef MALLOC_CLOSURE_DEBUG
- printf("block at %p allocated (%d bytes), %d ITEMs\n",
- item, count * sizeof(ITEM), count);
+ printf("block at %p allocated (%d bytes), %d ITEMs\n",
+ item, count * sizeof(ITEM), count);
#endif
- /* put them into the free list */
- for (i = 0; i < count; ++i) {
- item->next = free_list;
- free_list = item;
- ++item;
- }
+ /* put them into the free list */
+ for (i = 0; i < count; ++i) {
+ item->next = free_list;
+ free_list = item;
+ ++item;
+ }
}
/******************************************************************/
@@ -91,20 +91,20 @@ static void more_core(void)
/* put the item back into the free list */
void _ctypes_free_closure(void *p)
{
- ITEM *item = (ITEM *)p;
- item->next = free_list;
- free_list = item;
+ ITEM *item = (ITEM *)p;
+ item->next = free_list;
+ free_list = item;
}
/* return one item from the free list, allocating more if needed */
void *_ctypes_alloc_closure(void)
{
- ITEM *item;
- if (!free_list)
- more_core();
- if (!free_list)
- return NULL;
- item = free_list;
- free_list = item->next;
- return item;
+ ITEM *item;
+ if (!free_list)
+ more_core();
+ if (!free_list)
+ return NULL;
+ item = free_list;
+ free_list = item->next;
+ return item;
}
diff --git a/Modules/_ctypes/stgdict.c b/Modules/_ctypes/stgdict.c
index 6c81017..105e0df 100644
--- a/Modules/_ctypes/stgdict.c
+++ b/Modules/_ctypes/stgdict.c
@@ -19,143 +19,143 @@
static int
PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds)
{
- if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
- return -1;
- self->format = NULL;
- self->ndim = 0;
- self->shape = NULL;
- return 0;
+ if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
+ return -1;
+ self->format = NULL;
+ self->ndim = 0;
+ self->shape = NULL;
+ return 0;
}
static int
PyCStgDict_clear(StgDictObject *self)
{
- Py_CLEAR(self->proto);
- Py_CLEAR(self->argtypes);
- Py_CLEAR(self->converters);
- Py_CLEAR(self->restype);
- Py_CLEAR(self->checker);
- return 0;
+ Py_CLEAR(self->proto);
+ Py_CLEAR(self->argtypes);
+ Py_CLEAR(self->converters);
+ Py_CLEAR(self->restype);
+ Py_CLEAR(self->checker);
+ return 0;
}
static void
PyCStgDict_dealloc(StgDictObject *self)
{
- PyCStgDict_clear(self);
- PyMem_Free(self->format);
- PyMem_Free(self->shape);
- PyMem_Free(self->ffi_type_pointer.elements);
- PyDict_Type.tp_dealloc((PyObject *)self);
+ PyCStgDict_clear(self);
+ PyMem_Free(self->format);
+ PyMem_Free(self->shape);
+ PyMem_Free(self->ffi_type_pointer.elements);
+ PyDict_Type.tp_dealloc((PyObject *)self);
}
int
PyCStgDict_clone(StgDictObject *dst, StgDictObject *src)
{
- char *d, *s;
- Py_ssize_t size;
-
- PyCStgDict_clear(dst);
- PyMem_Free(dst->ffi_type_pointer.elements);
- PyMem_Free(dst->format);
- dst->format = NULL;
- PyMem_Free(dst->shape);
- dst->shape = NULL;
- dst->ffi_type_pointer.elements = NULL;
-
- d = (char *)dst;
- s = (char *)src;
- memcpy(d + sizeof(PyDictObject),
- s + sizeof(PyDictObject),
- sizeof(StgDictObject) - sizeof(PyDictObject));
-
- Py_XINCREF(dst->proto);
- Py_XINCREF(dst->argtypes);
- Py_XINCREF(dst->converters);
- Py_XINCREF(dst->restype);
- Py_XINCREF(dst->checker);
-
- if (src->format) {
- dst->format = PyMem_Malloc(strlen(src->format) + 1);
- if (dst->format == NULL)
- return -1;
- strcpy(dst->format, src->format);
- }
- if (src->shape) {
- dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
- if (dst->shape == NULL)
- return -1;
- memcpy(dst->shape, src->shape,
- sizeof(Py_ssize_t) * src->ndim);
- }
-
- if (src->ffi_type_pointer.elements == NULL)
- return 0;
- size = sizeof(ffi_type *) * (src->length + 1);
- dst->ffi_type_pointer.elements = PyMem_Malloc(size);
- if (dst->ffi_type_pointer.elements == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- memcpy(dst->ffi_type_pointer.elements,
- src->ffi_type_pointer.elements,
- size);
- return 0;
+ char *d, *s;
+ Py_ssize_t size;
+
+ PyCStgDict_clear(dst);
+ PyMem_Free(dst->ffi_type_pointer.elements);
+ PyMem_Free(dst->format);
+ dst->format = NULL;
+ PyMem_Free(dst->shape);
+ dst->shape = NULL;
+ dst->ffi_type_pointer.elements = NULL;
+
+ d = (char *)dst;
+ s = (char *)src;
+ memcpy(d + sizeof(PyDictObject),
+ s + sizeof(PyDictObject),
+ sizeof(StgDictObject) - sizeof(PyDictObject));
+
+ Py_XINCREF(dst->proto);
+ Py_XINCREF(dst->argtypes);
+ Py_XINCREF(dst->converters);
+ Py_XINCREF(dst->restype);
+ Py_XINCREF(dst->checker);
+
+ if (src->format) {
+ dst->format = PyMem_Malloc(strlen(src->format) + 1);
+ if (dst->format == NULL)
+ return -1;
+ strcpy(dst->format, src->format);
+ }
+ if (src->shape) {
+ dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
+ if (dst->shape == NULL)
+ return -1;
+ memcpy(dst->shape, src->shape,
+ sizeof(Py_ssize_t) * src->ndim);
+ }
+
+ if (src->ffi_type_pointer.elements == NULL)
+ return 0;
+ size = sizeof(ffi_type *) * (src->length + 1);
+ dst->ffi_type_pointer.elements = PyMem_Malloc(size);
+ if (dst->ffi_type_pointer.elements == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memcpy(dst->ffi_type_pointer.elements,
+ src->ffi_type_pointer.elements,
+ size);
+ return 0;
}
PyTypeObject PyCStgDict_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "StgDict",
- sizeof(StgDictObject),
- 0,
- (destructor)PyCStgDict_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)PyCStgDict_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "StgDict",
+ sizeof(StgDictObject),
+ 0,
+ (destructor)PyCStgDict_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)PyCStgDict_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
/* May return NULL, but does not set an exception! */
StgDictObject *
PyType_stgdict(PyObject *obj)
{
- PyTypeObject *type;
-
- if (!PyType_Check(obj))
- return NULL;
- type = (PyTypeObject *)obj;
- if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
- return NULL;
- return (StgDictObject *)type->tp_dict;
+ PyTypeObject *type;
+
+ if (!PyType_Check(obj))
+ return NULL;
+ type = (PyTypeObject *)obj;
+ if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
+ return NULL;
+ return (StgDictObject *)type->tp_dict;
}
/* May return NULL, but does not set an exception! */
@@ -166,10 +166,10 @@ PyType_stgdict(PyObject *obj)
StgDictObject *
PyObject_stgdict(PyObject *self)
{
- PyTypeObject *type = self->ob_type;
- if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
- return NULL;
- return (StgDictObject *)type->tp_dict;
+ PyTypeObject *type = self->ob_type;
+ if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
+ return NULL;
+ return (StgDictObject *)type->tp_dict;
}
/* descr is the descriptor for a field marked as anonymous. Get all the
@@ -178,78 +178,78 @@ PyObject_stgdict(PyObject *self)
*/
static int
MakeFields(PyObject *type, CFieldObject *descr,
- Py_ssize_t index, Py_ssize_t offset)
+ Py_ssize_t index, Py_ssize_t offset)
{
- Py_ssize_t i;
- PyObject *fields;
- PyObject *fieldlist;
-
- fields = PyObject_GetAttrString(descr->proto, "_fields_");
- if (fields == NULL)
- return -1;
- fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
- Py_DECREF(fields);
- if (fieldlist == NULL)
- return -1;
-
- for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
- PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
- PyObject *fname, *ftype, *bits;
- CFieldObject *fdescr;
- CFieldObject *new_descr;
- /* Convert to PyArg_UnpackTuple... */
- if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
- Py_DECREF(fieldlist);
- return -1;
- }
- fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
- if (fdescr == NULL) {
- Py_DECREF(fieldlist);
- return -1;
- }
- if (Py_TYPE(fdescr) != &PyCField_Type) {
- PyErr_SetString(PyExc_TypeError, "unexpected type");
- Py_DECREF(fdescr);
- Py_DECREF(fieldlist);
- return -1;
- }
- if (fdescr->anonymous) {
- int rc = MakeFields(type, fdescr,
- index + fdescr->index,
- offset + fdescr->offset);
- Py_DECREF(fdescr);
- if (rc == -1) {
- Py_DECREF(fieldlist);
- return -1;
- }
- continue;
- }
- new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL);
- if (new_descr == NULL) {
- Py_DECREF(fdescr);
- Py_DECREF(fieldlist);
- return -1;
- }
- assert(Py_TYPE(new_descr) == &PyCField_Type);
- new_descr->size = fdescr->size;
- new_descr->offset = fdescr->offset + offset;
- new_descr->index = fdescr->index + index;
- new_descr->proto = fdescr->proto;
- Py_XINCREF(new_descr->proto);
- new_descr->getfunc = fdescr->getfunc;
- new_descr->setfunc = fdescr->setfunc;
-
- Py_DECREF(fdescr);
-
- if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
- Py_DECREF(fieldlist);
- Py_DECREF(new_descr);
- return -1;
- }
- Py_DECREF(new_descr);
- }
- Py_DECREF(fieldlist);
- return 0;
+ Py_ssize_t i;
+ PyObject *fields;
+ PyObject *fieldlist;
+
+ fields = PyObject_GetAttrString(descr->proto, "_fields_");
+ if (fields == NULL)
+ return -1;
+ fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
+ Py_DECREF(fields);
+ if (fieldlist == NULL)
+ return -1;
+
+ for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
+ PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
+ PyObject *fname, *ftype, *bits;
+ CFieldObject *fdescr;
+ CFieldObject *new_descr;
+ /* Convert to PyArg_UnpackTuple... */
+ if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
+ Py_DECREF(fieldlist);
+ return -1;
+ }
+ fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
+ if (fdescr == NULL) {
+ Py_DECREF(fieldlist);
+ return -1;
+ }
+ if (Py_TYPE(fdescr) != &PyCField_Type) {
+ PyErr_SetString(PyExc_TypeError, "unexpected type");
+ Py_DECREF(fdescr);
+ Py_DECREF(fieldlist);
+ return -1;
+ }
+ if (fdescr->anonymous) {
+ int rc = MakeFields(type, fdescr,
+ index + fdescr->index,
+ offset + fdescr->offset);
+ Py_DECREF(fdescr);
+ if (rc == -1) {
+ Py_DECREF(fieldlist);
+ return -1;
+ }
+ continue;
+ }
+ new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL);
+ if (new_descr == NULL) {
+ Py_DECREF(fdescr);
+ Py_DECREF(fieldlist);
+ return -1;
+ }
+ assert(Py_TYPE(new_descr) == &PyCField_Type);
+ new_descr->size = fdescr->size;
+ new_descr->offset = fdescr->offset + offset;
+ new_descr->index = fdescr->index + index;
+ new_descr->proto = fdescr->proto;
+ Py_XINCREF(new_descr->proto);
+ new_descr->getfunc = fdescr->getfunc;
+ new_descr->setfunc = fdescr->setfunc;
+
+ Py_DECREF(fdescr);
+
+ if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
+ Py_DECREF(fieldlist);
+ Py_DECREF(new_descr);
+ return -1;
+ }
+ Py_DECREF(new_descr);
+ }
+ Py_DECREF(fieldlist);
+ return 0;
}
/* Iterate over the names in the type's _anonymous_ attribute, if present,
@@ -257,43 +257,43 @@ MakeFields(PyObject *type, CFieldObject *descr,
static int
MakeAnonFields(PyObject *type)
{
- PyObject *anon;
- PyObject *anon_names;
- Py_ssize_t i;
-
- anon = PyObject_GetAttrString(type, "_anonymous_");
- if (anon == NULL) {
- PyErr_Clear();
- return 0;
- }
- anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
- Py_DECREF(anon);
- if (anon_names == NULL)
- return -1;
-
- for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
- PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
- CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
- if (descr == NULL) {
- Py_DECREF(anon_names);
- return -1;
- }
- assert(Py_TYPE(descr) == &PyCField_Type);
- descr->anonymous = 1;
-
- /* descr is in the field descriptor. */
- if (-1 == MakeFields(type, (CFieldObject *)descr,
- ((CFieldObject *)descr)->index,
- ((CFieldObject *)descr)->offset)) {
- Py_DECREF(descr);
- Py_DECREF(anon_names);
- return -1;
- }
- Py_DECREF(descr);
- }
-
- Py_DECREF(anon_names);
- return 0;
+ PyObject *anon;
+ PyObject *anon_names;
+ Py_ssize_t i;
+
+ anon = PyObject_GetAttrString(type, "_anonymous_");
+ if (anon == NULL) {
+ PyErr_Clear();
+ return 0;
+ }
+ anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
+ Py_DECREF(anon);
+ if (anon_names == NULL)
+ return -1;
+
+ for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
+ PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
+ CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
+ if (descr == NULL) {
+ Py_DECREF(anon_names);
+ return -1;
+ }
+ assert(Py_TYPE(descr) == &PyCField_Type);
+ descr->anonymous = 1;
+
+ /* descr is in the field descriptor. */
+ if (-1 == MakeFields(type, (CFieldObject *)descr,
+ ((CFieldObject *)descr)->index,
+ ((CFieldObject *)descr)->offset)) {
+ Py_DECREF(descr);
+ Py_DECREF(anon_names);
+ return -1;
+ }
+ Py_DECREF(descr);
+ }
+
+ Py_DECREF(anon_names);
+ return 0;
}
/*
@@ -303,261 +303,261 @@ MakeAnonFields(PyObject *type)
int
PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct)
{
- StgDictObject *stgdict, *basedict;
- Py_ssize_t len, offset, size, align, i;
- Py_ssize_t union_size, total_align;
- Py_ssize_t field_size = 0;
- int bitofs;
- PyObject *isPacked;
- int pack = 0;
- Py_ssize_t ffi_ofs;
- int big_endian;
-
- /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
- be a way to use the old, broken sematics: _fields_ are not extended
- but replaced in subclasses.
-
- XXX Remove this in ctypes 1.0!
- */
- int use_broken_old_ctypes_semantics;
-
- if (fields == NULL)
- return 0;
+ StgDictObject *stgdict, *basedict;
+ Py_ssize_t len, offset, size, align, i;
+ Py_ssize_t union_size, total_align;
+ Py_ssize_t field_size = 0;
+ int bitofs;
+ PyObject *isPacked;
+ int pack = 0;
+ Py_ssize_t ffi_ofs;
+ int big_endian;
+
+ /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
+ be a way to use the old, broken sematics: _fields_ are not extended
+ but replaced in subclasses.
+
+ XXX Remove this in ctypes 1.0!
+ */
+ int use_broken_old_ctypes_semantics;
+
+ if (fields == NULL)
+ return 0;
#ifdef WORDS_BIGENDIAN
- big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
+ big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
#else
- big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
+ big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
#endif
- use_broken_old_ctypes_semantics = \
- PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");
-
- isPacked = PyObject_GetAttrString(type, "_pack_");
- if (isPacked) {
- pack = PyLong_AsLong(isPacked);
- if (pack < 0 || PyErr_Occurred()) {
- Py_XDECREF(isPacked);
- PyErr_SetString(PyExc_ValueError,
- "_pack_ must be a non-negative integer");
- return -1;
- }
- Py_DECREF(isPacked);
- } else
- PyErr_Clear();
-
- len = PySequence_Length(fields);
- if (len == -1) {
- PyErr_SetString(PyExc_TypeError,
- "'_fields_' must be a sequence of pairs");
- return -1;
- }
-
- stgdict = PyType_stgdict(type);
- if (!stgdict)
- return -1;
- /* If this structure/union is already marked final we cannot assign
- _fields_ anymore. */
-
- if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
- PyErr_SetString(PyExc_AttributeError,
- "_fields_ is final");
- return -1;
- }
-
- if (stgdict->format) {
- PyMem_Free(stgdict->format);
- stgdict->format = NULL;
- }
-
- if (stgdict->ffi_type_pointer.elements)
- PyMem_Free(stgdict->ffi_type_pointer.elements);
-
- basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
- if (basedict && !use_broken_old_ctypes_semantics) {
- size = offset = basedict->size;
- align = basedict->align;
- union_size = 0;
- total_align = align ? align : 1;
- stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
- stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
- if (stgdict->ffi_type_pointer.elements == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- memset(stgdict->ffi_type_pointer.elements, 0,
- sizeof(ffi_type *) * (basedict->length + len + 1));
- memcpy(stgdict->ffi_type_pointer.elements,
- basedict->ffi_type_pointer.elements,
- sizeof(ffi_type *) * (basedict->length));
- ffi_ofs = basedict->length;
- } else {
- offset = 0;
- size = 0;
- align = 0;
- union_size = 0;
- total_align = 1;
- stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
- stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
- if (stgdict->ffi_type_pointer.elements == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- memset(stgdict->ffi_type_pointer.elements, 0,
- sizeof(ffi_type *) * (len + 1));
- ffi_ofs = 0;
- }
-
- assert(stgdict->format == NULL);
- if (isStruct && !isPacked) {
- stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
- } else {
- /* PEP3118 doesn't support union, or packed structures (well,
- only standard packing, but we dont support the pep for
- that). Use 'B' for bytes. */
- stgdict->format = _ctypes_alloc_format_string(NULL, "B");
- }
+ use_broken_old_ctypes_semantics = \
+ PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");
+
+ isPacked = PyObject_GetAttrString(type, "_pack_");
+ if (isPacked) {
+ pack = PyLong_AsLong(isPacked);
+ if (pack < 0 || PyErr_Occurred()) {
+ Py_XDECREF(isPacked);
+ PyErr_SetString(PyExc_ValueError,
+ "_pack_ must be a non-negative integer");
+ return -1;
+ }
+ Py_DECREF(isPacked);
+ } else
+ PyErr_Clear();
+
+ len = PySequence_Length(fields);
+ if (len == -1) {
+ PyErr_SetString(PyExc_TypeError,
+ "'_fields_' must be a sequence of pairs");
+ return -1;
+ }
+
+ stgdict = PyType_stgdict(type);
+ if (!stgdict)
+ return -1;
+ /* If this structure/union is already marked final we cannot assign
+ _fields_ anymore. */
+
+ if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
+ PyErr_SetString(PyExc_AttributeError,
+ "_fields_ is final");
+ return -1;
+ }
+
+ if (stgdict->format) {
+ PyMem_Free(stgdict->format);
+ stgdict->format = NULL;
+ }
+
+ if (stgdict->ffi_type_pointer.elements)
+ PyMem_Free(stgdict->ffi_type_pointer.elements);
+
+ basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
+ if (basedict && !use_broken_old_ctypes_semantics) {
+ size = offset = basedict->size;
+ align = basedict->align;
+ union_size = 0;
+ total_align = align ? align : 1;
+ stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
+ stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
+ if (stgdict->ffi_type_pointer.elements == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memset(stgdict->ffi_type_pointer.elements, 0,
+ sizeof(ffi_type *) * (basedict->length + len + 1));
+ memcpy(stgdict->ffi_type_pointer.elements,
+ basedict->ffi_type_pointer.elements,
+ sizeof(ffi_type *) * (basedict->length));
+ ffi_ofs = basedict->length;
+ } else {
+ offset = 0;
+ size = 0;
+ align = 0;
+ union_size = 0;
+ total_align = 1;
+ stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
+ stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
+ if (stgdict->ffi_type_pointer.elements == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memset(stgdict->ffi_type_pointer.elements, 0,
+ sizeof(ffi_type *) * (len + 1));
+ ffi_ofs = 0;
+ }
+
+ assert(stgdict->format == NULL);
+ if (isStruct && !isPacked) {
+ stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
+ } else {
+ /* PEP3118 doesn't support union, or packed structures (well,
+ only standard packing, but we dont support the pep for
+ that). Use 'B' for bytes. */
+ stgdict->format = _ctypes_alloc_format_string(NULL, "B");
+ }
#define realdict ((PyObject *)&stgdict->dict)
- for (i = 0; i < len; ++i) {
- PyObject *name = NULL, *desc = NULL;
- PyObject *pair = PySequence_GetItem(fields, i);
- PyObject *prop;
- StgDictObject *dict;
- int bitsize = 0;
-
- if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
- PyErr_SetString(PyExc_AttributeError,
- "'_fields_' must be a sequence of pairs");
- Py_XDECREF(pair);
- return -1;
- }
- dict = PyType_stgdict(desc);
- if (dict == NULL) {
- Py_DECREF(pair);
- PyErr_Format(PyExc_TypeError,
- "second item in _fields_ tuple (index %zd) must be a C type",
- i);
- return -1;
- }
- stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
- if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
- stgdict->flags |= TYPEFLAG_HASPOINTER;
- dict->flags |= DICTFLAG_FINAL; /* mark field type final */
- if (PyTuple_Size(pair) == 3) { /* bits specified */
- switch(dict->ffi_type_pointer.type) {
- case FFI_TYPE_UINT8:
- case FFI_TYPE_UINT16:
- case FFI_TYPE_UINT32:
- case FFI_TYPE_SINT64:
- case FFI_TYPE_UINT64:
- break;
-
- case FFI_TYPE_SINT8:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_SINT32:
- if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
+ for (i = 0; i < len; ++i) {
+ PyObject *name = NULL, *desc = NULL;
+ PyObject *pair = PySequence_GetItem(fields, i);
+ PyObject *prop;
+ StgDictObject *dict;
+ int bitsize = 0;
+
+ if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "'_fields_' must be a sequence of pairs");
+ Py_XDECREF(pair);
+ return -1;
+ }
+ dict = PyType_stgdict(desc);
+ if (dict == NULL) {
+ Py_DECREF(pair);
+ PyErr_Format(PyExc_TypeError,
+ "second item in _fields_ tuple (index %zd) must be a C type",
+ i);
+ return -1;
+ }
+ stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
+ if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
+ stgdict->flags |= TYPEFLAG_HASPOINTER;
+ dict->flags |= DICTFLAG_FINAL; /* mark field type final */
+ if (PyTuple_Size(pair) == 3) { /* bits specified */
+ switch(dict->ffi_type_pointer.type) {
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT64:
+ case FFI_TYPE_UINT64:
+ break;
+
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_SINT32:
+ if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
#ifdef CTYPES_UNICODE
- && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
+ && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
#endif
- )
- break;
- /* else fall through */
- default:
- PyErr_Format(PyExc_TypeError,
- "bit fields not allowed for type %s",
- ((PyTypeObject *)desc)->tp_name);
- Py_DECREF(pair);
- return -1;
- }
- if (bitsize <= 0 || bitsize > dict->size * 8) {
- PyErr_SetString(PyExc_ValueError,
- "number of bits invalid for bit field");
- Py_DECREF(pair);
- return -1;
- }
- } else
- bitsize = 0;
- if (isStruct && !isPacked) {
- char *fieldfmt = dict->format ? dict->format : "B";
- char *fieldname = _PyUnicode_AsString(name);
- char *ptr;
- Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
- char *buf = alloca(len + 2 + 1);
-
- sprintf(buf, "%s:%s:", fieldfmt, fieldname);
-
- ptr = stgdict->format;
- stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
- PyMem_Free(ptr);
-
- if (stgdict->format == NULL) {
- Py_DECREF(pair);
- return -1;
- }
- }
- if (isStruct) {
- prop = PyCField_FromDesc(desc, i,
- &field_size, bitsize, &bitofs,
- &size, &offset, &align,
- pack, big_endian);
- } else /* union */ {
- size = 0;
- offset = 0;
- align = 0;
- prop = PyCField_FromDesc(desc, i,
- &field_size, bitsize, &bitofs,
- &size, &offset, &align,
- pack, big_endian);
- union_size = max(size, union_size);
- }
- total_align = max(align, total_align);
-
- if (!prop) {
- Py_DECREF(pair);
- return -1;
- }
- if (-1 == PyObject_SetAttr(type, name, prop)) {
- Py_DECREF(prop);
- Py_DECREF(pair);
- return -1;
- }
- Py_DECREF(pair);
- Py_DECREF(prop);
- }
+ )
+ break;
+ /* else fall through */
+ default:
+ PyErr_Format(PyExc_TypeError,
+ "bit fields not allowed for type %s",
+ ((PyTypeObject *)desc)->tp_name);
+ Py_DECREF(pair);
+ return -1;
+ }
+ if (bitsize <= 0 || bitsize > dict->size * 8) {
+ PyErr_SetString(PyExc_ValueError,
+ "number of bits invalid for bit field");
+ Py_DECREF(pair);
+ return -1;
+ }
+ } else
+ bitsize = 0;
+ if (isStruct && !isPacked) {
+ char *fieldfmt = dict->format ? dict->format : "B";
+ char *fieldname = _PyUnicode_AsString(name);
+ char *ptr;
+ Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
+ char *buf = alloca(len + 2 + 1);
+
+ sprintf(buf, "%s:%s:", fieldfmt, fieldname);
+
+ ptr = stgdict->format;
+ stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
+ PyMem_Free(ptr);
+
+ if (stgdict->format == NULL) {
+ Py_DECREF(pair);
+ return -1;
+ }
+ }
+ if (isStruct) {
+ prop = PyCField_FromDesc(desc, i,
+ &field_size, bitsize, &bitofs,
+ &size, &offset, &align,
+ pack, big_endian);
+ } else /* union */ {
+ size = 0;
+ offset = 0;
+ align = 0;
+ prop = PyCField_FromDesc(desc, i,
+ &field_size, bitsize, &bitofs,
+ &size, &offset, &align,
+ pack, big_endian);
+ union_size = max(size, union_size);
+ }
+ total_align = max(align, total_align);
+
+ if (!prop) {
+ Py_DECREF(pair);
+ return -1;
+ }
+ if (-1 == PyObject_SetAttr(type, name, prop)) {
+ Py_DECREF(prop);
+ Py_DECREF(pair);
+ return -1;
+ }
+ Py_DECREF(pair);
+ Py_DECREF(prop);
+ }
#undef realdict
- if (isStruct && !isPacked) {
- char *ptr = stgdict->format;
- stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
- PyMem_Free(ptr);
- if (stgdict->format == NULL)
- return -1;
- }
-
- if (!isStruct)
- size = union_size;
-
- /* Adjust the size according to the alignment requirements */
- size = ((size + total_align - 1) / total_align) * total_align;
-
- stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
- Py_ssize_t,
- unsigned short);
- stgdict->ffi_type_pointer.size = size;
-
- stgdict->size = size;
- stgdict->align = total_align;
- stgdict->length = len; /* ADD ffi_ofs? */
-
- /* We did check that this flag was NOT set above, it must not
- have been set until now. */
- if (stgdict->flags & DICTFLAG_FINAL) {
- PyErr_SetString(PyExc_AttributeError,
- "Structure or union cannot contain itself");
- return -1;
- }
- stgdict->flags |= DICTFLAG_FINAL;
-
- return MakeAnonFields(type);
+ if (isStruct && !isPacked) {
+ char *ptr = stgdict->format;
+ stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
+ PyMem_Free(ptr);
+ if (stgdict->format == NULL)
+ return -1;
+ }
+
+ if (!isStruct)
+ size = union_size;
+
+ /* Adjust the size according to the alignment requirements */
+ size = ((size + total_align - 1) / total_align) * total_align;
+
+ stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
+ Py_ssize_t,
+ unsigned short);
+ stgdict->ffi_type_pointer.size = size;
+
+ stgdict->size = size;
+ stgdict->align = total_align;
+ stgdict->length = len; /* ADD ffi_ofs? */
+
+ /* We did check that this flag was NOT set above, it must not
+ have been set until now. */
+ if (stgdict->flags & DICTFLAG_FINAL) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Structure or union cannot contain itself");
+ return -1;
+ }
+ stgdict->flags |= DICTFLAG_FINAL;
+
+ return MakeAnonFields(type);
}
diff --git a/Modules/_curses_panel.c b/Modules/_curses_panel.c
index ff1276d..8561a2e 100644
--- a/Modules/_curses_panel.c
+++ b/Modules/_curses_panel.c
@@ -22,7 +22,7 @@ static PyObject *PyCursesError;
/* Utility Functions */
/*
- * Check the return code from a curses function and return None
+ * Check the return code from a curses function and return None
* or raise an exception as appropriate.
*/
@@ -30,15 +30,15 @@ static PyObject *
PyCursesCheckERR(int code, char *fname)
{
if (code != ERR) {
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
} else {
- if (fname == NULL) {
- PyErr_SetString(PyCursesError, catchall_ERR);
- } else {
- PyErr_Format(PyCursesError, "%s() returned ERR", fname);
- }
- return NULL;
+ if (fname == NULL) {
+ PyErr_SetString(PyCursesError, catchall_ERR);
+ } else {
+ PyErr_Format(PyCursesError, "%s() returned ERR", fname);
+ }
+ return NULL;
}
}
@@ -51,12 +51,12 @@ PyCursesCheckERR(int code, char *fname)
typedef struct {
PyObject_HEAD
PANEL *pan;
- PyCursesWindowObject *wo; /* for reference counts */
+ PyCursesWindowObject *wo; /* for reference counts */
} PyCursesPanelObject;
PyTypeObject PyCursesPanel_Type;
-#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type)
+#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type)
/* Some helper functions. The problem is that there's always a window
associated with a panel. To ensure that Python's GC doesn't pull
@@ -88,10 +88,10 @@ static int
insert_lop(PyCursesPanelObject *po)
{
list_of_panels *new;
-
+
if ((new = (list_of_panels *)malloc(sizeof(list_of_panels))) == NULL) {
- PyErr_NoMemory();
- return -1;
+ PyErr_NoMemory();
+ return -1;
}
new->po = po;
new->next = lop;
@@ -107,17 +107,17 @@ remove_lop(PyCursesPanelObject *po)
temp = lop;
if (temp->po == po) {
- lop = temp->next;
- free(temp);
- return;
+ lop = temp->next;
+ free(temp);
+ return;
}
while (temp->next == NULL || temp->next->po != po) {
- if (temp->next == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "remove_lop: can't find Panel Object");
- return;
- }
- temp = temp->next;
+ if (temp->next == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "remove_lop: can't find Panel Object");
+ return;
+ }
+ temp = temp->next;
}
n = temp->next->next;
free(temp->next);
@@ -131,7 +131,7 @@ find_po(PANEL *pan)
{
list_of_panels *temp;
for (temp = lop; temp->po->pan != pan; temp = temp->next)
- if (temp->next == NULL) return NULL; /* not found!? */
+ if (temp->next == NULL) return NULL; /* not found!? */
return temp->po;
}
@@ -179,9 +179,9 @@ PyCursesPanel_New(PANEL *pan, PyCursesWindowObject *wo)
if (po == NULL) return NULL;
po->pan = pan;
if (insert_lop(po) < 0) {
- po->wo = NULL;
- Py_DECREF(po);
- return NULL;
+ po->wo = NULL;
+ Py_DECREF(po);
+ return NULL;
}
po->wo = wo;
Py_INCREF(wo);
@@ -193,8 +193,8 @@ PyCursesPanel_Dealloc(PyCursesPanelObject *po)
{
(void)del_panel(po->pan);
if (po->wo != NULL) {
- Py_DECREF(po->wo);
- remove_lop(po);
+ Py_DECREF(po->wo);
+ remove_lop(po);
}
PyObject_DEL(po);
}
@@ -206,19 +206,19 @@ PyCursesPanel_above(PyCursesPanelObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
-
+
pan = panel_above(self->pan);
- if (pan == NULL) { /* valid output, it means the calling panel
- is on top of the stack */
- Py_INCREF(Py_None);
- return Py_None;
+ if (pan == NULL) { /* valid output, it means the calling panel
+ is on top of the stack */
+ Py_INCREF(Py_None);
+ return Py_None;
}
po = find_po(pan);
if (po == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "panel_above: can't find Panel Object");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError,
+ "panel_above: can't find Panel Object");
+ return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@@ -231,19 +231,19 @@ PyCursesPanel_below(PyCursesPanelObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
-
+
pan = panel_below(self->pan);
-
- if (pan == NULL) { /* valid output, it means the calling panel
- is on the bottom of the stack */
- Py_INCREF(Py_None);
- return Py_None;
+
+ if (pan == NULL) { /* valid output, it means the calling panel
+ is on the bottom of the stack */
+ Py_INCREF(Py_None);
+ return Py_None;
}
po = find_po(pan);
if (po == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "panel_below: can't find Panel Object");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError,
+ "panel_below: can't find Panel Object");
+ return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@@ -262,26 +262,26 @@ PyCursesPanel_replace_panel(PyCursesPanelObject *self, PyObject *args)
PyCursesPanelObject *po;
PyCursesWindowObject *temp;
int rtn;
-
+
if (PyTuple_Size(args) != 1) {
- PyErr_SetString(PyExc_TypeError, "replace requires one argument");
- return NULL;
+ PyErr_SetString(PyExc_TypeError, "replace requires one argument");
+ return NULL;
}
if (!PyArg_ParseTuple(args, "O!;window object",
- &PyCursesWindow_Type, &temp))
- return NULL;
+ &PyCursesWindow_Type, &temp))
+ return NULL;
po = find_po(self->pan);
if (po == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "replace_panel: can't find Panel Object");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError,
+ "replace_panel: can't find Panel Object");
+ return NULL;
}
rtn = replace_panel(self->pan, temp->win);
if (rtn == ERR) {
- PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
- return NULL;
+ PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
+ return NULL;
}
Py_DECREF(po->wo);
po->wo = temp;
@@ -302,11 +302,11 @@ static PyObject *
PyCursesPanel_userptr(PyCursesPanelObject *self)
{
PyObject *obj;
- PyCursesInitialised;
+ PyCursesInitialised;
obj = (PyObject *) panel_userptr(self->pan);
if (obj == NULL) {
- PyErr_SetString(PyCursesError, "no userptr set");
- return NULL;
+ PyErr_SetString(PyCursesError, "no userptr set");
+ return NULL;
}
Py_INCREF(obj);
@@ -329,40 +329,40 @@ static PyMethodDef PyCursesPanel_Methods[] = {
{"top", (PyCFunction)PyCursesPanel_top_panel, METH_NOARGS},
{"userptr", (PyCFunction)PyCursesPanel_userptr, METH_NOARGS},
{"window", (PyCFunction)PyCursesPanel_window, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* -------------------------------------------------------*/
PyTypeObject PyCursesPanel_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_curses_panel.curses panel", /*tp_name*/
- sizeof(PyCursesPanelObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ "_curses_panel.curses panel", /*tp_name*/
+ sizeof(PyCursesPanelObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
(destructor)PyCursesPanel_Dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 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*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 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, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
PyCursesPanel_Methods, /*tp_methods*/
};
@@ -380,16 +380,16 @@ PyCurses_bottom_panel(PyObject *self)
pan = panel_above(NULL);
- if (pan == NULL) { /* valid output, it means
- there's no panel at all */
- Py_INCREF(Py_None);
- return Py_None;
+ if (pan == NULL) { /* valid output, it means
+ there's no panel at all */
+ Py_INCREF(Py_None);
+ return Py_None;
}
po = find_po(pan);
if (po == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "panel_above: can't find Panel Object");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError,
+ "panel_above: can't find Panel Object");
+ return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@@ -405,8 +405,8 @@ PyCurses_new_panel(PyObject *self, PyObject *args)
return NULL;
pan = new_panel(win->win);
if (pan == NULL) {
- PyErr_SetString(PyCursesError, catchall_NULL);
- return NULL;
+ PyErr_SetString(PyCursesError, catchall_NULL);
+ return NULL;
}
return (PyObject *)PyCursesPanel_New(pan, win);
}
@@ -421,28 +421,28 @@ PyCurses_top_panel(PyObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
-
+
PyCursesInitialised;
pan = panel_below(NULL);
- if (pan == NULL) { /* valid output, it means
- there's no panel at all */
- Py_INCREF(Py_None);
- return Py_None;
+ if (pan == NULL) { /* valid output, it means
+ there's no panel at all */
+ Py_INCREF(Py_None);
+ return Py_None;
}
po = find_po(pan);
if (po == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "panel_below: can't find Panel Object");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError,
+ "panel_below: can't find Panel Object");
+ return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
}
static PyObject *PyCurses_update_panels(PyObject *self)
-{
+{
PyCursesInitialised;
update_panels();
Py_INCREF(Py_None);
@@ -457,22 +457,22 @@ static PyMethodDef PyCurses_methods[] = {
{"new_panel", (PyCFunction)PyCurses_new_panel, METH_VARARGS},
{"top_panel", (PyCFunction)PyCurses_top_panel, METH_NOARGS},
{"update_panels", (PyCFunction)PyCurses_update_panels, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* Initialization function for the module */
static struct PyModuleDef _curses_panelmodule = {
- PyModuleDef_HEAD_INIT,
- "_curses_panel",
- NULL,
- -1,
- PyCurses_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_curses_panel",
+ NULL,
+ -1,
+ PyCurses_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -489,7 +489,7 @@ PyInit__curses_panel(void)
/* Create the module and add the functions */
m = PyModule_Create(&_curses_panelmodule);
if (m == NULL)
- return NULL;
+ return NULL;
d = PyModule_GetDict(m);
/* For exception _curses_panel.error */
diff --git a/Modules/_dbmmodule.c b/Modules/_dbmmodule.c
index 885c3aa..827acce 100644
--- a/Modules/_dbmmodule.c
+++ b/Modules/_dbmmodule.c
@@ -33,9 +33,9 @@ static char *which_dbm = "Berkeley DB";
#endif
typedef struct {
- PyObject_HEAD
- int di_size; /* -1 means recompute */
- DBM *di_dbm;
+ PyObject_HEAD
+ int di_size; /* -1 means recompute */
+ DBM *di_dbm;
} dbmobject;
static PyTypeObject Dbmtype;
@@ -50,18 +50,18 @@ static PyObject *DbmError;
static PyObject *
newdbmobject(char *file, int flags, int mode)
{
- dbmobject *dp;
-
- dp = PyObject_New(dbmobject, &Dbmtype);
- if (dp == NULL)
- return NULL;
- dp->di_size = -1;
- if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) {
- PyErr_SetFromErrno(DbmError);
- Py_DECREF(dp);
- return NULL;
- }
- return (PyObject *)dp;
+ dbmobject *dp;
+
+ dp = PyObject_New(dbmobject, &Dbmtype);
+ if (dp == NULL)
+ return NULL;
+ dp->di_size = -1;
+ if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) {
+ PyErr_SetFromErrno(DbmError);
+ Py_DECREF(dp);
+ return NULL;
+ }
+ return (PyObject *)dp;
}
/* Methods */
@@ -69,294 +69,294 @@ newdbmobject(char *file, int flags, int mode)
static void
dbm_dealloc(register dbmobject *dp)
{
- if ( dp->di_dbm )
- dbm_close(dp->di_dbm);
- PyObject_Del(dp);
+ if ( dp->di_dbm )
+ dbm_close(dp->di_dbm);
+ PyObject_Del(dp);
}
static Py_ssize_t
dbm_length(dbmobject *dp)
{
- if (dp->di_dbm == NULL) {
- PyErr_SetString(DbmError, "DBM object has already been closed");
- return -1;
- }
- if ( dp->di_size < 0 ) {
- datum key;
- int size;
-
- size = 0;
- for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
- key = dbm_nextkey(dp->di_dbm))
- size++;
- dp->di_size = size;
- }
- return dp->di_size;
+ if (dp->di_dbm == NULL) {
+ PyErr_SetString(DbmError, "DBM object has already been closed");
+ return -1;
+ }
+ if ( dp->di_size < 0 ) {
+ datum key;
+ int size;
+
+ size = 0;
+ for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
+ key = dbm_nextkey(dp->di_dbm))
+ size++;
+ dp->di_size = size;
+ }
+ return dp->di_size;
}
static PyObject *
dbm_subscript(dbmobject *dp, register PyObject *key)
{
- datum drec, krec;
- Py_ssize_t tmp_size;
-
- if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
- return NULL;
-
- krec.dsize = tmp_size;
- check_dbmobject_open(dp);
- drec = dbm_fetch(dp->di_dbm, krec);
- if ( drec.dptr == 0 ) {
- PyErr_SetObject(PyExc_KeyError, key);
- return NULL;
- }
- if ( dbm_error(dp->di_dbm) ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "");
- return NULL;
- }
- return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
+ datum drec, krec;
+ Py_ssize_t tmp_size;
+
+ if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
+ return NULL;
+
+ krec.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ drec = dbm_fetch(dp->di_dbm, krec);
+ if ( drec.dptr == 0 ) {
+ PyErr_SetObject(PyExc_KeyError, key);
+ return NULL;
+ }
+ if ( dbm_error(dp->di_dbm) ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "");
+ return NULL;
+ }
+ return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
}
static int
dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
{
- datum krec, drec;
- Py_ssize_t tmp_size;
-
- if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have bytes or string keys only");
- return -1;
- }
- krec.dsize = tmp_size;
- if (dp->di_dbm == NULL) {
- PyErr_SetString(DbmError, "DBM object has already been closed");
- return -1;
+ datum krec, drec;
+ Py_ssize_t tmp_size;
+
+ if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have bytes or string keys only");
+ return -1;
+ }
+ krec.dsize = tmp_size;
+ if (dp->di_dbm == NULL) {
+ PyErr_SetString(DbmError, "DBM object has already been closed");
+ return -1;
+ }
+ dp->di_size = -1;
+ if (w == NULL) {
+ if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetObject(PyExc_KeyError, v);
+ return -1;
+ }
+ } else {
+ if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have byte or string elements only");
+ return -1;
+ }
+ drec.dsize = tmp_size;
+ if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError,
+ "cannot add item to database");
+ return -1;
}
- dp->di_size = -1;
- if (w == NULL) {
- if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetObject(PyExc_KeyError, v);
- return -1;
- }
- } else {
- if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have byte or string elements only");
- return -1;
- }
- drec.dsize = tmp_size;
- if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError,
- "cannot add item to database");
- return -1;
- }
- }
- if ( dbm_error(dp->di_dbm) ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "");
- return -1;
- }
- return 0;
+ }
+ if ( dbm_error(dp->di_dbm) ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "");
+ return -1;
+ }
+ return 0;
}
static PyMappingMethods dbm_as_mapping = {
- (lenfunc)dbm_length, /*mp_length*/
- (binaryfunc)dbm_subscript, /*mp_subscript*/
- (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
+ (lenfunc)dbm_length, /*mp_length*/
+ (binaryfunc)dbm_subscript, /*mp_subscript*/
+ (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
};
static PyObject *
dbm__close(register dbmobject *dp, PyObject *unused)
{
- if (dp->di_dbm)
- dbm_close(dp->di_dbm);
- dp->di_dbm = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (dp->di_dbm)
+ dbm_close(dp->di_dbm);
+ dp->di_dbm = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
dbm_keys(register dbmobject *dp, PyObject *unused)
{
- register PyObject *v, *item;
- datum key;
- int err;
-
- check_dbmobject_open(dp);
- v = PyList_New(0);
- if (v == NULL)
- return NULL;
- for (key = dbm_firstkey(dp->di_dbm); key.dptr;
- key = dbm_nextkey(dp->di_dbm)) {
- item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
- if (item == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- err = PyList_Append(v, item);
- Py_DECREF(item);
- if (err != 0) {
- Py_DECREF(v);
- return NULL;
- }
- }
- return v;
+ register PyObject *v, *item;
+ datum key;
+ int err;
+
+ check_dbmobject_open(dp);
+ v = PyList_New(0);
+ if (v == NULL)
+ return NULL;
+ for (key = dbm_firstkey(dp->di_dbm); key.dptr;
+ key = dbm_nextkey(dp->di_dbm)) {
+ item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
+ if (item == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ err = PyList_Append(v, item);
+ Py_DECREF(item);
+ if (err != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ }
+ return v;
}
static int
dbm_contains(PyObject *self, PyObject *arg)
{
- dbmobject *dp = (dbmobject *)self;
- datum key, val;
-
- if ((dp)->di_dbm == NULL) {
- PyErr_SetString(DbmError,
- "DBM object has already been closed");
- return -1;
- }
- if (PyUnicode_Check(arg)) {
- arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
- if (arg == NULL)
- return -1;
- }
- if (!PyBytes_Check(arg)) {
- PyErr_Format(PyExc_TypeError,
- "dbm key must be string, not %.100s",
- arg->ob_type->tp_name);
- return -1;
- }
- key.dptr = PyBytes_AS_STRING(arg);
- key.dsize = PyBytes_GET_SIZE(arg);
- val = dbm_fetch(dp->di_dbm, key);
- return val.dptr != NULL;
+ dbmobject *dp = (dbmobject *)self;
+ datum key, val;
+
+ if ((dp)->di_dbm == NULL) {
+ PyErr_SetString(DbmError,
+ "DBM object has already been closed");
+ return -1;
+ }
+ if (PyUnicode_Check(arg)) {
+ arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
+ if (arg == NULL)
+ return -1;
+ }
+ if (!PyBytes_Check(arg)) {
+ PyErr_Format(PyExc_TypeError,
+ "dbm key must be string, not %.100s",
+ arg->ob_type->tp_name);
+ return -1;
+ }
+ key.dptr = PyBytes_AS_STRING(arg);
+ key.dsize = PyBytes_GET_SIZE(arg);
+ val = dbm_fetch(dp->di_dbm, key);
+ return val.dptr != NULL;
}
static PySequenceMethods dbm_as_sequence = {
- 0, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- dbm_contains, /* sq_contains */
- 0, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ dbm_contains, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
static PyObject *
dbm_get(register dbmobject *dp, PyObject *args)
{
- datum key, val;
- PyObject *defvalue = Py_None;
- char *tmp_ptr;
- Py_ssize_t tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#|O:get",
- &tmp_ptr, &tmp_size, &defvalue))
- return NULL;
- key.dptr = tmp_ptr;
- key.dsize = tmp_size;
- check_dbmobject_open(dp);
- val = dbm_fetch(dp->di_dbm, key);
- if (val.dptr != NULL)
- return PyBytes_FromStringAndSize(val.dptr, val.dsize);
- else {
- Py_INCREF(defvalue);
- return defvalue;
- }
+ datum key, val;
+ PyObject *defvalue = Py_None;
+ char *tmp_ptr;
+ Py_ssize_t tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#|O:get",
+ &tmp_ptr, &tmp_size, &defvalue))
+ return NULL;
+ key.dptr = tmp_ptr;
+ key.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ val = dbm_fetch(dp->di_dbm, key);
+ if (val.dptr != NULL)
+ return PyBytes_FromStringAndSize(val.dptr, val.dsize);
+ else {
+ Py_INCREF(defvalue);
+ return defvalue;
+ }
}
static PyObject *
dbm_setdefault(register dbmobject *dp, PyObject *args)
{
- datum key, val;
- PyObject *defvalue = NULL;
- char *tmp_ptr;
- Py_ssize_t tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#|O:setdefault",
- &tmp_ptr, &tmp_size, &defvalue))
- return NULL;
- key.dptr = tmp_ptr;
- key.dsize = tmp_size;
- check_dbmobject_open(dp);
- val = dbm_fetch(dp->di_dbm, key);
- if (val.dptr != NULL)
- return PyBytes_FromStringAndSize(val.dptr, val.dsize);
- if (defvalue == NULL) {
- defvalue = PyBytes_FromStringAndSize(NULL, 0);
- if (defvalue == NULL)
- return NULL;
- val.dptr = NULL;
- val.dsize = 0;
- }
- else {
- if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have byte string elements only");
- return NULL;
- }
- val.dsize = tmp_size;
- Py_INCREF(defvalue);
- }
- if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "cannot add item to database");
- Py_DECREF(defvalue);
- return NULL;
- }
- return defvalue;
+ datum key, val;
+ PyObject *defvalue = NULL;
+ char *tmp_ptr;
+ Py_ssize_t tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#|O:setdefault",
+ &tmp_ptr, &tmp_size, &defvalue))
+ return NULL;
+ key.dptr = tmp_ptr;
+ key.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ val = dbm_fetch(dp->di_dbm, key);
+ if (val.dptr != NULL)
+ return PyBytes_FromStringAndSize(val.dptr, val.dsize);
+ if (defvalue == NULL) {
+ defvalue = PyBytes_FromStringAndSize(NULL, 0);
+ if (defvalue == NULL)
+ return NULL;
+ val.dptr = NULL;
+ val.dsize = 0;
+ }
+ else {
+ if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have byte string elements only");
+ return NULL;
+ }
+ val.dsize = tmp_size;
+ Py_INCREF(defvalue);
+ }
+ if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "cannot add item to database");
+ Py_DECREF(defvalue);
+ return NULL;
+ }
+ return defvalue;
}
static PyMethodDef dbm_methods[] = {
- {"close", (PyCFunction)dbm__close, METH_NOARGS,
- "close()\nClose the database."},
- {"keys", (PyCFunction)dbm_keys, METH_NOARGS,
- "keys() -> list\nReturn a list of all keys in the database."},
- {"get", (PyCFunction)dbm_get, METH_VARARGS,
- "get(key[, default]) -> value\n"
- "Return the value for key if present, otherwise default."},
- {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS,
- "setdefault(key[, default]) -> value\n"
- "Return the value for key if present, otherwise default. If key\n"
- "is not in the database, it is inserted with default as the value."},
- {NULL, NULL} /* sentinel */
+ {"close", (PyCFunction)dbm__close, METH_NOARGS,
+ "close()\nClose the database."},
+ {"keys", (PyCFunction)dbm_keys, METH_NOARGS,
+ "keys() -> list\nReturn a list of all keys in the database."},
+ {"get", (PyCFunction)dbm_get, METH_VARARGS,
+ "get(key[, default]) -> value\n"
+ "Return the value for key if present, otherwise default."},
+ {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS,
+ "setdefault(key[, default]) -> value\n"
+ "Return the value for key if present, otherwise default. If key\n"
+ "is not in the database, it is inserted with default as the value."},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject Dbmtype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_dbm.dbm",
- sizeof(dbmobject),
- 0,
- (destructor)dbm_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- &dbm_as_sequence, /*tp_as_sequence*/
- &dbm_as_mapping, /*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, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- dbm_methods, /*tp_methods*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_dbm.dbm",
+ sizeof(dbmobject),
+ 0,
+ (destructor)dbm_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ &dbm_as_sequence, /*tp_as_sequence*/
+ &dbm_as_mapping, /*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, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ dbm_methods, /*tp_methods*/
};
/* ----------------------------------------------------------------- */
@@ -364,74 +364,74 @@ static PyTypeObject Dbmtype = {
static PyObject *
dbmopen(PyObject *self, PyObject *args)
{
- char *name;
- char *flags = "r";
- int iflags;
- int mode = 0666;
-
- if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) )
- return NULL;
- if ( strcmp(flags, "r") == 0 )
- iflags = O_RDONLY;
- else if ( strcmp(flags, "w") == 0 )
- iflags = O_RDWR;
- else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
- iflags = O_RDWR|O_CREAT;
- else if ( strcmp(flags, "c") == 0 )
- iflags = O_RDWR|O_CREAT;
- else if ( strcmp(flags, "n") == 0 )
- iflags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(DbmError,
- "arg 2 to open should be 'r', 'w', 'c', or 'n'");
- return NULL;
- }
- return newdbmobject(name, iflags, mode);
+ char *name;
+ char *flags = "r";
+ int iflags;
+ int mode = 0666;
+
+ if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) )
+ return NULL;
+ if ( strcmp(flags, "r") == 0 )
+ iflags = O_RDONLY;
+ else if ( strcmp(flags, "w") == 0 )
+ iflags = O_RDWR;
+ else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
+ iflags = O_RDWR|O_CREAT;
+ else if ( strcmp(flags, "c") == 0 )
+ iflags = O_RDWR|O_CREAT;
+ else if ( strcmp(flags, "n") == 0 )
+ iflags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(DbmError,
+ "arg 2 to open should be 'r', 'w', 'c', or 'n'");
+ return NULL;
+ }
+ return newdbmobject(name, iflags, mode);
}
static PyMethodDef dbmmodule_methods[] = {
- { "open", (PyCFunction)dbmopen, METH_VARARGS,
- "open(path[, flag[, mode]]) -> mapping\n"
- "Return a database object."},
- { 0, 0 },
+ { "open", (PyCFunction)dbmopen, METH_VARARGS,
+ "open(path[, flag[, mode]]) -> mapping\n"
+ "Return a database object."},
+ { 0, 0 },
};
static struct PyModuleDef _dbmmodule = {
- PyModuleDef_HEAD_INIT,
- "_dbm",
- NULL,
- -1,
- dbmmodule_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_dbm",
+ NULL,
+ -1,
+ dbmmodule_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__dbm(void) {
- PyObject *m, *d, *s;
-
- if (PyType_Ready(&Dbmtype) < 0)
- return NULL;
- m = PyModule_Create(&_dbmmodule);
- if (m == NULL)
- return NULL;
- d = PyModule_GetDict(m);
- if (DbmError == NULL)
- DbmError = PyErr_NewException("_dbm.error",
- PyExc_IOError, NULL);
- s = PyUnicode_FromString(which_dbm);
- if (s != NULL) {
- PyDict_SetItemString(d, "library", s);
- Py_DECREF(s);
- }
- if (DbmError != NULL)
- PyDict_SetItemString(d, "error", DbmError);
- if (PyErr_Occurred()) {
- Py_DECREF(m);
- m = NULL;
- }
- return m;
+ PyObject *m, *d, *s;
+
+ if (PyType_Ready(&Dbmtype) < 0)
+ return NULL;
+ m = PyModule_Create(&_dbmmodule);
+ if (m == NULL)
+ return NULL;
+ d = PyModule_GetDict(m);
+ if (DbmError == NULL)
+ DbmError = PyErr_NewException("_dbm.error",
+ PyExc_IOError, NULL);
+ s = PyUnicode_FromString(which_dbm);
+ if (s != NULL) {
+ PyDict_SetItemString(d, "library", s);
+ Py_DECREF(s);
+ }
+ if (DbmError != NULL)
+ PyDict_SetItemString(d, "error", DbmError);
+ if (PyErr_Occurred()) {
+ Py_DECREF(m);
+ m = NULL;
+ }
+ return m;
}
diff --git a/Modules/_functoolsmodule.c b/Modules/_functoolsmodule.c
index a9cdcb8..bf2ea3b 100644
--- a/Modules/_functoolsmodule.c
+++ b/Modules/_functoolsmodule.c
@@ -2,7 +2,7 @@
#include "Python.h"
#include "structmember.h"
-/* _functools module written and maintained
+/* _functools module written and maintained
by Hye-Shik Chang <perky@FreeBSD.org>
with adaptations by Raymond Hettinger <python@rcn.com>
Copyright (c) 2004, 2005, 2006 Python Software Foundation.
@@ -12,12 +12,12 @@
/* partial object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *fn;
- PyObject *args;
- PyObject *kw;
- PyObject *dict;
- PyObject *weakreflist; /* List of weak references */
+ PyObject_HEAD
+ PyObject *fn;
+ PyObject *args;
+ PyObject *kw;
+ PyObject *dict;
+ PyObject *weakreflist; /* List of weak references */
} partialobject;
static PyTypeObject partial_type;
@@ -25,175 +25,175 @@ static PyTypeObject partial_type;
static PyObject *
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *func;
- partialobject *pto;
-
- if (PyTuple_GET_SIZE(args) < 1) {
- PyErr_SetString(PyExc_TypeError,
- "type 'partial' takes at least one argument");
- return NULL;
- }
-
- func = PyTuple_GET_ITEM(args, 0);
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError,
- "the first argument must be callable");
- return NULL;
- }
-
- /* create partialobject structure */
- pto = (partialobject *)type->tp_alloc(type, 0);
- if (pto == NULL)
- return NULL;
-
- pto->fn = func;
- Py_INCREF(func);
- pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
- if (pto->args == NULL) {
- pto->kw = NULL;
- Py_DECREF(pto);
- return NULL;
- }
- if (kw != NULL) {
- pto->kw = PyDict_Copy(kw);
- if (pto->kw == NULL) {
- Py_DECREF(pto);
- return NULL;
- }
- } else {
- pto->kw = Py_None;
- Py_INCREF(Py_None);
- }
-
- pto->weakreflist = NULL;
- pto->dict = NULL;
-
- return (PyObject *)pto;
+ PyObject *func;
+ partialobject *pto;
+
+ if (PyTuple_GET_SIZE(args) < 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "type 'partial' takes at least one argument");
+ return NULL;
+ }
+
+ func = PyTuple_GET_ITEM(args, 0);
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the first argument must be callable");
+ return NULL;
+ }
+
+ /* create partialobject structure */
+ pto = (partialobject *)type->tp_alloc(type, 0);
+ if (pto == NULL)
+ return NULL;
+
+ pto->fn = func;
+ Py_INCREF(func);
+ pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
+ if (pto->args == NULL) {
+ pto->kw = NULL;
+ Py_DECREF(pto);
+ return NULL;
+ }
+ if (kw != NULL) {
+ pto->kw = PyDict_Copy(kw);
+ if (pto->kw == NULL) {
+ Py_DECREF(pto);
+ return NULL;
+ }
+ } else {
+ pto->kw = Py_None;
+ Py_INCREF(Py_None);
+ }
+
+ pto->weakreflist = NULL;
+ pto->dict = NULL;
+
+ return (PyObject *)pto;
}
static void
partial_dealloc(partialobject *pto)
{
- PyObject_GC_UnTrack(pto);
- if (pto->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) pto);
- Py_XDECREF(pto->fn);
- Py_XDECREF(pto->args);
- Py_XDECREF(pto->kw);
- Py_XDECREF(pto->dict);
- Py_TYPE(pto)->tp_free(pto);
+ PyObject_GC_UnTrack(pto);
+ if (pto->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) pto);
+ Py_XDECREF(pto->fn);
+ Py_XDECREF(pto->args);
+ Py_XDECREF(pto->kw);
+ Py_XDECREF(pto->dict);
+ Py_TYPE(pto)->tp_free(pto);
}
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
- PyObject *ret;
- PyObject *argappl = NULL, *kwappl = NULL;
-
- assert (PyCallable_Check(pto->fn));
- assert (PyTuple_Check(pto->args));
- assert (pto->kw == Py_None || PyDict_Check(pto->kw));
-
- if (PyTuple_GET_SIZE(pto->args) == 0) {
- argappl = args;
- Py_INCREF(args);
- } else if (PyTuple_GET_SIZE(args) == 0) {
- argappl = pto->args;
- Py_INCREF(pto->args);
- } else {
- argappl = PySequence_Concat(pto->args, args);
- if (argappl == NULL)
- return NULL;
- }
-
- if (pto->kw == Py_None) {
- kwappl = kw;
- Py_XINCREF(kw);
- } else {
- kwappl = PyDict_Copy(pto->kw);
- if (kwappl == NULL) {
- Py_DECREF(argappl);
- return NULL;
- }
- if (kw != NULL) {
- if (PyDict_Merge(kwappl, kw, 1) != 0) {
- Py_DECREF(argappl);
- Py_DECREF(kwappl);
- return NULL;
- }
- }
- }
-
- ret = PyObject_Call(pto->fn, argappl, kwappl);
- Py_DECREF(argappl);
- Py_XDECREF(kwappl);
- return ret;
+ PyObject *ret;
+ PyObject *argappl = NULL, *kwappl = NULL;
+
+ assert (PyCallable_Check(pto->fn));
+ assert (PyTuple_Check(pto->args));
+ assert (pto->kw == Py_None || PyDict_Check(pto->kw));
+
+ if (PyTuple_GET_SIZE(pto->args) == 0) {
+ argappl = args;
+ Py_INCREF(args);
+ } else if (PyTuple_GET_SIZE(args) == 0) {
+ argappl = pto->args;
+ Py_INCREF(pto->args);
+ } else {
+ argappl = PySequence_Concat(pto->args, args);
+ if (argappl == NULL)
+ return NULL;
+ }
+
+ if (pto->kw == Py_None) {
+ kwappl = kw;
+ Py_XINCREF(kw);
+ } else {
+ kwappl = PyDict_Copy(pto->kw);
+ if (kwappl == NULL) {
+ Py_DECREF(argappl);
+ return NULL;
+ }
+ if (kw != NULL) {
+ if (PyDict_Merge(kwappl, kw, 1) != 0) {
+ Py_DECREF(argappl);
+ Py_DECREF(kwappl);
+ return NULL;
+ }
+ }
+ }
+
+ ret = PyObject_Call(pto->fn, argappl, kwappl);
+ Py_DECREF(argappl);
+ Py_XDECREF(kwappl);
+ return ret;
}
static int
partial_traverse(partialobject *pto, visitproc visit, void *arg)
{
- Py_VISIT(pto->fn);
- Py_VISIT(pto->args);
- Py_VISIT(pto->kw);
- Py_VISIT(pto->dict);
- return 0;
+ Py_VISIT(pto->fn);
+ Py_VISIT(pto->args);
+ Py_VISIT(pto->kw);
+ Py_VISIT(pto->dict);
+ return 0;
}
PyDoc_STRVAR(partial_doc,
"partial(func, *args, **keywords) - new function with partial application\n\
- of the given arguments and keywords.\n");
+ of the given arguments and keywords.\n");
#define OFF(x) offsetof(partialobject, x)
static PyMemberDef partial_memberlist[] = {
- {"func", T_OBJECT, OFF(fn), READONLY,
- "function object to use in future partial calls"},
- {"args", T_OBJECT, OFF(args), READONLY,
- "tuple of arguments to future partial calls"},
- {"keywords", T_OBJECT, OFF(kw), READONLY,
- "dictionary of keyword arguments to future partial calls"},
- {NULL} /* Sentinel */
+ {"func", T_OBJECT, OFF(fn), READONLY,
+ "function object to use in future partial calls"},
+ {"args", T_OBJECT, OFF(args), READONLY,
+ "tuple of arguments to future partial calls"},
+ {"keywords", T_OBJECT, OFF(kw), READONLY,
+ "dictionary of keyword arguments to future partial calls"},
+ {NULL} /* Sentinel */
};
static PyObject *
partial_get_dict(partialobject *pto)
{
- if (pto->dict == NULL) {
- pto->dict = PyDict_New();
- if (pto->dict == NULL)
- return NULL;
- }
- Py_INCREF(pto->dict);
- return pto->dict;
+ if (pto->dict == NULL) {
+ pto->dict = PyDict_New();
+ if (pto->dict == NULL)
+ return NULL;
+ }
+ Py_INCREF(pto->dict);
+ return pto->dict;
}
static int
partial_set_dict(partialobject *pto, PyObject *value)
{
- PyObject *tmp;
-
- /* It is illegal to del p.__dict__ */
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "a partial object's dictionary may not be deleted");
- return -1;
- }
- /* Can only set __dict__ to a dictionary */
- if (!PyDict_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "setting partial object's dictionary to a non-dict");
- return -1;
- }
- tmp = pto->dict;
- Py_INCREF(value);
- pto->dict = value;
- Py_XDECREF(tmp);
- return 0;
+ PyObject *tmp;
+
+ /* It is illegal to del p.__dict__ */
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "a partial object's dictionary may not be deleted");
+ return -1;
+ }
+ /* Can only set __dict__ to a dictionary */
+ if (!PyDict_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "setting partial object's dictionary to a non-dict");
+ return -1;
+ }
+ tmp = pto->dict;
+ Py_INCREF(value);
+ pto->dict = value;
+ Py_XDECREF(tmp);
+ return 0;
}
static PyGetSetDef partial_getsetlist[] = {
- {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict},
- {NULL} /* Sentinel */
+ {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict},
+ {NULL} /* Sentinel */
};
/* Pickle strategy:
@@ -206,85 +206,85 @@ static PyGetSetDef partial_getsetlist[] = {
static PyObject *
partial_reduce(partialobject *pto, PyObject *unused)
{
- return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
- pto->args, pto->kw,
- pto->dict ? pto->dict : Py_None);
+ return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
+ pto->args, pto->kw,
+ pto->dict ? pto->dict : Py_None);
}
static PyObject *
partial_setstate(partialobject *pto, PyObject *args)
{
- PyObject *fn, *fnargs, *kw, *dict;
- if (!PyArg_ParseTuple(args, "(OOOO):__setstate__",
- &fn, &fnargs, &kw, &dict))
- return NULL;
- Py_XDECREF(pto->fn);
- Py_XDECREF(pto->args);
- Py_XDECREF(pto->kw);
- Py_XDECREF(pto->dict);
- pto->fn = fn;
- pto->args = fnargs;
- pto->kw = kw;
- if (dict != Py_None) {
- pto->dict = dict;
- Py_INCREF(dict);
- } else {
- pto->dict = NULL;
- }
- Py_INCREF(fn);
- Py_INCREF(fnargs);
- Py_INCREF(kw);
- Py_RETURN_NONE;
+ PyObject *fn, *fnargs, *kw, *dict;
+ if (!PyArg_ParseTuple(args, "(OOOO):__setstate__",
+ &fn, &fnargs, &kw, &dict))
+ return NULL;
+ Py_XDECREF(pto->fn);
+ Py_XDECREF(pto->args);
+ Py_XDECREF(pto->kw);
+ Py_XDECREF(pto->dict);
+ pto->fn = fn;
+ pto->args = fnargs;
+ pto->kw = kw;
+ if (dict != Py_None) {
+ pto->dict = dict;
+ Py_INCREF(dict);
+ } else {
+ pto->dict = NULL;
+ }
+ Py_INCREF(fn);
+ Py_INCREF(fnargs);
+ Py_INCREF(kw);
+ Py_RETURN_NONE;
}
static PyMethodDef partial_methods[] = {
- {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
- {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
+ {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject partial_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "functools.partial", /* tp_name */
- sizeof(partialobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)partial_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)partial_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- partial_doc, /* tp_doc */
- (traverseproc)partial_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- partial_methods, /* tp_methods */
- partial_memberlist, /* tp_members */
- partial_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- offsetof(partialobject, dict), /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- partial_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "functools.partial", /* tp_name */
+ sizeof(partialobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)partial_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)partial_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ partial_doc, /* tp_doc */
+ (traverseproc)partial_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ partial_methods, /* tp_methods */
+ partial_memberlist, /* tp_members */
+ partial_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ offsetof(partialobject, dict), /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ partial_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -293,64 +293,64 @@ static PyTypeObject partial_type = {
static PyObject *
functools_reduce(PyObject *self, PyObject *args)
{
- PyObject *seq, *func, *result = NULL, *it;
-
- if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
- return NULL;
- if (result != NULL)
- Py_INCREF(result);
-
- it = PyObject_GetIter(seq);
- if (it == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "reduce() arg 2 must support iteration");
- Py_XDECREF(result);
- return NULL;
- }
-
- if ((args = PyTuple_New(2)) == NULL)
- goto Fail;
-
- for (;;) {
- PyObject *op2;
-
- if (args->ob_refcnt > 1) {
- Py_DECREF(args);
- if ((args = PyTuple_New(2)) == NULL)
- goto Fail;
- }
-
- op2 = PyIter_Next(it);
- if (op2 == NULL) {
- if (PyErr_Occurred())
- goto Fail;
- break;
- }
-
- if (result == NULL)
- result = op2;
- else {
- PyTuple_SetItem(args, 0, result);
- PyTuple_SetItem(args, 1, op2);
- if ((result = PyEval_CallObject(func, args)) == NULL)
- goto Fail;
- }
- }
-
- Py_DECREF(args);
-
- if (result == NULL)
- PyErr_SetString(PyExc_TypeError,
- "reduce() of empty sequence with no initial value");
-
- Py_DECREF(it);
- return result;
+ PyObject *seq, *func, *result = NULL, *it;
+
+ if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
+ return NULL;
+ if (result != NULL)
+ Py_INCREF(result);
+
+ it = PyObject_GetIter(seq);
+ if (it == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "reduce() arg 2 must support iteration");
+ Py_XDECREF(result);
+ return NULL;
+ }
+
+ if ((args = PyTuple_New(2)) == NULL)
+ goto Fail;
+
+ for (;;) {
+ PyObject *op2;
+
+ if (args->ob_refcnt > 1) {
+ Py_DECREF(args);
+ if ((args = PyTuple_New(2)) == NULL)
+ goto Fail;
+ }
+
+ op2 = PyIter_Next(it);
+ if (op2 == NULL) {
+ if (PyErr_Occurred())
+ goto Fail;
+ break;
+ }
+
+ if (result == NULL)
+ result = op2;
+ else {
+ PyTuple_SetItem(args, 0, result);
+ PyTuple_SetItem(args, 1, op2);
+ if ((result = PyEval_CallObject(func, args)) == NULL)
+ goto Fail;
+ }
+ }
+
+ Py_DECREF(args);
+
+ if (result == NULL)
+ PyErr_SetString(PyExc_TypeError,
+ "reduce() of empty sequence with no initial value");
+
+ Py_DECREF(it);
+ return result;
Fail:
- Py_XDECREF(args);
- Py_XDECREF(result);
- Py_DECREF(it);
- return NULL;
+ Py_XDECREF(args);
+ Py_XDECREF(result);
+ Py_DECREF(it);
+ return NULL;
}
PyDoc_STRVAR(functools_reduce_doc,
@@ -369,47 +369,47 @@ PyDoc_STRVAR(module_doc,
"Tools that operate on functions.");
static PyMethodDef module_methods[] = {
- {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
- {NULL, NULL} /* sentinel */
+ {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef _functoolsmodule = {
- PyModuleDef_HEAD_INIT,
- "_functools",
- module_doc,
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_functools",
+ module_doc,
+ -1,
+ module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__functools(void)
{
- int i;
- PyObject *m;
- char *name;
- PyTypeObject *typelist[] = {
- &partial_type,
- NULL
- };
-
- m = PyModule_Create(&_functoolsmodule);
- if (m == NULL)
- return NULL;
-
- for (i=0 ; typelist[i] != NULL ; i++) {
- if (PyType_Ready(typelist[i]) < 0) {
- Py_DECREF(m);
- return NULL;
- }
- name = strchr(typelist[i]->tp_name, '.');
- assert (name != NULL);
- Py_INCREF(typelist[i]);
- PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
- }
- return m;
+ int i;
+ PyObject *m;
+ char *name;
+ PyTypeObject *typelist[] = {
+ &partial_type,
+ NULL
+ };
+
+ m = PyModule_Create(&_functoolsmodule);
+ if (m == NULL)
+ return NULL;
+
+ for (i=0 ; typelist[i] != NULL ; i++) {
+ if (PyType_Ready(typelist[i]) < 0) {
+ Py_DECREF(m);
+ return NULL;
+ }
+ name = strchr(typelist[i]->tp_name, '.');
+ assert (name != NULL);
+ Py_INCREF(typelist[i]);
+ PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
+ }
+ return m;
}
diff --git a/Modules/_gdbmmodule.c b/Modules/_gdbmmodule.c
index de453ac..f15fefd 100644
--- a/Modules/_gdbmmodule.c
+++ b/Modules/_gdbmmodule.c
@@ -30,7 +30,7 @@ supported.");
typedef struct {
PyObject_HEAD
- int di_size; /* -1 means recompute */
+ int di_size; /* -1 means recompute */
GDBM_FILE di_dbm;
} dbmobject;
@@ -177,7 +177,7 @@ dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
}
static PyMappingMethods dbm_as_mapping = {
- (lenfunc)dbm_length, /*mp_length*/
+ (lenfunc)dbm_length, /*mp_length*/
(binaryfunc)dbm_subscript, /*mp_subscript*/
(objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
};
@@ -247,15 +247,15 @@ dbm_contains(PyObject *self, PyObject *arg)
datum key;
if ((dp)->di_dbm == NULL) {
- PyErr_SetString(DbmError,
- "GDBM object has already been closed");
- return -1;
+ PyErr_SetString(DbmError,
+ "GDBM object has already been closed");
+ return -1;
}
if (!PyBytes_Check(arg)) {
- PyErr_Format(PyExc_TypeError,
- "gdbm key must be bytes, not %.100s",
- arg->ob_type->tp_name);
- return -1;
+ PyErr_Format(PyExc_TypeError,
+ "gdbm key must be bytes, not %.100s",
+ arg->ob_type->tp_name);
+ return -1;
}
key.dptr = PyBytes_AS_STRING(arg);
key.dsize = PyBytes_GET_SIZE(arg);
@@ -263,16 +263,16 @@ dbm_contains(PyObject *self, PyObject *arg)
}
static PySequenceMethods dbm_as_sequence = {
- 0, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- dbm_contains, /* sq_contains */
- 0, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ dbm_contains, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
PyDoc_STRVAR(dbm_firstkey__doc__,
@@ -372,13 +372,13 @@ dbm_sync(register dbmobject *dp, PyObject *unused)
}
static PyMethodDef dbm_methods[] = {
- {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__},
- {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__},
+ {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__},
+ {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__},
{"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__},
- {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__},
+ {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__},
{"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__},
{"sync", (PyCFunction)dbm_sync, METH_NOARGS, dbm_sync__doc__},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject Dbmtype = {
@@ -486,7 +486,7 @@ dbmopen(PyObject *self, PyObject *args)
#endif
default:
PyOS_snprintf(buf, sizeof(buf), "Flag '%c' is not supported.",
- *flags);
+ *flags);
PyErr_SetString(DbmError, buf);
return NULL;
}
@@ -514,15 +514,15 @@ static PyMethodDef dbmmodule_methods[] = {
static struct PyModuleDef _gdbmmodule = {
- PyModuleDef_HEAD_INIT,
- "_gdbm",
- gdbmmodule__doc__,
- -1,
- dbmmodule_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_gdbm",
+ gdbmmodule__doc__,
+ -1,
+ dbmmodule_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -530,10 +530,10 @@ PyInit__gdbm(void) {
PyObject *m, *d, *s;
if (PyType_Ready(&Dbmtype) < 0)
- return NULL;
+ return NULL;
m = PyModule_Create(&_gdbmmodule);
if (m == NULL)
- return NULL;
+ return NULL;
d = PyModule_GetDict(m);
DbmError = PyErr_NewException("_gdbm.error", PyExc_IOError, NULL);
if (DbmError != NULL) {
diff --git a/Modules/_gestalt.c b/Modules/_gestalt.c
index 462a6d2..a45780f 100644
--- a/Modules/_gestalt.c
+++ b/Modules/_gestalt.c
@@ -4,10 +4,10 @@ The Netherlands.
All Rights Reserved
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
+both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
@@ -34,9 +34,9 @@ convert_to_OSType(PyObject *v, OSType *pr)
{
uint32_t tmp;
if (!PyUnicode_Check(v) || PyUnicode_GetSize(v) != 4) {
- PyErr_SetString(PyExc_TypeError,
- "OSType arg must be string of 4 chars");
- return 0;
+ PyErr_SetString(PyExc_TypeError,
+ "OSType arg must be string of 4 chars");
+ return 0;
}
memcpy((char *)&tmp, _PyUnicode_AsString(v), 4);
*pr = (OSType)ntohl(tmp);
@@ -50,12 +50,12 @@ gestalt_gestalt(PyObject *self, PyObject *args)
OSType selector;
SInt32 response;
if (!PyArg_ParseTuple(args, "O&", convert_to_OSType, &selector))
- return NULL;
+ return NULL;
iErr = Gestalt(selector, &response);
if (iErr != 0) {
- PyErr_SetString(PyExc_OSError,
- "non-zero exit code!");
- return NULL;
+ PyErr_SetString(PyExc_OSError,
+ "non-zero exit code!");
+ return NULL;
}
return PyLong_FromLong(response);
}
@@ -66,19 +66,19 @@ static struct PyMethodDef gestalt_methods[] = {
};
static struct PyModuleDef gestaltmodule = {
- PyModuleDef_HEAD_INIT,
- "_gestalt",
- NULL,
- -1,
- gestalt_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_gestalt",
+ NULL,
+ -1,
+ gestalt_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__gestalt(void)
{
- return PyModule_Create(&gestaltmodule);
+ return PyModule_Create(&gestaltmodule);
}
diff --git a/Modules/_heapqmodule.c b/Modules/_heapqmodule.c
index 7921823..366fb3d 100644
--- a/Modules/_heapqmodule.c
+++ b/Modules/_heapqmodule.c
@@ -1,4 +1,4 @@
-/* Drop in replacement for heapq.py
+/* Drop in replacement for heapq.py
C implementation derived directly from heapq.py in Py2.3
which was written by Kevin O'Connor, augmented by Tim Peters,
@@ -11,115 +11,115 @@ annotated by François Pinard, and converted to C by Raymond Hettinger.
static int
cmp_lt(PyObject *x, PyObject *y)
{
- return PyObject_RichCompareBool(x, y, Py_LT);
+ return PyObject_RichCompareBool(x, y, Py_LT);
}
static int
_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
- PyObject *newitem, *parent;
- int cmp;
- Py_ssize_t parentpos;
-
- assert(PyList_Check(heap));
- if (pos >= PyList_GET_SIZE(heap)) {
- PyErr_SetString(PyExc_IndexError, "index out of range");
- return -1;
- }
-
- newitem = PyList_GET_ITEM(heap, pos);
- Py_INCREF(newitem);
- /* Follow the path to the root, moving parents down until finding
- a place newitem fits. */
- while (pos > startpos){
- parentpos = (pos - 1) >> 1;
- parent = PyList_GET_ITEM(heap, parentpos);
- cmp = cmp_lt(newitem, parent);
- if (cmp == -1) {
- Py_DECREF(newitem);
- return -1;
- }
- if (cmp == 0)
- break;
- Py_INCREF(parent);
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, parent);
- pos = parentpos;
- }
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, newitem);
- return 0;
+ PyObject *newitem, *parent;
+ int cmp;
+ Py_ssize_t parentpos;
+
+ assert(PyList_Check(heap));
+ if (pos >= PyList_GET_SIZE(heap)) {
+ PyErr_SetString(PyExc_IndexError, "index out of range");
+ return -1;
+ }
+
+ newitem = PyList_GET_ITEM(heap, pos);
+ Py_INCREF(newitem);
+ /* Follow the path to the root, moving parents down until finding
+ a place newitem fits. */
+ while (pos > startpos){
+ parentpos = (pos - 1) >> 1;
+ parent = PyList_GET_ITEM(heap, parentpos);
+ cmp = cmp_lt(newitem, parent);
+ if (cmp == -1) {
+ Py_DECREF(newitem);
+ return -1;
+ }
+ if (cmp == 0)
+ break;
+ Py_INCREF(parent);
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, parent);
+ pos = parentpos;
+ }
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, newitem);
+ return 0;
}
static int
_siftup(PyListObject *heap, Py_ssize_t pos)
{
- Py_ssize_t startpos, endpos, childpos, rightpos;
- int cmp;
- PyObject *newitem, *tmp;
-
- assert(PyList_Check(heap));
- endpos = PyList_GET_SIZE(heap);
- startpos = pos;
- if (pos >= endpos) {
- PyErr_SetString(PyExc_IndexError, "index out of range");
- return -1;
- }
- newitem = PyList_GET_ITEM(heap, pos);
- Py_INCREF(newitem);
-
- /* Bubble up the smaller child until hitting a leaf. */
- childpos = 2*pos + 1; /* leftmost child position */
- while (childpos < endpos) {
- /* Set childpos to index of smaller child. */
- rightpos = childpos + 1;
- if (rightpos < endpos) {
- cmp = cmp_lt(
- PyList_GET_ITEM(heap, childpos),
- PyList_GET_ITEM(heap, rightpos));
- if (cmp == -1) {
- Py_DECREF(newitem);
- return -1;
- }
- if (cmp == 0)
- childpos = rightpos;
- }
- /* Move the smaller child up. */
- tmp = PyList_GET_ITEM(heap, childpos);
- Py_INCREF(tmp);
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, tmp);
- pos = childpos;
- childpos = 2*pos + 1;
- }
-
- /* The leaf at pos is empty now. Put newitem there, and and bubble
- it up to its final resting place (by sifting its parents down). */
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, newitem);
- return _siftdown(heap, startpos, pos);
+ Py_ssize_t startpos, endpos, childpos, rightpos;
+ int cmp;
+ PyObject *newitem, *tmp;
+
+ assert(PyList_Check(heap));
+ endpos = PyList_GET_SIZE(heap);
+ startpos = pos;
+ if (pos >= endpos) {
+ PyErr_SetString(PyExc_IndexError, "index out of range");
+ return -1;
+ }
+ newitem = PyList_GET_ITEM(heap, pos);
+ Py_INCREF(newitem);
+
+ /* Bubble up the smaller child until hitting a leaf. */
+ childpos = 2*pos + 1; /* leftmost child position */
+ while (childpos < endpos) {
+ /* Set childpos to index of smaller child. */
+ rightpos = childpos + 1;
+ if (rightpos < endpos) {
+ cmp = cmp_lt(
+ PyList_GET_ITEM(heap, childpos),
+ PyList_GET_ITEM(heap, rightpos));
+ if (cmp == -1) {
+ Py_DECREF(newitem);
+ return -1;
+ }
+ if (cmp == 0)
+ childpos = rightpos;
+ }
+ /* Move the smaller child up. */
+ tmp = PyList_GET_ITEM(heap, childpos);
+ Py_INCREF(tmp);
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, tmp);
+ pos = childpos;
+ childpos = 2*pos + 1;
+ }
+
+ /* The leaf at pos is empty now. Put newitem there, and and bubble
+ it up to its final resting place (by sifting its parents down). */
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, newitem);
+ return _siftdown(heap, startpos, pos);
}
static PyObject *
heappush(PyObject *self, PyObject *args)
{
- PyObject *heap, *item;
+ PyObject *heap, *item;
- if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
+ return NULL;
- if (!PyList_Check(heap)) {
- PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
- return NULL;
- }
+ if (!PyList_Check(heap)) {
+ PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
+ return NULL;
+ }
- if (PyList_Append(heap, item) == -1)
- return NULL;
+ if (PyList_Append(heap, item) == -1)
+ return NULL;
- if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(heappush_doc,
@@ -128,35 +128,35 @@ PyDoc_STRVAR(heappush_doc,
static PyObject *
heappop(PyObject *self, PyObject *heap)
{
- PyObject *lastelt, *returnitem;
- Py_ssize_t n;
-
- if (!PyList_Check(heap)) {
- PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
- return NULL;
- }
-
- /* # raises appropriate IndexError if heap is empty */
- n = PyList_GET_SIZE(heap);
- if (n == 0) {
- PyErr_SetString(PyExc_IndexError, "index out of range");
- return NULL;
- }
-
- lastelt = PyList_GET_ITEM(heap, n-1) ;
- Py_INCREF(lastelt);
- PyList_SetSlice(heap, n-1, n, NULL);
- n--;
-
- if (!n)
- return lastelt;
- returnitem = PyList_GET_ITEM(heap, 0);
- PyList_SET_ITEM(heap, 0, lastelt);
- if (_siftup((PyListObject *)heap, 0) == -1) {
- Py_DECREF(returnitem);
- return NULL;
- }
- return returnitem;
+ PyObject *lastelt, *returnitem;
+ Py_ssize_t n;
+
+ if (!PyList_Check(heap)) {
+ PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
+ return NULL;
+ }
+
+ /* # raises appropriate IndexError if heap is empty */
+ n = PyList_GET_SIZE(heap);
+ if (n == 0) {
+ PyErr_SetString(PyExc_IndexError, "index out of range");
+ return NULL;
+ }
+
+ lastelt = PyList_GET_ITEM(heap, n-1) ;
+ Py_INCREF(lastelt);
+ PyList_SetSlice(heap, n-1, n, NULL);
+ n--;
+
+ if (!n)
+ return lastelt;
+ returnitem = PyList_GET_ITEM(heap, 0);
+ PyList_SET_ITEM(heap, 0, lastelt);
+ if (_siftup((PyListObject *)heap, 0) == -1) {
+ Py_DECREF(returnitem);
+ return NULL;
+ }
+ return returnitem;
}
PyDoc_STRVAR(heappop_doc,
@@ -165,29 +165,29 @@ PyDoc_STRVAR(heappop_doc,
static PyObject *
heapreplace(PyObject *self, PyObject *args)
{
- PyObject *heap, *item, *returnitem;
-
- if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
- return NULL;
-
- if (!PyList_Check(heap)) {
- PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
- return NULL;
- }
-
- if (PyList_GET_SIZE(heap) < 1) {
- PyErr_SetString(PyExc_IndexError, "index out of range");
- return NULL;
- }
-
- returnitem = PyList_GET_ITEM(heap, 0);
- Py_INCREF(item);
- PyList_SET_ITEM(heap, 0, item);
- if (_siftup((PyListObject *)heap, 0) == -1) {
- Py_DECREF(returnitem);
- return NULL;
- }
- return returnitem;
+ PyObject *heap, *item, *returnitem;
+
+ if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
+ return NULL;
+
+ if (!PyList_Check(heap)) {
+ PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
+ return NULL;
+ }
+
+ if (PyList_GET_SIZE(heap) < 1) {
+ PyErr_SetString(PyExc_IndexError, "index out of range");
+ return NULL;
+ }
+
+ returnitem = PyList_GET_ITEM(heap, 0);
+ Py_INCREF(item);
+ PyList_SET_ITEM(heap, 0, item);
+ if (_siftup((PyListObject *)heap, 0) == -1) {
+ Py_DECREF(returnitem);
+ return NULL;
+ }
+ return returnitem;
}
PyDoc_STRVAR(heapreplace_doc,
@@ -197,44 +197,44 @@ This is more efficient than heappop() followed by heappush(), and can be\n\
more appropriate when using a fixed-size heap. Note that the value\n\
returned may be larger than item! That constrains reasonable uses of\n\
this routine unless written as part of a conditional replacement:\n\n\
- if item > heap[0]:\n\
- item = heapreplace(heap, item)\n");
+ if item > heap[0]:\n\
+ item = heapreplace(heap, item)\n");
static PyObject *
heappushpop(PyObject *self, PyObject *args)
{
- PyObject *heap, *item, *returnitem;
- int cmp;
-
- if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
- return NULL;
-
- if (!PyList_Check(heap)) {
- PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
- return NULL;
- }
-
- if (PyList_GET_SIZE(heap) < 1) {
- Py_INCREF(item);
- return item;
- }
-
- cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
- if (cmp == -1)
- return NULL;
- if (cmp == 0) {
- Py_INCREF(item);
- return item;
- }
-
- returnitem = PyList_GET_ITEM(heap, 0);
- Py_INCREF(item);
- PyList_SET_ITEM(heap, 0, item);
- if (_siftup((PyListObject *)heap, 0) == -1) {
- Py_DECREF(returnitem);
- return NULL;
- }
- return returnitem;
+ PyObject *heap, *item, *returnitem;
+ int cmp;
+
+ if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
+ return NULL;
+
+ if (!PyList_Check(heap)) {
+ PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
+ return NULL;
+ }
+
+ if (PyList_GET_SIZE(heap) < 1) {
+ Py_INCREF(item);
+ return item;
+ }
+
+ cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
+ if (cmp == -1)
+ return NULL;
+ if (cmp == 0) {
+ Py_INCREF(item);
+ return item;
+ }
+
+ returnitem = PyList_GET_ITEM(heap, 0);
+ Py_INCREF(item);
+ PyList_SET_ITEM(heap, 0, item);
+ if (_siftup((PyListObject *)heap, 0) == -1) {
+ Py_DECREF(returnitem);
+ return NULL;
+ }
+ return returnitem;
}
PyDoc_STRVAR(heappushpop_doc,
@@ -245,26 +245,26 @@ heappush() followed by a separate call to heappop().");
static PyObject *
heapify(PyObject *self, PyObject *heap)
{
- Py_ssize_t i, n;
-
- if (!PyList_Check(heap)) {
- PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
- return NULL;
- }
-
- n = PyList_GET_SIZE(heap);
- /* Transform bottom-up. The largest index there's any point to
- looking at is the largest with a child index in-range, so must
- have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
- (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
- n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
- and that's again n//2-1.
- */
- for (i=n/2-1 ; i>=0 ; i--)
- if(_siftup((PyListObject *)heap, i) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t i, n;
+
+ if (!PyList_Check(heap)) {
+ PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
+ return NULL;
+ }
+
+ n = PyList_GET_SIZE(heap);
+ /* Transform bottom-up. The largest index there's any point to
+ looking at is the largest with a child index in-range, so must
+ have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
+ (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
+ n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
+ and that's again n//2-1.
+ */
+ for (i=n/2-1 ; i>=0 ; i--)
+ if(_siftup((PyListObject *)heap, i) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(heapify_doc,
@@ -273,79 +273,79 @@ PyDoc_STRVAR(heapify_doc,
static PyObject *
nlargest(PyObject *self, PyObject *args)
{
- PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
- Py_ssize_t i, n;
- int cmp;
-
- if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
- return NULL;
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- heap = PyList_New(0);
- if (heap == NULL)
- goto fail;
-
- for (i=0 ; i<n ; i++ ){
- elem = PyIter_Next(it);
- if (elem == NULL) {
- if (PyErr_Occurred())
- goto fail;
- else
- goto sortit;
- }
- if (PyList_Append(heap, elem) == -1) {
- Py_DECREF(elem);
- goto fail;
- }
- Py_DECREF(elem);
- }
- if (PyList_GET_SIZE(heap) == 0)
- goto sortit;
-
- for (i=n/2-1 ; i>=0 ; i--)
- if(_siftup((PyListObject *)heap, i) == -1)
- goto fail;
-
- sol = PyList_GET_ITEM(heap, 0);
- while (1) {
- elem = PyIter_Next(it);
- if (elem == NULL) {
- if (PyErr_Occurred())
- goto fail;
- else
- goto sortit;
- }
- cmp = cmp_lt(sol, elem);
- if (cmp == -1) {
- Py_DECREF(elem);
- goto fail;
- }
- if (cmp == 0) {
- Py_DECREF(elem);
- continue;
- }
- oldelem = PyList_GET_ITEM(heap, 0);
- PyList_SET_ITEM(heap, 0, elem);
- Py_DECREF(oldelem);
- if (_siftup((PyListObject *)heap, 0) == -1)
- goto fail;
- sol = PyList_GET_ITEM(heap, 0);
- }
+ PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
+ Py_ssize_t i, n;
+ int cmp;
+
+ if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
+ return NULL;
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ heap = PyList_New(0);
+ if (heap == NULL)
+ goto fail;
+
+ for (i=0 ; i<n ; i++ ){
+ elem = PyIter_Next(it);
+ if (elem == NULL) {
+ if (PyErr_Occurred())
+ goto fail;
+ else
+ goto sortit;
+ }
+ if (PyList_Append(heap, elem) == -1) {
+ Py_DECREF(elem);
+ goto fail;
+ }
+ Py_DECREF(elem);
+ }
+ if (PyList_GET_SIZE(heap) == 0)
+ goto sortit;
+
+ for (i=n/2-1 ; i>=0 ; i--)
+ if(_siftup((PyListObject *)heap, i) == -1)
+ goto fail;
+
+ sol = PyList_GET_ITEM(heap, 0);
+ while (1) {
+ elem = PyIter_Next(it);
+ if (elem == NULL) {
+ if (PyErr_Occurred())
+ goto fail;
+ else
+ goto sortit;
+ }
+ cmp = cmp_lt(sol, elem);
+ if (cmp == -1) {
+ Py_DECREF(elem);
+ goto fail;
+ }
+ if (cmp == 0) {
+ Py_DECREF(elem);
+ continue;
+ }
+ oldelem = PyList_GET_ITEM(heap, 0);
+ PyList_SET_ITEM(heap, 0, elem);
+ Py_DECREF(oldelem);
+ if (_siftup((PyListObject *)heap, 0) == -1)
+ goto fail;
+ sol = PyList_GET_ITEM(heap, 0);
+ }
sortit:
- if (PyList_Sort(heap) == -1)
- goto fail;
- if (PyList_Reverse(heap) == -1)
- goto fail;
- Py_DECREF(it);
- return heap;
+ if (PyList_Sort(heap) == -1)
+ goto fail;
+ if (PyList_Reverse(heap) == -1)
+ goto fail;
+ Py_DECREF(it);
+ return heap;
fail:
- Py_DECREF(it);
- Py_XDECREF(heap);
- return NULL;
+ Py_DECREF(it);
+ Py_XDECREF(heap);
+ return NULL;
}
PyDoc_STRVAR(nlargest_doc,
@@ -356,166 +356,166 @@ Equivalent to: sorted(iterable, reverse=True)[:n]\n");
static int
_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
- PyObject *newitem, *parent;
- int cmp;
- Py_ssize_t parentpos;
-
- assert(PyList_Check(heap));
- if (pos >= PyList_GET_SIZE(heap)) {
- PyErr_SetString(PyExc_IndexError, "index out of range");
- return -1;
- }
-
- newitem = PyList_GET_ITEM(heap, pos);
- Py_INCREF(newitem);
- /* Follow the path to the root, moving parents down until finding
- a place newitem fits. */
- while (pos > startpos){
- parentpos = (pos - 1) >> 1;
- parent = PyList_GET_ITEM(heap, parentpos);
- cmp = cmp_lt(parent, newitem);
- if (cmp == -1) {
- Py_DECREF(newitem);
- return -1;
- }
- if (cmp == 0)
- break;
- Py_INCREF(parent);
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, parent);
- pos = parentpos;
- }
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, newitem);
- return 0;
+ PyObject *newitem, *parent;
+ int cmp;
+ Py_ssize_t parentpos;
+
+ assert(PyList_Check(heap));
+ if (pos >= PyList_GET_SIZE(heap)) {
+ PyErr_SetString(PyExc_IndexError, "index out of range");
+ return -1;
+ }
+
+ newitem = PyList_GET_ITEM(heap, pos);
+ Py_INCREF(newitem);
+ /* Follow the path to the root, moving parents down until finding
+ a place newitem fits. */
+ while (pos > startpos){
+ parentpos = (pos - 1) >> 1;
+ parent = PyList_GET_ITEM(heap, parentpos);
+ cmp = cmp_lt(parent, newitem);
+ if (cmp == -1) {
+ Py_DECREF(newitem);
+ return -1;
+ }
+ if (cmp == 0)
+ break;
+ Py_INCREF(parent);
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, parent);
+ pos = parentpos;
+ }
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, newitem);
+ return 0;
}
static int
_siftupmax(PyListObject *heap, Py_ssize_t pos)
{
- Py_ssize_t startpos, endpos, childpos, rightpos;
- int cmp;
- PyObject *newitem, *tmp;
-
- assert(PyList_Check(heap));
- endpos = PyList_GET_SIZE(heap);
- startpos = pos;
- if (pos >= endpos) {
- PyErr_SetString(PyExc_IndexError, "index out of range");
- return -1;
- }
- newitem = PyList_GET_ITEM(heap, pos);
- Py_INCREF(newitem);
-
- /* Bubble up the smaller child until hitting a leaf. */
- childpos = 2*pos + 1; /* leftmost child position */
- while (childpos < endpos) {
- /* Set childpos to index of smaller child. */
- rightpos = childpos + 1;
- if (rightpos < endpos) {
- cmp = cmp_lt(
- PyList_GET_ITEM(heap, rightpos),
- PyList_GET_ITEM(heap, childpos));
- if (cmp == -1) {
- Py_DECREF(newitem);
- return -1;
- }
- if (cmp == 0)
- childpos = rightpos;
- }
- /* Move the smaller child up. */
- tmp = PyList_GET_ITEM(heap, childpos);
- Py_INCREF(tmp);
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, tmp);
- pos = childpos;
- childpos = 2*pos + 1;
- }
-
- /* The leaf at pos is empty now. Put newitem there, and and bubble
- it up to its final resting place (by sifting its parents down). */
- Py_DECREF(PyList_GET_ITEM(heap, pos));
- PyList_SET_ITEM(heap, pos, newitem);
- return _siftdownmax(heap, startpos, pos);
+ Py_ssize_t startpos, endpos, childpos, rightpos;
+ int cmp;
+ PyObject *newitem, *tmp;
+
+ assert(PyList_Check(heap));
+ endpos = PyList_GET_SIZE(heap);
+ startpos = pos;
+ if (pos >= endpos) {
+ PyErr_SetString(PyExc_IndexError, "index out of range");
+ return -1;
+ }
+ newitem = PyList_GET_ITEM(heap, pos);
+ Py_INCREF(newitem);
+
+ /* Bubble up the smaller child until hitting a leaf. */
+ childpos = 2*pos + 1; /* leftmost child position */
+ while (childpos < endpos) {
+ /* Set childpos to index of smaller child. */
+ rightpos = childpos + 1;
+ if (rightpos < endpos) {
+ cmp = cmp_lt(
+ PyList_GET_ITEM(heap, rightpos),
+ PyList_GET_ITEM(heap, childpos));
+ if (cmp == -1) {
+ Py_DECREF(newitem);
+ return -1;
+ }
+ if (cmp == 0)
+ childpos = rightpos;
+ }
+ /* Move the smaller child up. */
+ tmp = PyList_GET_ITEM(heap, childpos);
+ Py_INCREF(tmp);
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, tmp);
+ pos = childpos;
+ childpos = 2*pos + 1;
+ }
+
+ /* The leaf at pos is empty now. Put newitem there, and and bubble
+ it up to its final resting place (by sifting its parents down). */
+ Py_DECREF(PyList_GET_ITEM(heap, pos));
+ PyList_SET_ITEM(heap, pos, newitem);
+ return _siftdownmax(heap, startpos, pos);
}
static PyObject *
nsmallest(PyObject *self, PyObject *args)
{
- PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
- Py_ssize_t i, n;
- int cmp;
-
- if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
- return NULL;
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- heap = PyList_New(0);
- if (heap == NULL)
- goto fail;
-
- for (i=0 ; i<n ; i++ ){
- elem = PyIter_Next(it);
- if (elem == NULL) {
- if (PyErr_Occurred())
- goto fail;
- else
- goto sortit;
- }
- if (PyList_Append(heap, elem) == -1) {
- Py_DECREF(elem);
- goto fail;
- }
- Py_DECREF(elem);
- }
- n = PyList_GET_SIZE(heap);
- if (n == 0)
- goto sortit;
-
- for (i=n/2-1 ; i>=0 ; i--)
- if(_siftupmax((PyListObject *)heap, i) == -1)
- goto fail;
-
- los = PyList_GET_ITEM(heap, 0);
- while (1) {
- elem = PyIter_Next(it);
- if (elem == NULL) {
- if (PyErr_Occurred())
- goto fail;
- else
- goto sortit;
- }
- cmp = cmp_lt(elem, los);
- if (cmp == -1) {
- Py_DECREF(elem);
- goto fail;
- }
- if (cmp == 0) {
- Py_DECREF(elem);
- continue;
- }
-
- oldelem = PyList_GET_ITEM(heap, 0);
- PyList_SET_ITEM(heap, 0, elem);
- Py_DECREF(oldelem);
- if (_siftupmax((PyListObject *)heap, 0) == -1)
- goto fail;
- los = PyList_GET_ITEM(heap, 0);
- }
+ PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
+ Py_ssize_t i, n;
+ int cmp;
+
+ if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
+ return NULL;
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ heap = PyList_New(0);
+ if (heap == NULL)
+ goto fail;
+
+ for (i=0 ; i<n ; i++ ){
+ elem = PyIter_Next(it);
+ if (elem == NULL) {
+ if (PyErr_Occurred())
+ goto fail;
+ else
+ goto sortit;
+ }
+ if (PyList_Append(heap, elem) == -1) {
+ Py_DECREF(elem);
+ goto fail;
+ }
+ Py_DECREF(elem);
+ }
+ n = PyList_GET_SIZE(heap);
+ if (n == 0)
+ goto sortit;
+
+ for (i=n/2-1 ; i>=0 ; i--)
+ if(_siftupmax((PyListObject *)heap, i) == -1)
+ goto fail;
+
+ los = PyList_GET_ITEM(heap, 0);
+ while (1) {
+ elem = PyIter_Next(it);
+ if (elem == NULL) {
+ if (PyErr_Occurred())
+ goto fail;
+ else
+ goto sortit;
+ }
+ cmp = cmp_lt(elem, los);
+ if (cmp == -1) {
+ Py_DECREF(elem);
+ goto fail;
+ }
+ if (cmp == 0) {
+ Py_DECREF(elem);
+ continue;
+ }
+
+ oldelem = PyList_GET_ITEM(heap, 0);
+ PyList_SET_ITEM(heap, 0, elem);
+ Py_DECREF(oldelem);
+ if (_siftupmax((PyListObject *)heap, 0) == -1)
+ goto fail;
+ los = PyList_GET_ITEM(heap, 0);
+ }
sortit:
- if (PyList_Sort(heap) == -1)
- goto fail;
- Py_DECREF(it);
- return heap;
+ if (PyList_Sort(heap) == -1)
+ goto fail;
+ Py_DECREF(it);
+ return heap;
fail:
- Py_DECREF(it);
- Py_XDECREF(heap);
- return NULL;
+ Py_DECREF(it);
+ Py_XDECREF(heap);
+ return NULL;
}
PyDoc_STRVAR(nsmallest_doc,
@@ -524,21 +524,21 @@ PyDoc_STRVAR(nsmallest_doc,
Equivalent to: sorted(iterable)[:n]\n");
static PyMethodDef heapq_methods[] = {
- {"heappush", (PyCFunction)heappush,
- METH_VARARGS, heappush_doc},
- {"heappushpop", (PyCFunction)heappushpop,
- METH_VARARGS, heappushpop_doc},
- {"heappop", (PyCFunction)heappop,
- METH_O, heappop_doc},
- {"heapreplace", (PyCFunction)heapreplace,
- METH_VARARGS, heapreplace_doc},
- {"heapify", (PyCFunction)heapify,
- METH_O, heapify_doc},
- {"nlargest", (PyCFunction)nlargest,
- METH_VARARGS, nlargest_doc},
- {"nsmallest", (PyCFunction)nsmallest,
- METH_VARARGS, nsmallest_doc},
- {NULL, NULL} /* sentinel */
+ {"heappush", (PyCFunction)heappush,
+ METH_VARARGS, heappush_doc},
+ {"heappushpop", (PyCFunction)heappushpop,
+ METH_VARARGS, heappushpop_doc},
+ {"heappop", (PyCFunction)heappop,
+ METH_O, heappop_doc},
+ {"heapreplace", (PyCFunction)heapreplace,
+ METH_VARARGS, heapreplace_doc},
+ {"heapify", (PyCFunction)heapify,
+ METH_O, heapify_doc},
+ {"nlargest", (PyCFunction)nlargest,
+ METH_VARARGS, nlargest_doc},
+ {"nsmallest", (PyCFunction)nsmallest,
+ METH_VARARGS, nsmallest_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@@ -668,27 +668,27 @@ From all times, sorting has always been a Great Art! :-)\n");
static struct PyModuleDef _heapqmodule = {
- PyModuleDef_HEAD_INIT,
- "_heapq",
- module_doc,
- -1,
- heapq_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_heapq",
+ module_doc,
+ -1,
+ heapq_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__heapq(void)
{
- PyObject *m, *about;
-
- m = PyModule_Create(&_heapqmodule);
- if (m == NULL)
- return NULL;
- about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
- PyModule_AddObject(m, "__about__", about);
- return m;
+ PyObject *m, *about;
+
+ m = PyModule_Create(&_heapqmodule);
+ if (m == NULL)
+ return NULL;
+ about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
+ PyModule_AddObject(m, "__about__", about);
+ return m;
}
diff --git a/Modules/_json.c b/Modules/_json.c
index e555439..c965176 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -511,7 +511,7 @@ py_scanstring(PyObject* self UNUSED, PyObject *args)
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
- PyErr_Format(PyExc_TypeError,
+ PyErr_Format(PyExc_TypeError,
"first argument must be a string or bytes, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
@@ -1394,7 +1394,7 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
if (PyObject_IsTrue(s->sort_keys)) {
if (code == NULL) {
- code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])",
+ code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])",
"_json.c", Py_eval_input);
if (code == NULL)
goto bail;
@@ -1409,14 +1409,14 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
}
items = PyEval_EvalCode((PyCodeObject *)code, PyEval_GetGlobals(), mapping);
Py_DECREF(mapping);
- } else {
+ } else {
items = PyMapping_Items(dct);
- }
- if (items == NULL)
+ }
+ if (items == NULL)
goto bail;
it = PyObject_GetIter(items);
- Py_DECREF(items);
- if (it == NULL)
+ Py_DECREF(items);
+ if (it == NULL)
goto bail;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
@@ -1437,8 +1437,8 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
- /* This must come before the PyLong_Check because
- True and False are also 1 and 0.*/
+ /* This must come before the PyLong_Check because
+ True and False are also 1 and 0.*/
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
@@ -1704,15 +1704,15 @@ PyDoc_STRVAR(module_doc,
"json speedups\n");
static struct PyModuleDef jsonmodule = {
- PyModuleDef_HEAD_INIT,
- "_json",
- module_doc,
- -1,
- speedups_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_json",
+ module_doc,
+ -1,
+ speedups_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyObject*
diff --git a/Modules/_localemodule.c b/Modules/_localemodule.c
index aabc3ac..84e393e 100644
--- a/Modules/_localemodule.c
+++ b/Modules/_localemodule.c
@@ -77,7 +77,7 @@ str2uni(const char* s)
if (dest != smallbuf)
PyMem_Free(dest);
return res2;
-}
+}
/* support functions for formatting floating point numbers */
@@ -243,7 +243,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
PyObject *os1, *os2, *result = NULL;
wchar_t *ws1 = NULL, *ws2 = NULL;
Py_ssize_t len1, len2;
-
+
if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2))
return NULL;
/* Convert the unicode strings to wchar[]. */
@@ -373,9 +373,9 @@ PyLocale_getdefaultlocale(PyObject* self)
#ifdef HAVE_LANGINFO_H
#define LANGINFO(X) {#X, X}
static struct langinfo_constant{
- char* name;
- int value;
-} langinfo_constants[] =
+ char* name;
+ int value;
+} langinfo_constants[] =
{
/* These constants should exist on any langinfo implementation */
LANGINFO(DAY_1),
@@ -514,10 +514,10 @@ PyDoc_STRVAR(gettext__doc__,
static PyObject*
PyIntl_gettext(PyObject* self, PyObject *args)
{
- char *in;
- if (!PyArg_ParseTuple(args, "s", &in))
- return 0;
- return str2uni(gettext(in));
+ char *in;
+ if (!PyArg_ParseTuple(args, "s", &in))
+ return 0;
+ return str2uni(gettext(in));
}
PyDoc_STRVAR(dgettext__doc__,
@@ -527,10 +527,10 @@ PyDoc_STRVAR(dgettext__doc__,
static PyObject*
PyIntl_dgettext(PyObject* self, PyObject *args)
{
- char *domain, *in;
- if (!PyArg_ParseTuple(args, "zs", &domain, &in))
- return 0;
- return str2uni(dgettext(domain, in));
+ char *domain, *in;
+ if (!PyArg_ParseTuple(args, "zs", &domain, &in))
+ return 0;
+ return str2uni(dgettext(domain, in));
}
PyDoc_STRVAR(dcgettext__doc__,
@@ -540,11 +540,11 @@ PyDoc_STRVAR(dcgettext__doc__,
static PyObject*
PyIntl_dcgettext(PyObject *self, PyObject *args)
{
- char *domain, *msgid;
- int category;
- if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
- return 0;
- return str2uni(dcgettext(domain,msgid,category));
+ char *domain, *msgid;
+ int category;
+ if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
+ return 0;
+ return str2uni(dcgettext(domain,msgid,category));
}
PyDoc_STRVAR(textdomain__doc__,
@@ -554,15 +554,15 @@ PyDoc_STRVAR(textdomain__doc__,
static PyObject*
PyIntl_textdomain(PyObject* self, PyObject* args)
{
- char *domain;
- if (!PyArg_ParseTuple(args, "z", &domain))
- return 0;
- domain = textdomain(domain);
- if (!domain) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- return str2uni(domain);
+ char *domain;
+ if (!PyArg_ParseTuple(args, "z", &domain))
+ return 0;
+ domain = textdomain(domain);
+ if (!domain) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ return str2uni(domain);
}
PyDoc_STRVAR(bindtextdomain__doc__,
@@ -572,19 +572,19 @@ PyDoc_STRVAR(bindtextdomain__doc__,
static PyObject*
PyIntl_bindtextdomain(PyObject* self,PyObject*args)
{
- char *domain, *dirname;
- if (!PyArg_ParseTuple(args, "sz", &domain, &dirname))
- return 0;
- if (!strlen(domain)) {
- PyErr_SetString(Error, "domain must be a non-empty string");
- return 0;
- }
- dirname = bindtextdomain(domain, dirname);
- if (!dirname) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- return str2uni(dirname);
+ char *domain, *dirname;
+ if (!PyArg_ParseTuple(args, "sz", &domain, &dirname))
+ return 0;
+ if (!strlen(domain)) {
+ PyErr_SetString(Error, "domain must be a non-empty string");
+ return 0;
+ }
+ dirname = bindtextdomain(domain, dirname);
+ if (!dirname) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ return str2uni(dirname);
}
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
@@ -595,32 +595,32 @@ PyDoc_STRVAR(bind_textdomain_codeset__doc__,
static PyObject*
PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args)
{
- char *domain,*codeset;
- if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
- return NULL;
- codeset = bind_textdomain_codeset(domain, codeset);
- if (codeset)
- return str2uni(codeset);
- Py_RETURN_NONE;
+ char *domain,*codeset;
+ if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
+ return NULL;
+ codeset = bind_textdomain_codeset(domain, codeset);
+ if (codeset)
+ return str2uni(codeset);
+ Py_RETURN_NONE;
}
#endif
#endif
static struct PyMethodDef PyLocale_Methods[] = {
- {"setlocale", (PyCFunction) PyLocale_setlocale,
+ {"setlocale", (PyCFunction) PyLocale_setlocale,
METH_VARARGS, setlocale__doc__},
- {"localeconv", (PyCFunction) PyLocale_localeconv,
+ {"localeconv", (PyCFunction) PyLocale_localeconv,
METH_NOARGS, localeconv__doc__},
#ifdef HAVE_WCSCOLL
- {"strcoll", (PyCFunction) PyLocale_strcoll,
+ {"strcoll", (PyCFunction) PyLocale_strcoll,
METH_VARARGS, strcoll__doc__},
#endif
#ifdef HAVE_WCSXFRM
- {"strxfrm", (PyCFunction) PyLocale_strxfrm,
+ {"strxfrm", (PyCFunction) PyLocale_strxfrm,
METH_VARARGS, strxfrm__doc__},
#endif
-#if defined(MS_WINDOWS)
+#if defined(MS_WINDOWS)
{"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS},
#endif
#ifdef HAVE_LANGINFO_H
@@ -642,21 +642,21 @@ static struct PyMethodDef PyLocale_Methods[] = {
{"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset,
METH_VARARGS, bind_textdomain_codeset__doc__},
#endif
-#endif
+#endif
{NULL, NULL}
};
static struct PyModuleDef _localemodule = {
- PyModuleDef_HEAD_INIT,
- "_locale",
- locale__doc__,
- -1,
- PyLocale_Methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_locale",
+ locale__doc__,
+ -1,
+ PyLocale_Methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -669,7 +669,7 @@ PyInit__locale(void)
m = PyModule_Create(&_localemodule);
if (m == NULL)
- return NULL;
+ return NULL;
d = PyModule_GetDict(m);
@@ -712,14 +712,14 @@ PyInit__locale(void)
#ifdef HAVE_LANGINFO_H
for (i = 0; langinfo_constants[i].name; i++) {
- PyModule_AddIntConstant(m, langinfo_constants[i].name,
- langinfo_constants[i].value);
+ PyModule_AddIntConstant(m, langinfo_constants[i].name,
+ langinfo_constants[i].value);
}
#endif
return m;
}
-/*
+/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
diff --git a/Modules/_lsprof.c b/Modules/_lsprof.c
index a4951c0..1fd660b 100644
--- a/Modules/_lsprof.c
+++ b/Modules/_lsprof.c
@@ -17,19 +17,19 @@
static PY_LONG_LONG
hpTimer(void)
{
- LARGE_INTEGER li;
- QueryPerformanceCounter(&li);
- return li.QuadPart;
+ LARGE_INTEGER li;
+ QueryPerformanceCounter(&li);
+ return li.QuadPart;
}
static double
hpTimerUnit(void)
{
- LARGE_INTEGER li;
- if (QueryPerformanceFrequency(&li))
- return 1.0 / li.QuadPart;
- else
- return 0.000001; /* unlikely */
+ LARGE_INTEGER li;
+ if (QueryPerformanceFrequency(&li))
+ return 1.0 / li.QuadPart;
+ else
+ return 0.000001; /* unlikely */
}
#else /* !MS_WINDOWS */
@@ -48,22 +48,22 @@ hpTimerUnit(void)
static PY_LONG_LONG
hpTimer(void)
{
- struct timeval tv;
- PY_LONG_LONG ret;
+ struct timeval tv;
+ PY_LONG_LONG ret;
#ifdef GETTIMEOFDAY_NO_TZ
- gettimeofday(&tv);
+ gettimeofday(&tv);
#else
- gettimeofday(&tv, (struct timezone *)NULL);
+ gettimeofday(&tv, (struct timezone *)NULL);
#endif
- ret = tv.tv_sec;
- ret = ret * 1000000 + tv.tv_usec;
- return ret;
+ ret = tv.tv_sec;
+ ret = ret * 1000000 + tv.tv_usec;
+ return ret;
}
static double
hpTimerUnit(void)
{
- return 0.000001;
+ return 0.000001;
}
#endif /* MS_WINDOWS */
@@ -75,41 +75,41 @@ struct _ProfilerEntry;
/* represents a function called from another function */
typedef struct _ProfilerSubEntry {
- rotating_node_t header;
- PY_LONG_LONG tt;
- PY_LONG_LONG it;
- long callcount;
- long recursivecallcount;
- long recursionLevel;
+ rotating_node_t header;
+ PY_LONG_LONG tt;
+ PY_LONG_LONG it;
+ long callcount;
+ long recursivecallcount;
+ long recursionLevel;
} ProfilerSubEntry;
/* represents a function or user defined block */
typedef struct _ProfilerEntry {
- rotating_node_t header;
- PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
- PY_LONG_LONG tt; /* total time in this entry */
- PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */
- long callcount; /* how many times this was called */
- long recursivecallcount; /* how many times called recursively */
- long recursionLevel;
- rotating_node_t *calls;
+ rotating_node_t header;
+ PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
+ PY_LONG_LONG tt; /* total time in this entry */
+ PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */
+ long callcount; /* how many times this was called */
+ long recursivecallcount; /* how many times called recursively */
+ long recursionLevel;
+ rotating_node_t *calls;
} ProfilerEntry;
typedef struct _ProfilerContext {
- PY_LONG_LONG t0;
- PY_LONG_LONG subt;
- struct _ProfilerContext *previous;
- ProfilerEntry *ctxEntry;
+ PY_LONG_LONG t0;
+ PY_LONG_LONG subt;
+ struct _ProfilerContext *previous;
+ ProfilerEntry *ctxEntry;
} ProfilerContext;
typedef struct {
- PyObject_HEAD
- rotating_node_t *profilerEntries;
- ProfilerContext *currentProfilerContext;
- ProfilerContext *freelistProfilerContext;
- int flags;
- PyObject *externalTimer;
- double externalTimerUnit;
+ PyObject_HEAD
+ rotating_node_t *profilerEntries;
+ ProfilerContext *currentProfilerContext;
+ ProfilerContext *freelistProfilerContext;
+ int flags;
+ PyObject *externalTimer;
+ double externalTimerUnit;
} ProfilerObject;
#define POF_ENABLED 0x001
@@ -129,407 +129,407 @@ static PyObject *empty_tuple;
static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj)
{
- PY_LONG_LONG result;
- PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL);
- if (o == NULL) {
- PyErr_WriteUnraisable(pObj->externalTimer);
- return 0;
- }
- if (pObj->externalTimerUnit > 0.0) {
- /* interpret the result as an integer that will be scaled
- in profiler_getstats() */
- result = PyLong_AsLongLong(o);
- }
- else {
- /* interpret the result as a double measured in seconds.
- As the profiler works with PY_LONG_LONG internally
- we convert it to a large integer */
- double val = PyFloat_AsDouble(o);
- /* error handling delayed to the code below */
- result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION);
- }
- Py_DECREF(o);
- if (PyErr_Occurred()) {
- PyErr_WriteUnraisable(pObj->externalTimer);
- return 0;
- }
- return result;
+ PY_LONG_LONG result;
+ PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL);
+ if (o == NULL) {
+ PyErr_WriteUnraisable(pObj->externalTimer);
+ return 0;
+ }
+ if (pObj->externalTimerUnit > 0.0) {
+ /* interpret the result as an integer that will be scaled
+ in profiler_getstats() */
+ result = PyLong_AsLongLong(o);
+ }
+ else {
+ /* interpret the result as a double measured in seconds.
+ As the profiler works with PY_LONG_LONG internally
+ we convert it to a large integer */
+ double val = PyFloat_AsDouble(o);
+ /* error handling delayed to the code below */
+ result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION);
+ }
+ Py_DECREF(o);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(pObj->externalTimer);
+ return 0;
+ }
+ return result;
}
-#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \
- CallExternalTimer(pObj) : \
- hpTimer())
+#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \
+ CallExternalTimer(pObj) : \
+ hpTimer())
/*** ProfilerObject ***/
static PyObject *
normalizeUserObj(PyObject *obj)
{
- PyCFunctionObject *fn;
- if (!PyCFunction_Check(obj)) {
- Py_INCREF(obj);
- return obj;
- }
- /* Replace built-in function objects with a descriptive string
- because of built-in methods -- keeping a reference to
- __self__ is probably not a good idea. */
- fn = (PyCFunctionObject *)obj;
-
- if (fn->m_self == NULL) {
- /* built-in function: look up the module name */
- PyObject *mod = fn->m_module;
- const char *modname;
- if (mod && PyUnicode_Check(mod)) {
- modname = _PyUnicode_AsString(mod);
- }
- else if (mod && PyModule_Check(mod)) {
- modname = PyModule_GetName(mod);
- if (modname == NULL) {
- PyErr_Clear();
- modname = "builtins";
- }
- }
- else {
- modname = "builtins";
- }
- if (strcmp(modname, "builtins") != 0)
- return PyUnicode_FromFormat("<%s.%s>",
- modname,
- fn->m_ml->ml_name);
- else
- return PyUnicode_FromFormat("<%s>",
- fn->m_ml->ml_name);
- }
- else {
- /* built-in method: try to return
- repr(getattr(type(__self__), __name__))
- */
- PyObject *self = fn->m_self;
- PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name);
- if (name != NULL) {
- PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
- Py_XINCREF(mo);
- Py_DECREF(name);
- if (mo != NULL) {
- PyObject *res = PyObject_Repr(mo);
- Py_DECREF(mo);
- if (res != NULL)
- return res;
- }
- }
- PyErr_Clear();
- return PyUnicode_FromFormat("<built-in method %s>",
- fn->m_ml->ml_name);
- }
+ PyCFunctionObject *fn;
+ if (!PyCFunction_Check(obj)) {
+ Py_INCREF(obj);
+ return obj;
+ }
+ /* Replace built-in function objects with a descriptive string
+ because of built-in methods -- keeping a reference to
+ __self__ is probably not a good idea. */
+ fn = (PyCFunctionObject *)obj;
+
+ if (fn->m_self == NULL) {
+ /* built-in function: look up the module name */
+ PyObject *mod = fn->m_module;
+ const char *modname;
+ if (mod && PyUnicode_Check(mod)) {
+ modname = _PyUnicode_AsString(mod);
+ }
+ else if (mod && PyModule_Check(mod)) {
+ modname = PyModule_GetName(mod);
+ if (modname == NULL) {
+ PyErr_Clear();
+ modname = "builtins";
+ }
+ }
+ else {
+ modname = "builtins";
+ }
+ if (strcmp(modname, "builtins") != 0)
+ return PyUnicode_FromFormat("<%s.%s>",
+ modname,
+ fn->m_ml->ml_name);
+ else
+ return PyUnicode_FromFormat("<%s>",
+ fn->m_ml->ml_name);
+ }
+ else {
+ /* built-in method: try to return
+ repr(getattr(type(__self__), __name__))
+ */
+ PyObject *self = fn->m_self;
+ PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name);
+ if (name != NULL) {
+ PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
+ Py_XINCREF(mo);
+ Py_DECREF(name);
+ if (mo != NULL) {
+ PyObject *res = PyObject_Repr(mo);
+ Py_DECREF(mo);
+ if (res != NULL)
+ return res;
+ }
+ }
+ PyErr_Clear();
+ return PyUnicode_FromFormat("<built-in method %s>",
+ fn->m_ml->ml_name);
+ }
}
static ProfilerEntry*
newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj)
{
- ProfilerEntry *self;
- self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry));
- if (self == NULL) {
- pObj->flags |= POF_NOMEMORY;
- return NULL;
- }
- userObj = normalizeUserObj(userObj);
- if (userObj == NULL) {
- PyErr_Clear();
- free(self);
- pObj->flags |= POF_NOMEMORY;
- return NULL;
- }
- self->header.key = key;
- self->userObj = userObj;
- self->tt = 0;
- self->it = 0;
- self->callcount = 0;
- self->recursivecallcount = 0;
- self->recursionLevel = 0;
- self->calls = EMPTY_ROTATING_TREE;
- RotatingTree_Add(&pObj->profilerEntries, &self->header);
- return self;
+ ProfilerEntry *self;
+ self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry));
+ if (self == NULL) {
+ pObj->flags |= POF_NOMEMORY;
+ return NULL;
+ }
+ userObj = normalizeUserObj(userObj);
+ if (userObj == NULL) {
+ PyErr_Clear();
+ free(self);
+ pObj->flags |= POF_NOMEMORY;
+ return NULL;
+ }
+ self->header.key = key;
+ self->userObj = userObj;
+ self->tt = 0;
+ self->it = 0;
+ self->callcount = 0;
+ self->recursivecallcount = 0;
+ self->recursionLevel = 0;
+ self->calls = EMPTY_ROTATING_TREE;
+ RotatingTree_Add(&pObj->profilerEntries, &self->header);
+ return self;
}
static ProfilerEntry*
getEntry(ProfilerObject *pObj, void *key)
{
- return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
+ return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
}
-static ProfilerSubEntry *
+static ProfilerSubEntry *
getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
- return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
- (void *)entry);
+ return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
+ (void *)entry);
}
static ProfilerSubEntry *
newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
- ProfilerSubEntry *self;
- self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry));
- if (self == NULL) {
- pObj->flags |= POF_NOMEMORY;
- return NULL;
- }
- self->header.key = (void *)entry;
- self->tt = 0;
- self->it = 0;
- self->callcount = 0;
- self->recursivecallcount = 0;
- self->recursionLevel = 0;
- RotatingTree_Add(&caller->calls, &self->header);
- return self;
+ ProfilerSubEntry *self;
+ self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry));
+ if (self == NULL) {
+ pObj->flags |= POF_NOMEMORY;
+ return NULL;
+ }
+ self->header.key = (void *)entry;
+ self->tt = 0;
+ self->it = 0;
+ self->callcount = 0;
+ self->recursivecallcount = 0;
+ self->recursionLevel = 0;
+ RotatingTree_Add(&caller->calls, &self->header);
+ return self;
}
static int freeSubEntry(rotating_node_t *header, void *arg)
{
- ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
- free(subentry);
- return 0;
+ ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
+ free(subentry);
+ return 0;
}
static int freeEntry(rotating_node_t *header, void *arg)
{
- ProfilerEntry *entry = (ProfilerEntry*) header;
- RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
- Py_DECREF(entry->userObj);
- free(entry);
- return 0;
+ ProfilerEntry *entry = (ProfilerEntry*) header;
+ RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
+ Py_DECREF(entry->userObj);
+ free(entry);
+ return 0;
}
static void clearEntries(ProfilerObject *pObj)
{
- RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
- pObj->profilerEntries = EMPTY_ROTATING_TREE;
- /* release the memory hold by the ProfilerContexts */
- if (pObj->currentProfilerContext) {
- free(pObj->currentProfilerContext);
- pObj->currentProfilerContext = NULL;
- }
- while (pObj->freelistProfilerContext) {
- ProfilerContext *c = pObj->freelistProfilerContext;
- pObj->freelistProfilerContext = c->previous;
- free(c);
- }
- pObj->freelistProfilerContext = NULL;
+ RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
+ pObj->profilerEntries = EMPTY_ROTATING_TREE;
+ /* release the memory hold by the ProfilerContexts */
+ if (pObj->currentProfilerContext) {
+ free(pObj->currentProfilerContext);
+ pObj->currentProfilerContext = NULL;
+ }
+ while (pObj->freelistProfilerContext) {
+ ProfilerContext *c = pObj->freelistProfilerContext;
+ pObj->freelistProfilerContext = c->previous;
+ free(c);
+ }
+ pObj->freelistProfilerContext = NULL;
}
static void
initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
- self->ctxEntry = entry;
- self->subt = 0;
- self->previous = pObj->currentProfilerContext;
- pObj->currentProfilerContext = self;
- ++entry->recursionLevel;
- if ((pObj->flags & POF_SUBCALLS) && self->previous) {
- /* find or create an entry for me in my caller's entry */
- ProfilerEntry *caller = self->previous->ctxEntry;
- ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
- if (subentry == NULL)
- subentry = newSubEntry(pObj, caller, entry);
- if (subentry)
- ++subentry->recursionLevel;
- }
- self->t0 = CALL_TIMER(pObj);
+ self->ctxEntry = entry;
+ self->subt = 0;
+ self->previous = pObj->currentProfilerContext;
+ pObj->currentProfilerContext = self;
+ ++entry->recursionLevel;
+ if ((pObj->flags & POF_SUBCALLS) && self->previous) {
+ /* find or create an entry for me in my caller's entry */
+ ProfilerEntry *caller = self->previous->ctxEntry;
+ ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
+ if (subentry == NULL)
+ subentry = newSubEntry(pObj, caller, entry);
+ if (subentry)
+ ++subentry->recursionLevel;
+ }
+ self->t0 = CALL_TIMER(pObj);
}
static void
Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
- PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0;
- PY_LONG_LONG it = tt - self->subt;
- if (self->previous)
- self->previous->subt += tt;
- pObj->currentProfilerContext = self->previous;
- if (--entry->recursionLevel == 0)
- entry->tt += tt;
- else
- ++entry->recursivecallcount;
- entry->it += it;
- entry->callcount++;
- if ((pObj->flags & POF_SUBCALLS) && self->previous) {
- /* find or create an entry for me in my caller's entry */
- ProfilerEntry *caller = self->previous->ctxEntry;
- ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
- if (subentry) {
- if (--subentry->recursionLevel == 0)
- subentry->tt += tt;
- else
- ++subentry->recursivecallcount;
- subentry->it += it;
- ++subentry->callcount;
- }
- }
+ PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0;
+ PY_LONG_LONG it = tt - self->subt;
+ if (self->previous)
+ self->previous->subt += tt;
+ pObj->currentProfilerContext = self->previous;
+ if (--entry->recursionLevel == 0)
+ entry->tt += tt;
+ else
+ ++entry->recursivecallcount;
+ entry->it += it;
+ entry->callcount++;
+ if ((pObj->flags & POF_SUBCALLS) && self->previous) {
+ /* find or create an entry for me in my caller's entry */
+ ProfilerEntry *caller = self->previous->ctxEntry;
+ ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
+ if (subentry) {
+ if (--subentry->recursionLevel == 0)
+ subentry->tt += tt;
+ else
+ ++subentry->recursivecallcount;
+ subentry->it += it;
+ ++subentry->callcount;
+ }
+ }
}
static void
ptrace_enter_call(PyObject *self, void *key, PyObject *userObj)
{
- /* entering a call to the function identified by 'key'
- (which can be a PyCodeObject or a PyMethodDef pointer) */
- ProfilerObject *pObj = (ProfilerObject*)self;
- ProfilerEntry *profEntry;
- ProfilerContext *pContext;
-
- /* In the case of entering a generator expression frame via a
- * throw (gen_send_ex(.., 1)), we may already have an
- * Exception set here. We must not mess around with this
- * exception, and some of the code under here assumes that
- * PyErr_* is its own to mess around with, so we have to
- * save and restore any current exception. */
- PyObject *last_type, *last_value, *last_tb;
- PyErr_Fetch(&last_type, &last_value, &last_tb);
-
- profEntry = getEntry(pObj, key);
- if (profEntry == NULL) {
- profEntry = newProfilerEntry(pObj, key, userObj);
- if (profEntry == NULL)
- goto restorePyerr;
- }
- /* grab a ProfilerContext out of the free list */
- pContext = pObj->freelistProfilerContext;
- if (pContext) {
- pObj->freelistProfilerContext = pContext->previous;
- }
- else {
- /* free list exhausted, allocate a new one */
- pContext = (ProfilerContext*)
- malloc(sizeof(ProfilerContext));
- if (pContext == NULL) {
- pObj->flags |= POF_NOMEMORY;
- goto restorePyerr;
- }
- }
- initContext(pObj, pContext, profEntry);
+ /* entering a call to the function identified by 'key'
+ (which can be a PyCodeObject or a PyMethodDef pointer) */
+ ProfilerObject *pObj = (ProfilerObject*)self;
+ ProfilerEntry *profEntry;
+ ProfilerContext *pContext;
+
+ /* In the case of entering a generator expression frame via a
+ * throw (gen_send_ex(.., 1)), we may already have an
+ * Exception set here. We must not mess around with this
+ * exception, and some of the code under here assumes that
+ * PyErr_* is its own to mess around with, so we have to
+ * save and restore any current exception. */
+ PyObject *last_type, *last_value, *last_tb;
+ PyErr_Fetch(&last_type, &last_value, &last_tb);
+
+ profEntry = getEntry(pObj, key);
+ if (profEntry == NULL) {
+ profEntry = newProfilerEntry(pObj, key, userObj);
+ if (profEntry == NULL)
+ goto restorePyerr;
+ }
+ /* grab a ProfilerContext out of the free list */
+ pContext = pObj->freelistProfilerContext;
+ if (pContext) {
+ pObj->freelistProfilerContext = pContext->previous;
+ }
+ else {
+ /* free list exhausted, allocate a new one */
+ pContext = (ProfilerContext*)
+ malloc(sizeof(ProfilerContext));
+ if (pContext == NULL) {
+ pObj->flags |= POF_NOMEMORY;
+ goto restorePyerr;
+ }
+ }
+ initContext(pObj, pContext, profEntry);
restorePyerr:
- PyErr_Restore(last_type, last_value, last_tb);
+ PyErr_Restore(last_type, last_value, last_tb);
}
static void
ptrace_leave_call(PyObject *self, void *key)
{
- /* leaving a call to the function identified by 'key' */
- ProfilerObject *pObj = (ProfilerObject*)self;
- ProfilerEntry *profEntry;
- ProfilerContext *pContext;
-
- pContext = pObj->currentProfilerContext;
- if (pContext == NULL)
- return;
- profEntry = getEntry(pObj, key);
- if (profEntry) {
- Stop(pObj, pContext, profEntry);
- }
- else {
- pObj->currentProfilerContext = pContext->previous;
- }
- /* put pContext into the free list */
- pContext->previous = pObj->freelistProfilerContext;
- pObj->freelistProfilerContext = pContext;
+ /* leaving a call to the function identified by 'key' */
+ ProfilerObject *pObj = (ProfilerObject*)self;
+ ProfilerEntry *profEntry;
+ ProfilerContext *pContext;
+
+ pContext = pObj->currentProfilerContext;
+ if (pContext == NULL)
+ return;
+ profEntry = getEntry(pObj, key);
+ if (profEntry) {
+ Stop(pObj, pContext, profEntry);
+ }
+ else {
+ pObj->currentProfilerContext = pContext->previous;
+ }
+ /* put pContext into the free list */
+ pContext->previous = pObj->freelistProfilerContext;
+ pObj->freelistProfilerContext = pContext;
}
static int
profiler_callback(PyObject *self, PyFrameObject *frame, int what,
- PyObject *arg)
+ PyObject *arg)
{
- switch (what) {
-
- /* the 'frame' of a called function is about to start its execution */
- case PyTrace_CALL:
- ptrace_enter_call(self, (void *)frame->f_code,
- (PyObject *)frame->f_code);
- break;
-
- /* the 'frame' of a called function is about to finish
- (either normally or with an exception) */
- case PyTrace_RETURN:
- ptrace_leave_call(self, (void *)frame->f_code);
- break;
-
- /* case PyTrace_EXCEPTION:
- If the exception results in the function exiting, a
- PyTrace_RETURN event will be generated, so we don't need to
- handle it. */
-
-#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
- /* the Python function 'frame' is issuing a call to the built-in
- function 'arg' */
- case PyTrace_C_CALL:
- if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
- && PyCFunction_Check(arg)) {
- ptrace_enter_call(self,
- ((PyCFunctionObject *)arg)->m_ml,
- arg);
- }
- break;
-
- /* the call to the built-in function 'arg' is returning into its
- caller 'frame' */
- case PyTrace_C_RETURN: /* ...normally */
- case PyTrace_C_EXCEPTION: /* ...with an exception set */
- if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
- && PyCFunction_Check(arg)) {
- ptrace_leave_call(self,
- ((PyCFunctionObject *)arg)->m_ml);
- }
- break;
+ switch (what) {
+
+ /* the 'frame' of a called function is about to start its execution */
+ case PyTrace_CALL:
+ ptrace_enter_call(self, (void *)frame->f_code,
+ (PyObject *)frame->f_code);
+ break;
+
+ /* the 'frame' of a called function is about to finish
+ (either normally or with an exception) */
+ case PyTrace_RETURN:
+ ptrace_leave_call(self, (void *)frame->f_code);
+ break;
+
+ /* case PyTrace_EXCEPTION:
+ If the exception results in the function exiting, a
+ PyTrace_RETURN event will be generated, so we don't need to
+ handle it. */
+
+#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
+ /* the Python function 'frame' is issuing a call to the built-in
+ function 'arg' */
+ case PyTrace_C_CALL:
+ if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
+ && PyCFunction_Check(arg)) {
+ ptrace_enter_call(self,
+ ((PyCFunctionObject *)arg)->m_ml,
+ arg);
+ }
+ break;
+
+ /* the call to the built-in function 'arg' is returning into its
+ caller 'frame' */
+ case PyTrace_C_RETURN: /* ...normally */
+ case PyTrace_C_EXCEPTION: /* ...with an exception set */
+ if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
+ && PyCFunction_Check(arg)) {
+ ptrace_leave_call(self,
+ ((PyCFunctionObject *)arg)->m_ml);
+ }
+ break;
#endif
- default:
- break;
- }
- return 0;
+ default:
+ break;
+ }
+ return 0;
}
static int
pending_exception(ProfilerObject *pObj)
{
- if (pObj->flags & POF_NOMEMORY) {
- pObj->flags -= POF_NOMEMORY;
- PyErr_SetString(PyExc_MemoryError,
- "memory was exhausted while profiling");
- return -1;
- }
- return 0;
+ if (pObj->flags & POF_NOMEMORY) {
+ pObj->flags -= POF_NOMEMORY;
+ PyErr_SetString(PyExc_MemoryError,
+ "memory was exhausted while profiling");
+ return -1;
+ }
+ return 0;
}
/************************************************************/
static PyStructSequence_Field profiler_entry_fields[] = {
- {"code", "code object or built-in function name"},
- {"callcount", "how many times this was called"},
- {"reccallcount", "how many times called recursively"},
- {"totaltime", "total time in this entry"},
- {"inlinetime", "inline time in this entry (not in subcalls)"},
- {"calls", "details of the calls"},
- {0}
+ {"code", "code object or built-in function name"},
+ {"callcount", "how many times this was called"},
+ {"reccallcount", "how many times called recursively"},
+ {"totaltime", "total time in this entry"},
+ {"inlinetime", "inline time in this entry (not in subcalls)"},
+ {"calls", "details of the calls"},
+ {0}
};
static PyStructSequence_Field profiler_subentry_fields[] = {
- {"code", "called code object or built-in function name"},
- {"callcount", "how many times this is called"},
- {"reccallcount", "how many times this is called recursively"},
- {"totaltime", "total time spent in this call"},
- {"inlinetime", "inline time (not in further subcalls)"},
- {0}
+ {"code", "called code object or built-in function name"},
+ {"callcount", "how many times this is called"},
+ {"reccallcount", "how many times this is called recursively"},
+ {"totaltime", "total time spent in this call"},
+ {"inlinetime", "inline time (not in further subcalls)"},
+ {0}
};
static PyStructSequence_Desc profiler_entry_desc = {
- "_lsprof.profiler_entry", /* name */
- NULL, /* doc */
- profiler_entry_fields,
- 6
+ "_lsprof.profiler_entry", /* name */
+ NULL, /* doc */
+ profiler_entry_fields,
+ 6
};
static PyStructSequence_Desc profiler_subentry_desc = {
- "_lsprof.profiler_subentry", /* name */
- NULL, /* doc */
- profiler_subentry_fields,
- 5
+ "_lsprof.profiler_subentry", /* name */
+ NULL, /* doc */
+ profiler_subentry_fields,
+ 5
};
static int initialized;
@@ -538,70 +538,70 @@ static PyTypeObject StatsSubEntryType;
typedef struct {
- PyObject *list;
- PyObject *sublist;
- double factor;
+ PyObject *list;
+ PyObject *sublist;
+ double factor;
} statscollector_t;
static int statsForSubEntry(rotating_node_t *node, void *arg)
{
- ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
- statscollector_t *collect = (statscollector_t*) arg;
- ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
- int err;
- PyObject *sinfo;
- sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType,
- "((Olldd))",
- entry->userObj,
- sentry->callcount,
- sentry->recursivecallcount,
- collect->factor * sentry->tt,
- collect->factor * sentry->it);
- if (sinfo == NULL)
- return -1;
- err = PyList_Append(collect->sublist, sinfo);
- Py_DECREF(sinfo);
- return err;
+ ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
+ statscollector_t *collect = (statscollector_t*) arg;
+ ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
+ int err;
+ PyObject *sinfo;
+ sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType,
+ "((Olldd))",
+ entry->userObj,
+ sentry->callcount,
+ sentry->recursivecallcount,
+ collect->factor * sentry->tt,
+ collect->factor * sentry->it);
+ if (sinfo == NULL)
+ return -1;
+ err = PyList_Append(collect->sublist, sinfo);
+ Py_DECREF(sinfo);
+ return err;
}
static int statsForEntry(rotating_node_t *node, void *arg)
{
- ProfilerEntry *entry = (ProfilerEntry*) node;
- statscollector_t *collect = (statscollector_t*) arg;
- PyObject *info;
- int err;
- if (entry->callcount == 0)
- return 0; /* skip */
-
- if (entry->calls != EMPTY_ROTATING_TREE) {
- collect->sublist = PyList_New(0);
- if (collect->sublist == NULL)
- return -1;
- if (RotatingTree_Enum(entry->calls,
- statsForSubEntry, collect) != 0) {
- Py_DECREF(collect->sublist);
- return -1;
- }
- }
- else {
- Py_INCREF(Py_None);
- collect->sublist = Py_None;
- }
-
- info = PyObject_CallFunction((PyObject*) &StatsEntryType,
- "((OllddO))",
- entry->userObj,
- entry->callcount,
- entry->recursivecallcount,
- collect->factor * entry->tt,
- collect->factor * entry->it,
- collect->sublist);
- Py_DECREF(collect->sublist);
- if (info == NULL)
- return -1;
- err = PyList_Append(collect->list, info);
- Py_DECREF(info);
- return err;
+ ProfilerEntry *entry = (ProfilerEntry*) node;
+ statscollector_t *collect = (statscollector_t*) arg;
+ PyObject *info;
+ int err;
+ if (entry->callcount == 0)
+ return 0; /* skip */
+
+ if (entry->calls != EMPTY_ROTATING_TREE) {
+ collect->sublist = PyList_New(0);
+ if (collect->sublist == NULL)
+ return -1;
+ if (RotatingTree_Enum(entry->calls,
+ statsForSubEntry, collect) != 0) {
+ Py_DECREF(collect->sublist);
+ return -1;
+ }
+ }
+ else {
+ Py_INCREF(Py_None);
+ collect->sublist = Py_None;
+ }
+
+ info = PyObject_CallFunction((PyObject*) &StatsEntryType,
+ "((OllddO))",
+ entry->userObj,
+ entry->callcount,
+ entry->recursivecallcount,
+ collect->factor * entry->tt,
+ collect->factor * entry->it,
+ collect->sublist);
+ Py_DECREF(collect->sublist);
+ if (info == NULL)
+ return -1;
+ err = PyList_Append(collect->list, info);
+ Py_DECREF(info);
+ return err;
}
PyDoc_STRVAR(getstats_doc, "\
@@ -631,51 +631,51 @@ profiler_subentry objects:\n\
static PyObject*
profiler_getstats(ProfilerObject *pObj, PyObject* noarg)
{
- statscollector_t collect;
- if (pending_exception(pObj))
- return NULL;
- if (!pObj->externalTimer)
- collect.factor = hpTimerUnit();
- else if (pObj->externalTimerUnit > 0.0)
- collect.factor = pObj->externalTimerUnit;
- else
- collect.factor = 1.0 / DOUBLE_TIMER_PRECISION;
- collect.list = PyList_New(0);
- if (collect.list == NULL)
- return NULL;
- if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect)
- != 0) {
- Py_DECREF(collect.list);
- return NULL;
- }
- return collect.list;
+ statscollector_t collect;
+ if (pending_exception(pObj))
+ return NULL;
+ if (!pObj->externalTimer)
+ collect.factor = hpTimerUnit();
+ else if (pObj->externalTimerUnit > 0.0)
+ collect.factor = pObj->externalTimerUnit;
+ else
+ collect.factor = 1.0 / DOUBLE_TIMER_PRECISION;
+ collect.list = PyList_New(0);
+ if (collect.list == NULL)
+ return NULL;
+ if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect)
+ != 0) {
+ Py_DECREF(collect.list);
+ return NULL;
+ }
+ return collect.list;
}
static int
setSubcalls(ProfilerObject *pObj, int nvalue)
{
- if (nvalue == 0)
- pObj->flags &= ~POF_SUBCALLS;
- else if (nvalue > 0)
- pObj->flags |= POF_SUBCALLS;
- return 0;
+ if (nvalue == 0)
+ pObj->flags &= ~POF_SUBCALLS;
+ else if (nvalue > 0)
+ pObj->flags |= POF_SUBCALLS;
+ return 0;
}
static int
setBuiltins(ProfilerObject *pObj, int nvalue)
{
- if (nvalue == 0)
- pObj->flags &= ~POF_BUILTINS;
- else if (nvalue > 0) {
+ if (nvalue == 0)
+ pObj->flags &= ~POF_BUILTINS;
+ else if (nvalue > 0) {
#ifndef PyTrace_C_CALL
- PyErr_SetString(PyExc_ValueError,
- "builtins=True requires Python >= 2.4");
- return -1;
+ PyErr_SetString(PyExc_ValueError,
+ "builtins=True requires Python >= 2.4");
+ return -1;
#else
- pObj->flags |= POF_BUILTINS;
+ pObj->flags |= POF_BUILTINS;
#endif
- }
- return 0;
+ }
+ return 0;
}
PyDoc_STRVAR(enable_doc, "\
@@ -691,33 +691,33 @@ built-in functions separately from their caller.\n\
static PyObject*
profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds)
{
- int subcalls = -1;
- int builtins = -1;
- static char *kwlist[] = {"subcalls", "builtins", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable",
- kwlist, &subcalls, &builtins))
- return NULL;
- if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0)
- return NULL;
- PyEval_SetProfile(profiler_callback, (PyObject*)self);
- self->flags |= POF_ENABLED;
- Py_INCREF(Py_None);
- return Py_None;
+ int subcalls = -1;
+ int builtins = -1;
+ static char *kwlist[] = {"subcalls", "builtins", 0};
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable",
+ kwlist, &subcalls, &builtins))
+ return NULL;
+ if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0)
+ return NULL;
+ PyEval_SetProfile(profiler_callback, (PyObject*)self);
+ self->flags |= POF_ENABLED;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
flush_unmatched(ProfilerObject *pObj)
{
- while (pObj->currentProfilerContext) {
- ProfilerContext *pContext = pObj->currentProfilerContext;
- ProfilerEntry *profEntry= pContext->ctxEntry;
- if (profEntry)
- Stop(pObj, pContext, profEntry);
- else
- pObj->currentProfilerContext = pContext->previous;
- if (pContext)
- free(pContext);
- }
+ while (pObj->currentProfilerContext) {
+ ProfilerContext *pContext = pObj->currentProfilerContext;
+ ProfilerEntry *profEntry= pContext->ctxEntry;
+ if (profEntry)
+ Stop(pObj, pContext, profEntry);
+ else
+ pObj->currentProfilerContext = pContext->previous;
+ if (pContext)
+ free(pContext);
+ }
}
@@ -730,13 +730,13 @@ Stop collecting profiling information.\n\
static PyObject*
profiler_disable(ProfilerObject *self, PyObject* noarg)
{
- self->flags &= ~POF_ENABLED;
- PyEval_SetProfile(NULL, NULL);
- flush_unmatched(self);
- if (pending_exception(self))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ self->flags &= ~POF_ENABLED;
+ PyEval_SetProfile(NULL, NULL);
+ flush_unmatched(self);
+ if (pending_exception(self))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(clear_doc, "\
@@ -748,62 +748,62 @@ Clear all profiling information collected so far.\n\
static PyObject*
profiler_clear(ProfilerObject *pObj, PyObject* noarg)
{
- clearEntries(pObj);
- Py_INCREF(Py_None);
- return Py_None;
+ clearEntries(pObj);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
profiler_dealloc(ProfilerObject *op)
{
- if (op->flags & POF_ENABLED)
- PyEval_SetProfile(NULL, NULL);
- flush_unmatched(op);
- clearEntries(op);
- Py_XDECREF(op->externalTimer);
- Py_TYPE(op)->tp_free(op);
+ if (op->flags & POF_ENABLED)
+ PyEval_SetProfile(NULL, NULL);
+ flush_unmatched(op);
+ clearEntries(op);
+ Py_XDECREF(op->externalTimer);
+ Py_TYPE(op)->tp_free(op);
}
static int
profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw)
{
- PyObject *o;
- PyObject *timer = NULL;
- double timeunit = 0.0;
- int subcalls = 1;
+ PyObject *o;
+ PyObject *timer = NULL;
+ double timeunit = 0.0;
+ int subcalls = 1;
#ifdef PyTrace_C_CALL
- int builtins = 1;
+ int builtins = 1;
#else
- int builtins = 0;
+ int builtins = 0;
#endif
- static char *kwlist[] = {"timer", "timeunit",
- "subcalls", "builtins", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist,
- &timer, &timeunit,
- &subcalls, &builtins))
- return -1;
-
- if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
- return -1;
- o = pObj->externalTimer;
- pObj->externalTimer = timer;
- Py_XINCREF(timer);
- Py_XDECREF(o);
- pObj->externalTimerUnit = timeunit;
- return 0;
+ static char *kwlist[] = {"timer", "timeunit",
+ "subcalls", "builtins", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist,
+ &timer, &timeunit,
+ &subcalls, &builtins))
+ return -1;
+
+ if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
+ return -1;
+ o = pObj->externalTimer;
+ pObj->externalTimer = timer;
+ Py_XINCREF(timer);
+ Py_XDECREF(o);
+ pObj->externalTimerUnit = timeunit;
+ return 0;
}
static PyMethodDef profiler_methods[] = {
- {"getstats", (PyCFunction)profiler_getstats,
- METH_NOARGS, getstats_doc},
- {"enable", (PyCFunction)profiler_enable,
- METH_VARARGS | METH_KEYWORDS, enable_doc},
- {"disable", (PyCFunction)profiler_disable,
- METH_NOARGS, disable_doc},
- {"clear", (PyCFunction)profiler_clear,
- METH_NOARGS, clear_doc},
- {NULL, NULL}
+ {"getstats", (PyCFunction)profiler_getstats,
+ METH_NOARGS, getstats_doc},
+ {"enable", (PyCFunction)profiler_enable,
+ METH_VARARGS | METH_KEYWORDS, enable_doc},
+ {"disable", (PyCFunction)profiler_disable,
+ METH_NOARGS, disable_doc},
+ {"clear", (PyCFunction)profiler_clear,
+ METH_NOARGS, clear_doc},
+ {NULL, NULL}
};
PyDoc_STRVAR(profiler_doc, "\
@@ -817,89 +817,89 @@ Profiler(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\n\
");
static PyTypeObject PyProfiler_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_lsprof.Profiler", /* tp_name */
- sizeof(ProfilerObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)profiler_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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 */
- profiler_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- profiler_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)profiler_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_lsprof.Profiler", /* tp_name */
+ sizeof(ProfilerObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)profiler_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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 */
+ profiler_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ profiler_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)profiler_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_Del, /* tp_free */
};
static PyMethodDef moduleMethods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
static struct PyModuleDef _lsprofmodule = {
- PyModuleDef_HEAD_INIT,
- "_lsprof",
- "Fast profiler",
- -1,
- moduleMethods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_lsprof",
+ "Fast profiler",
+ -1,
+ moduleMethods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__lsprof(void)
{
- PyObject *module, *d;
- module = PyModule_Create(&_lsprofmodule);
- if (module == NULL)
- return NULL;
- d = PyModule_GetDict(module);
- if (PyType_Ready(&PyProfiler_Type) < 0)
- return NULL;
- PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
-
- if (!initialized) {
- PyStructSequence_InitType(&StatsEntryType,
- &profiler_entry_desc);
- PyStructSequence_InitType(&StatsSubEntryType,
- &profiler_subentry_desc);
- }
- Py_INCREF((PyObject*) &StatsEntryType);
- Py_INCREF((PyObject*) &StatsSubEntryType);
- PyModule_AddObject(module, "profiler_entry",
- (PyObject*) &StatsEntryType);
- PyModule_AddObject(module, "profiler_subentry",
- (PyObject*) &StatsSubEntryType);
- empty_tuple = PyTuple_New(0);
- initialized = 1;
- return module;
+ PyObject *module, *d;
+ module = PyModule_Create(&_lsprofmodule);
+ if (module == NULL)
+ return NULL;
+ d = PyModule_GetDict(module);
+ if (PyType_Ready(&PyProfiler_Type) < 0)
+ return NULL;
+ PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
+
+ if (!initialized) {
+ PyStructSequence_InitType(&StatsEntryType,
+ &profiler_entry_desc);
+ PyStructSequence_InitType(&StatsSubEntryType,
+ &profiler_subentry_desc);
+ }
+ Py_INCREF((PyObject*) &StatsEntryType);
+ Py_INCREF((PyObject*) &StatsSubEntryType);
+ PyModule_AddObject(module, "profiler_entry",
+ (PyObject*) &StatsEntryType);
+ PyModule_AddObject(module, "profiler_subentry",
+ (PyObject*) &StatsSubEntryType);
+ empty_tuple = PyTuple_New(0);
+ initialized = 1;
+ return module;
}
diff --git a/Modules/_math.c b/Modules/_math.c
index 995d1c0..b5d8b45 100644
--- a/Modules/_math.c
+++ b/Modules/_math.c
@@ -14,7 +14,7 @@
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
- * software is freely granted, provided that this notice
+ * software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
@@ -27,11 +27,11 @@ static const double zero = 0.0;
/* acosh(x)
* Method :
* Based on
- * acosh(x) = log [ x + sqrt(x*x-1) ]
+ * acosh(x) = log [ x + sqrt(x*x-1) ]
* we have
- * acosh(x) := log(x)+ln2, if x is large; else
- * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
- * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
+ * acosh(x) := log(x)+ln2, if x is large; else
+ * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
+ * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
*
* Special cases:
* acosh(x) is NaN with signal if x<1.
@@ -41,82 +41,82 @@ static const double zero = 0.0;
double
_Py_acosh(double x)
{
- if (Py_IS_NAN(x)) {
- return x+x;
- }
- if (x < 1.) { /* x < 1; return a signaling NaN */
- errno = EDOM;
+ if (Py_IS_NAN(x)) {
+ return x+x;
+ }
+ if (x < 1.) { /* x < 1; return a signaling NaN */
+ errno = EDOM;
#ifdef Py_NAN
- return Py_NAN;
+ return Py_NAN;
#else
- return (x-x)/(x-x);
+ return (x-x)/(x-x);
#endif
- }
- else if (x >= two_pow_p28) { /* x > 2**28 */
- if (Py_IS_INFINITY(x)) {
- return x+x;
- } else {
- return log(x)+ln2; /* acosh(huge)=log(2x) */
- }
- }
- else if (x == 1.) {
- return 0.0; /* acosh(1) = 0 */
- }
- else if (x > 2.) { /* 2 < x < 2**28 */
- double t = x*x;
- return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
- }
- else { /* 1 < x <= 2 */
- double t = x - 1.0;
- return m_log1p(t + sqrt(2.0*t + t*t));
- }
+ }
+ else if (x >= two_pow_p28) { /* x > 2**28 */
+ if (Py_IS_INFINITY(x)) {
+ return x+x;
+ } else {
+ return log(x)+ln2; /* acosh(huge)=log(2x) */
+ }
+ }
+ else if (x == 1.) {
+ return 0.0; /* acosh(1) = 0 */
+ }
+ else if (x > 2.) { /* 2 < x < 2**28 */
+ double t = x*x;
+ return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
+ }
+ else { /* 1 < x <= 2 */
+ double t = x - 1.0;
+ return m_log1p(t + sqrt(2.0*t + t*t));
+ }
}
/* asinh(x)
* Method :
- * Based on
- * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
- * we have
- * asinh(x) := x if 1+x*x=1,
- * := sign(x)*(log(x)+ln2)) for large |x|, else
- * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
- * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2)))
+ * Based on
+ * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
+ * we have
+ * asinh(x) := x if 1+x*x=1,
+ * := sign(x)*(log(x)+ln2)) for large |x|, else
+ * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
+ * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2)))
*/
double
_Py_asinh(double x)
-{
- double w;
- double absx = fabs(x);
-
- if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
- return x+x;
- }
- if (absx < two_pow_m28) { /* |x| < 2**-28 */
- return x; /* return x inexact except 0 */
- }
- if (absx > two_pow_p28) { /* |x| > 2**28 */
- w = log(absx)+ln2;
- }
- else if (absx > 2.0) { /* 2 < |x| < 2**28 */
- w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
- }
- else { /* 2**-28 <= |x| < 2= */
- double t = x*x;
- w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
- }
- return copysign(w, x);
-
+{
+ double w;
+ double absx = fabs(x);
+
+ if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
+ return x+x;
+ }
+ if (absx < two_pow_m28) { /* |x| < 2**-28 */
+ return x; /* return x inexact except 0 */
+ }
+ if (absx > two_pow_p28) { /* |x| > 2**28 */
+ w = log(absx)+ln2;
+ }
+ else if (absx > 2.0) { /* 2 < |x| < 2**28 */
+ w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
+ }
+ else { /* 2**-28 <= |x| < 2= */
+ double t = x*x;
+ w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
+ }
+ return copysign(w, x);
+
}
/* atanh(x)
* Method :
* 1.Reduced x to positive by atanh(-x) = -atanh(x)
* 2.For x>=0.5
- * 1 2x x
+ * 1 2x x
* atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------)
- * 2 1 - x 1 - x
+ * 2 1 - x 1 - x
*
* For x<0.5
* atanh(x) = 0.5*log1p(2x+2x*x/(1-x))
@@ -130,32 +130,32 @@ _Py_asinh(double x)
double
_Py_atanh(double x)
{
- double absx;
- double t;
-
- if (Py_IS_NAN(x)) {
- return x+x;
- }
- absx = fabs(x);
- if (absx >= 1.) { /* |x| >= 1 */
- errno = EDOM;
+ double absx;
+ double t;
+
+ if (Py_IS_NAN(x)) {
+ return x+x;
+ }
+ absx = fabs(x);
+ if (absx >= 1.) { /* |x| >= 1 */
+ errno = EDOM;
#ifdef Py_NAN
- return Py_NAN;
+ return Py_NAN;
#else
- return x/zero;
+ return x/zero;
#endif
- }
- if (absx < two_pow_m28) { /* |x| < 2**-28 */
- return x;
- }
- if (absx < 0.5) { /* |x| < 0.5 */
- t = absx+absx;
- t = 0.5 * m_log1p(t + t*absx / (1.0 - absx));
- }
- else { /* 0.5 <= |x| <= 1.0 */
- t = 0.5 * m_log1p((absx + absx) / (1.0 - absx));
- }
- return copysign(t, x);
+ }
+ if (absx < two_pow_m28) { /* |x| < 2**-28 */
+ return x;
+ }
+ if (absx < 0.5) { /* |x| < 0.5 */
+ t = absx+absx;
+ t = 0.5 * m_log1p(t + t*absx / (1.0 - absx));
+ }
+ else { /* 0.5 <= |x| <= 1.0 */
+ t = 0.5 * m_log1p((absx + absx) / (1.0 - absx));
+ }
+ return copysign(t, x);
}
/* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed
@@ -173,15 +173,15 @@ _Py_expm1(double x)
*/
if (fabs(x) < 0.7) {
- double u;
- u = exp(x);
- if (u == 1.0)
- return x;
- else
- return (u - 1.0) * x / log(u);
+ double u;
+ u = exp(x);
+ if (u == 1.0)
+ return x;
+ else
+ return (u - 1.0) * x / log(u);
}
else
- return exp(x) - 1.0;
+ return exp(x) - 1.0;
}
/* log1p(x) = log(1+x). The log1p function is designed to avoid the
@@ -194,7 +194,7 @@ _Py_log1p(double x)
/* For x small, we use the following approach. Let y be the nearest float
to 1+x, then
- 1+x = y * (1 - (y-1-x)/y)
+ 1+x = y * (1 - (y-1-x)/y)
so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, the
second term is well approximated by (y-1-x)/y. If abs(x) >=
@@ -213,17 +213,17 @@ _Py_log1p(double x)
double y;
if (fabs(x) < DBL_EPSILON/2.) {
- return x;
+ return x;
} else if (-0.5 <= x && x <= 1.) {
- /* WARNING: it's possible than an overeager compiler
- will incorrectly optimize the following two lines
- to the equivalent of "return log(1.+x)". If this
- happens, then results from log1p will be inaccurate
- for small x. */
- y = 1.+x;
- return log(y)-((y-1.)-x)/y;
+ /* WARNING: it's possible than an overeager compiler
+ will incorrectly optimize the following two lines
+ to the equivalent of "return log(1.+x)". If this
+ happens, then results from log1p will be inaccurate
+ for small x. */
+ y = 1.+x;
+ return log(y)-((y-1.)-x)/y;
} else {
- /* NaNs and infinities should end up here */
- return log(1.+x);
+ /* NaNs and infinities should end up here */
+ return log(1.+x);
}
}
diff --git a/Modules/_multiprocessing/connection.h b/Modules/_multiprocessing/connection.h
index 2ee5368..002d5aa 100644
--- a/Modules/_multiprocessing/connection.h
+++ b/Modules/_multiprocessing/connection.h
@@ -1,5 +1,5 @@
/*
- * Definition of a `Connection` type.
+ * Definition of a `Connection` type.
* Used by `socket_connection.c` and `pipe_connection.c`.
*
* connection.h
@@ -19,14 +19,14 @@
#define CHECK_READABLE(self) \
if (!(self->flags & READABLE)) { \
- PyErr_SetString(PyExc_IOError, "connection is write-only"); \
- return NULL; \
+ PyErr_SetString(PyExc_IOError, "connection is write-only"); \
+ return NULL; \
}
#define CHECK_WRITABLE(self) \
if (!(self->flags & WRITABLE)) { \
- PyErr_SetString(PyExc_IOError, "connection is read-only"); \
- return NULL; \
+ PyErr_SetString(PyExc_IOError, "connection is read-only"); \
+ return NULL; \
}
/*
@@ -36,57 +36,57 @@
static PyObject *
connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- ConnectionObject *self;
- HANDLE handle;
- BOOL readable = TRUE, writable = TRUE;
-
- static char *kwlist[] = {"handle", "readable", "writable", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist,
- &handle, &readable, &writable))
- return NULL;
-
- if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) {
- PyErr_Format(PyExc_IOError, "invalid handle %zd",
- (Py_ssize_t)handle);
- return NULL;
- }
-
- if (!readable && !writable) {
- PyErr_SetString(PyExc_ValueError,
- "either readable or writable must be true");
- return NULL;
- }
-
- self = PyObject_New(ConnectionObject, type);
- if (self == NULL)
- return NULL;
-
- self->weakreflist = NULL;
- self->handle = handle;
- self->flags = 0;
-
- if (readable)
- self->flags |= READABLE;
- if (writable)
- self->flags |= WRITABLE;
- assert(self->flags >= 1 && self->flags <= 3);
-
- return (PyObject*)self;
+ ConnectionObject *self;
+ HANDLE handle;
+ BOOL readable = TRUE, writable = TRUE;
+
+ static char *kwlist[] = {"handle", "readable", "writable", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist,
+ &handle, &readable, &writable))
+ return NULL;
+
+ if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) {
+ PyErr_Format(PyExc_IOError, "invalid handle %zd",
+ (Py_ssize_t)handle);
+ return NULL;
+ }
+
+ if (!readable && !writable) {
+ PyErr_SetString(PyExc_ValueError,
+ "either readable or writable must be true");
+ return NULL;
+ }
+
+ self = PyObject_New(ConnectionObject, type);
+ if (self == NULL)
+ return NULL;
+
+ self->weakreflist = NULL;
+ self->handle = handle;
+ self->flags = 0;
+
+ if (readable)
+ self->flags |= READABLE;
+ if (writable)
+ self->flags |= WRITABLE;
+ assert(self->flags >= 1 && self->flags <= 3);
+
+ return (PyObject*)self;
}
static void
connection_dealloc(ConnectionObject* self)
{
- if (self->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject*)self);
-
- if (self->handle != INVALID_HANDLE_VALUE) {
- Py_BEGIN_ALLOW_THREADS
- CLOSE(self->handle);
- Py_END_ALLOW_THREADS
- }
- PyObject_Del(self);
+ if (self->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject*)self);
+
+ if (self->handle != INVALID_HANDLE_VALUE) {
+ Py_BEGIN_ALLOW_THREADS
+ CLOSE(self->handle);
+ Py_END_ALLOW_THREADS
+ }
+ PyObject_Del(self);
}
/*
@@ -96,168 +96,168 @@ connection_dealloc(ConnectionObject* self)
static PyObject *
connection_sendbytes(ConnectionObject *self, PyObject *args)
{
- Py_buffer pbuffer;
- char *buffer;
- Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN;
- int res;
-
- if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T,
- &pbuffer, &offset, &size))
- return NULL;
- buffer = pbuffer.buf;
- length = pbuffer.len;
-
- CHECK_WRITABLE(self); /* XXX release buffer in case of failure */
-
- if (offset < 0) {
- PyBuffer_Release(&pbuffer);
- PyErr_SetString(PyExc_ValueError, "offset is negative");
- return NULL;
- }
- if (length < offset) {
- PyBuffer_Release(&pbuffer);
- PyErr_SetString(PyExc_ValueError, "buffer length < offset");
- return NULL;
- }
-
- if (size == PY_SSIZE_T_MIN) {
- size = length - offset;
- } else {
- if (size < 0) {
- PyBuffer_Release(&pbuffer);
- PyErr_SetString(PyExc_ValueError, "size is negative");
- return NULL;
- }
- if (offset + size > length) {
- PyBuffer_Release(&pbuffer);
- PyErr_SetString(PyExc_ValueError,
- "buffer length < offset + size");
- return NULL;
- }
- }
-
- res = conn_send_string(self, buffer + offset, size);
-
- PyBuffer_Release(&pbuffer);
- if (res < 0) {
- if (PyErr_Occurred())
- return NULL;
- else
- return mp_SetError(PyExc_IOError, res);
- }
-
- Py_RETURN_NONE;
+ Py_buffer pbuffer;
+ char *buffer;
+ Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN;
+ int res;
+
+ if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T,
+ &pbuffer, &offset, &size))
+ return NULL;
+ buffer = pbuffer.buf;
+ length = pbuffer.len;
+
+ CHECK_WRITABLE(self); /* XXX release buffer in case of failure */
+
+ if (offset < 0) {
+ PyBuffer_Release(&pbuffer);
+ PyErr_SetString(PyExc_ValueError, "offset is negative");
+ return NULL;
+ }
+ if (length < offset) {
+ PyBuffer_Release(&pbuffer);
+ PyErr_SetString(PyExc_ValueError, "buffer length < offset");
+ return NULL;
+ }
+
+ if (size == PY_SSIZE_T_MIN) {
+ size = length - offset;
+ } else {
+ if (size < 0) {
+ PyBuffer_Release(&pbuffer);
+ PyErr_SetString(PyExc_ValueError, "size is negative");
+ return NULL;
+ }
+ if (offset + size > length) {
+ PyBuffer_Release(&pbuffer);
+ PyErr_SetString(PyExc_ValueError,
+ "buffer length < offset + size");
+ return NULL;
+ }
+ }
+
+ res = conn_send_string(self, buffer + offset, size);
+
+ PyBuffer_Release(&pbuffer);
+ if (res < 0) {
+ if (PyErr_Occurred())
+ return NULL;
+ else
+ return mp_SetError(PyExc_IOError, res);
+ }
+
+ Py_RETURN_NONE;
}
static PyObject *
-connection_recvbytes(ConnectionObject *self, PyObject *args)
+connection_recvbytes(ConnectionObject *self, PyObject *args)
{
- char *freeme = NULL;
- Py_ssize_t res, maxlength = PY_SSIZE_T_MAX;
- PyObject *result = NULL;
-
- if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
- return NULL;
-
- CHECK_READABLE(self);
-
- if (maxlength < 0) {
- PyErr_SetString(PyExc_ValueError, "maxlength < 0");
- return NULL;
- }
-
- res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
- &freeme, maxlength);
-
- if (res < 0) {
- if (res == MP_BAD_MESSAGE_LENGTH) {
- if ((self->flags & WRITABLE) == 0) {
- Py_BEGIN_ALLOW_THREADS
- CLOSE(self->handle);
- Py_END_ALLOW_THREADS
- self->handle = INVALID_HANDLE_VALUE;
- } else {
- self->flags = WRITABLE;
- }
- }
- mp_SetError(PyExc_IOError, res);
- } else {
- if (freeme == NULL) {
- result = PyBytes_FromStringAndSize(self->buffer, res);
- } else {
- result = PyBytes_FromStringAndSize(freeme, res);
- PyMem_Free(freeme);
- }
- }
-
- return result;
+ char *freeme = NULL;
+ Py_ssize_t res, maxlength = PY_SSIZE_T_MAX;
+ PyObject *result = NULL;
+
+ if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
+ return NULL;
+
+ CHECK_READABLE(self);
+
+ if (maxlength < 0) {
+ PyErr_SetString(PyExc_ValueError, "maxlength < 0");
+ return NULL;
+ }
+
+ res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
+ &freeme, maxlength);
+
+ if (res < 0) {
+ if (res == MP_BAD_MESSAGE_LENGTH) {
+ if ((self->flags & WRITABLE) == 0) {
+ Py_BEGIN_ALLOW_THREADS
+ CLOSE(self->handle);
+ Py_END_ALLOW_THREADS
+ self->handle = INVALID_HANDLE_VALUE;
+ } else {
+ self->flags = WRITABLE;
+ }
+ }
+ mp_SetError(PyExc_IOError, res);
+ } else {
+ if (freeme == NULL) {
+ result = PyBytes_FromStringAndSize(self->buffer, res);
+ } else {
+ result = PyBytes_FromStringAndSize(freeme, res);
+ PyMem_Free(freeme);
+ }
+ }
+
+ return result;
}
static PyObject *
-connection_recvbytes_into(ConnectionObject *self, PyObject *args)
+connection_recvbytes_into(ConnectionObject *self, PyObject *args)
{
- char *freeme = NULL, *buffer = NULL;
- Py_ssize_t res, length, offset = 0;
- PyObject *result = NULL;
- Py_buffer pbuf;
-
- CHECK_READABLE(self);
-
- if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
- &pbuf, &offset))
- return NULL;
-
- buffer = pbuf.buf;
- length = pbuf.len;
-
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError, "negative offset");
- goto _error;
- }
-
- if (offset > length) {
- PyErr_SetString(PyExc_ValueError, "offset too large");
- goto _error;
- }
-
- res = conn_recv_string(self, buffer+offset, length-offset,
- &freeme, PY_SSIZE_T_MAX);
-
- if (res < 0) {
- if (res == MP_BAD_MESSAGE_LENGTH) {
- if ((self->flags & WRITABLE) == 0) {
- Py_BEGIN_ALLOW_THREADS
- CLOSE(self->handle);
- Py_END_ALLOW_THREADS
- self->handle = INVALID_HANDLE_VALUE;
- } else {
- self->flags = WRITABLE;
- }
- }
- mp_SetError(PyExc_IOError, res);
- } else {
- if (freeme == NULL) {
- result = PyInt_FromSsize_t(res);
- } else {
- result = PyObject_CallFunction(BufferTooShort,
- F_RBUFFER "#",
- freeme, res);
- PyMem_Free(freeme);
- if (result) {
- PyErr_SetObject(BufferTooShort, result);
- Py_DECREF(result);
- }
- goto _error;
- }
- }
+ char *freeme = NULL, *buffer = NULL;
+ Py_ssize_t res, length, offset = 0;
+ PyObject *result = NULL;
+ Py_buffer pbuf;
+
+ CHECK_READABLE(self);
+
+ if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
+ &pbuf, &offset))
+ return NULL;
+
+ buffer = pbuf.buf;
+ length = pbuf.len;
+
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError, "negative offset");
+ goto _error;
+ }
+
+ if (offset > length) {
+ PyErr_SetString(PyExc_ValueError, "offset too large");
+ goto _error;
+ }
+
+ res = conn_recv_string(self, buffer+offset, length-offset,
+ &freeme, PY_SSIZE_T_MAX);
+
+ if (res < 0) {
+ if (res == MP_BAD_MESSAGE_LENGTH) {
+ if ((self->flags & WRITABLE) == 0) {
+ Py_BEGIN_ALLOW_THREADS
+ CLOSE(self->handle);
+ Py_END_ALLOW_THREADS
+ self->handle = INVALID_HANDLE_VALUE;
+ } else {
+ self->flags = WRITABLE;
+ }
+ }
+ mp_SetError(PyExc_IOError, res);
+ } else {
+ if (freeme == NULL) {
+ result = PyInt_FromSsize_t(res);
+ } else {
+ result = PyObject_CallFunction(BufferTooShort,
+ F_RBUFFER "#",
+ freeme, res);
+ PyMem_Free(freeme);
+ if (result) {
+ PyErr_SetObject(BufferTooShort, result);
+ Py_DECREF(result);
+ }
+ goto _error;
+ }
+ }
_cleanup:
- PyBuffer_Release(&pbuf);
- return result;
+ PyBuffer_Release(&pbuf);
+ return result;
_error:
- result = NULL;
- goto _cleanup;
+ result = NULL;
+ goto _cleanup;
}
/*
@@ -267,74 +267,74 @@ _error:
static PyObject *
connection_send_obj(ConnectionObject *self, PyObject *obj)
{
- char *buffer;
- int res;
- Py_ssize_t length;
- PyObject *pickled_string = NULL;
+ char *buffer;
+ int res;
+ Py_ssize_t length;
+ PyObject *pickled_string = NULL;
- CHECK_WRITABLE(self);
+ CHECK_WRITABLE(self);
- pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj,
- pickle_protocol, NULL);
- if (!pickled_string)
- goto failure;
+ pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj,
+ pickle_protocol, NULL);
+ if (!pickled_string)
+ goto failure;
- if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0)
- goto failure;
+ if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0)
+ goto failure;
- res = conn_send_string(self, buffer, (int)length);
+ res = conn_send_string(self, buffer, (int)length);
- if (res < 0) {
- mp_SetError(PyExc_IOError, res);
- goto failure;
- }
+ if (res < 0) {
+ mp_SetError(PyExc_IOError, res);
+ goto failure;
+ }
- Py_XDECREF(pickled_string);
- Py_RETURN_NONE;
+ Py_XDECREF(pickled_string);
+ Py_RETURN_NONE;
failure:
- Py_XDECREF(pickled_string);
- return NULL;
+ Py_XDECREF(pickled_string);
+ return NULL;
}
static PyObject *
connection_recv_obj(ConnectionObject *self)
{
- char *freeme = NULL;
- Py_ssize_t res;
- PyObject *temp = NULL, *result = NULL;
-
- CHECK_READABLE(self);
-
- res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
- &freeme, PY_SSIZE_T_MAX);
-
- if (res < 0) {
- if (res == MP_BAD_MESSAGE_LENGTH) {
- if ((self->flags & WRITABLE) == 0) {
- Py_BEGIN_ALLOW_THREADS
- CLOSE(self->handle);
- Py_END_ALLOW_THREADS
- self->handle = INVALID_HANDLE_VALUE;
- } else {
- self->flags = WRITABLE;
- }
- }
- mp_SetError(PyExc_IOError, res);
- } else {
- if (freeme == NULL) {
- temp = PyBytes_FromStringAndSize(self->buffer, res);
- } else {
- temp = PyBytes_FromStringAndSize(freeme, res);
- PyMem_Free(freeme);
- }
- }
-
- if (temp)
- result = PyObject_CallFunctionObjArgs(pickle_loads,
- temp, NULL);
- Py_XDECREF(temp);
- return result;
+ char *freeme = NULL;
+ Py_ssize_t res;
+ PyObject *temp = NULL, *result = NULL;
+
+ CHECK_READABLE(self);
+
+ res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
+ &freeme, PY_SSIZE_T_MAX);
+
+ if (res < 0) {
+ if (res == MP_BAD_MESSAGE_LENGTH) {
+ if ((self->flags & WRITABLE) == 0) {
+ Py_BEGIN_ALLOW_THREADS
+ CLOSE(self->handle);
+ Py_END_ALLOW_THREADS
+ self->handle = INVALID_HANDLE_VALUE;
+ } else {
+ self->flags = WRITABLE;
+ }
+ }
+ mp_SetError(PyExc_IOError, res);
+ } else {
+ if (freeme == NULL) {
+ temp = PyBytes_FromStringAndSize(self->buffer, res);
+ } else {
+ temp = PyBytes_FromStringAndSize(freeme, res);
+ PyMem_Free(freeme);
+ }
+ }
+
+ if (temp)
+ result = PyObject_CallFunctionObjArgs(pickle_loads,
+ temp, NULL);
+ Py_XDECREF(temp);
+ return result;
}
/*
@@ -344,73 +344,73 @@ connection_recv_obj(ConnectionObject *self)
static PyObject *
connection_poll(ConnectionObject *self, PyObject *args)
{
- PyObject *timeout_obj = NULL;
- double timeout = 0.0;
- int res;
-
- CHECK_READABLE(self);
-
- if (!PyArg_ParseTuple(args, "|O", &timeout_obj))
- return NULL;
-
- if (timeout_obj == NULL) {
- timeout = 0.0;
- } else if (timeout_obj == Py_None) {
- timeout = -1.0; /* block forever */
- } else {
- timeout = PyFloat_AsDouble(timeout_obj);
- if (PyErr_Occurred())
- return NULL;
- if (timeout < 0.0)
- timeout = 0.0;
- }
-
- Py_BEGIN_ALLOW_THREADS
- res = conn_poll(self, timeout, _save);
- Py_END_ALLOW_THREADS
-
- switch (res) {
- case TRUE:
- Py_RETURN_TRUE;
- case FALSE:
- Py_RETURN_FALSE;
- default:
- return mp_SetError(PyExc_IOError, res);
- }
+ PyObject *timeout_obj = NULL;
+ double timeout = 0.0;
+ int res;
+
+ CHECK_READABLE(self);
+
+ if (!PyArg_ParseTuple(args, "|O", &timeout_obj))
+ return NULL;
+
+ if (timeout_obj == NULL) {
+ timeout = 0.0;
+ } else if (timeout_obj == Py_None) {
+ timeout = -1.0; /* block forever */
+ } else {
+ timeout = PyFloat_AsDouble(timeout_obj);
+ if (PyErr_Occurred())
+ return NULL;
+ if (timeout < 0.0)
+ timeout = 0.0;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ res = conn_poll(self, timeout, _save);
+ Py_END_ALLOW_THREADS
+
+ switch (res) {
+ case TRUE:
+ Py_RETURN_TRUE;
+ case FALSE:
+ Py_RETURN_FALSE;
+ default:
+ return mp_SetError(PyExc_IOError, res);
+ }
}
static PyObject *
connection_fileno(ConnectionObject* self)
{
- if (self->handle == INVALID_HANDLE_VALUE) {
- PyErr_SetString(PyExc_IOError, "handle is invalid");
- return NULL;
- }
- return PyInt_FromLong((long)self->handle);
+ if (self->handle == INVALID_HANDLE_VALUE) {
+ PyErr_SetString(PyExc_IOError, "handle is invalid");
+ return NULL;
+ }
+ return PyInt_FromLong((long)self->handle);
}
static PyObject *
connection_close(ConnectionObject *self)
{
- if (self->handle != INVALID_HANDLE_VALUE) {
- Py_BEGIN_ALLOW_THREADS
- CLOSE(self->handle);
- Py_END_ALLOW_THREADS
- self->handle = INVALID_HANDLE_VALUE;
- }
-
- Py_RETURN_NONE;
+ if (self->handle != INVALID_HANDLE_VALUE) {
+ Py_BEGIN_ALLOW_THREADS
+ CLOSE(self->handle);
+ Py_END_ALLOW_THREADS
+ self->handle = INVALID_HANDLE_VALUE;
+ }
+
+ Py_RETURN_NONE;
}
static PyObject *
connection_repr(ConnectionObject *self)
{
- static char *conn_type[] = {"read-only", "write-only", "read-write"};
+ static char *conn_type[] = {"read-only", "write-only", "read-write"};
- assert(self->flags >= 1 && self->flags <= 3);
- return FROM_FORMAT("<%s %s, handle %zd>",
- conn_type[self->flags - 1],
- CONNECTION_NAME, (Py_ssize_t)self->handle);
+ assert(self->flags >= 1 && self->flags <= 3);
+ return FROM_FORMAT("<%s %s, handle %zd>",
+ conn_type[self->flags - 1],
+ CONNECTION_NAME, (Py_ssize_t)self->handle);
}
/*
@@ -420,19 +420,19 @@ connection_repr(ConnectionObject *self)
static PyObject *
connection_closed(ConnectionObject *self, void *closure)
{
- return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE));
+ return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE));
}
static PyObject *
connection_readable(ConnectionObject *self, void *closure)
{
- return PyBool_FromLong((long)(self->flags & READABLE));
+ return PyBool_FromLong((long)(self->flags & READABLE));
}
static PyObject *
connection_writable(ConnectionObject *self, void *closure)
{
- return PyBool_FromLong((long)(self->flags & WRITABLE));
+ return PyBool_FromLong((long)(self->flags & WRITABLE));
}
/*
@@ -440,37 +440,37 @@ connection_writable(ConnectionObject *self, void *closure)
*/
static PyMethodDef connection_methods[] = {
- {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS,
- "send the byte data from a readable buffer-like object"},
- {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS,
- "receive byte data as a string"},
- {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS,
- "receive byte data into a writeable buffer-like object\n"
- "returns the number of bytes read"},
-
- {"send", (PyCFunction)connection_send_obj, METH_O,
- "send a (picklable) object"},
- {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS,
- "receive a (picklable) object"},
-
- {"poll", (PyCFunction)connection_poll, METH_VARARGS,
- "whether there is any input available to be read"},
- {"fileno", (PyCFunction)connection_fileno, METH_NOARGS,
- "file descriptor or handle of the connection"},
- {"close", (PyCFunction)connection_close, METH_NOARGS,
- "close the connection"},
-
- {NULL} /* Sentinel */
+ {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS,
+ "send the byte data from a readable buffer-like object"},
+ {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS,
+ "receive byte data as a string"},
+ {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS,
+ "receive byte data into a writeable buffer-like object\n"
+ "returns the number of bytes read"},
+
+ {"send", (PyCFunction)connection_send_obj, METH_O,
+ "send a (picklable) object"},
+ {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS,
+ "receive a (picklable) object"},
+
+ {"poll", (PyCFunction)connection_poll, METH_VARARGS,
+ "whether there is any input available to be read"},
+ {"fileno", (PyCFunction)connection_fileno, METH_NOARGS,
+ "file descriptor or handle of the connection"},
+ {"close", (PyCFunction)connection_close, METH_NOARGS,
+ "close the connection"},
+
+ {NULL} /* Sentinel */
};
static PyGetSetDef connection_getset[] = {
- {"closed", (getter)connection_closed, NULL,
- "True if the connection is closed", NULL},
- {"readable", (getter)connection_readable, NULL,
- "True if the connection is readable", NULL},
- {"writable", (getter)connection_writable, NULL,
- "True if the connection is writable", NULL},
- {NULL}
+ {"closed", (getter)connection_closed, NULL,
+ "True if the connection is closed", NULL},
+ {"readable", (getter)connection_readable, NULL,
+ "True if the connection is readable", NULL},
+ {"writable", (getter)connection_writable, NULL,
+ "True if the connection is writable", NULL},
+ {NULL}
};
/*
@@ -478,50 +478,50 @@ static PyGetSetDef connection_getset[] = {
*/
PyDoc_STRVAR(connection_doc,
- "Connection type whose constructor signature is\n\n"
- " Connection(handle, readable=True, writable=True).\n\n"
- "The constructor does *not* duplicate the handle.");
+ "Connection type whose constructor signature is\n\n"
+ " Connection(handle, readable=True, writable=True).\n\n"
+ "The constructor does *not* duplicate the handle.");
PyTypeObject CONNECTION_TYPE = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* tp_name */ "_multiprocessing." CONNECTION_NAME,
- /* tp_basicsize */ sizeof(ConnectionObject),
- /* tp_itemsize */ 0,
- /* tp_dealloc */ (destructor)connection_dealloc,
- /* tp_print */ 0,
- /* tp_getattr */ 0,
- /* tp_setattr */ 0,
- /* tp_reserved */ 0,
- /* tp_repr */ (reprfunc)connection_repr,
- /* 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 */ 0,
- /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_HAVE_WEAKREFS,
- /* tp_doc */ connection_doc,
- /* tp_traverse */ 0,
- /* tp_clear */ 0,
- /* tp_richcompare */ 0,
- /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist),
- /* tp_iter */ 0,
- /* tp_iternext */ 0,
- /* tp_methods */ connection_methods,
- /* tp_members */ 0,
- /* tp_getset */ connection_getset,
- /* tp_base */ 0,
- /* tp_dict */ 0,
- /* tp_descr_get */ 0,
- /* tp_descr_set */ 0,
- /* tp_dictoffset */ 0,
- /* tp_init */ 0,
- /* tp_alloc */ 0,
- /* tp_new */ connection_new,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* tp_name */ "_multiprocessing." CONNECTION_NAME,
+ /* tp_basicsize */ sizeof(ConnectionObject),
+ /* tp_itemsize */ 0,
+ /* tp_dealloc */ (destructor)connection_dealloc,
+ /* tp_print */ 0,
+ /* tp_getattr */ 0,
+ /* tp_setattr */ 0,
+ /* tp_reserved */ 0,
+ /* tp_repr */ (reprfunc)connection_repr,
+ /* 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 */ 0,
+ /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_WEAKREFS,
+ /* tp_doc */ connection_doc,
+ /* tp_traverse */ 0,
+ /* tp_clear */ 0,
+ /* tp_richcompare */ 0,
+ /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist),
+ /* tp_iter */ 0,
+ /* tp_iternext */ 0,
+ /* tp_methods */ connection_methods,
+ /* tp_members */ 0,
+ /* tp_getset */ connection_getset,
+ /* tp_base */ 0,
+ /* tp_dict */ 0,
+ /* tp_descr_get */ 0,
+ /* tp_descr_set */ 0,
+ /* tp_dictoffset */ 0,
+ /* tp_init */ 0,
+ /* tp_alloc */ 0,
+ /* tp_new */ connection_new,
};
#endif /* CONNECTION_H */
diff --git a/Modules/_multiprocessing/multiprocessing.c b/Modules/_multiprocessing/multiprocessing.c
index b09fb25..c584f2b 100644
--- a/Modules/_multiprocessing/multiprocessing.c
+++ b/Modules/_multiprocessing/multiprocessing.c
@@ -9,9 +9,9 @@
#include "multiprocessing.h"
#ifdef SCM_RIGHTS
- #define HAVE_FD_TRANSFER 1
+ #define HAVE_FD_TRANSFER 1
#else
- #define HAVE_FD_TRANSFER 0
+ #define HAVE_FD_TRANSFER 0
#endif
PyObject *create_win32_namespace(void);
@@ -26,46 +26,46 @@ PyObject *ProcessError, *BufferTooShort;
PyObject *
mp_SetError(PyObject *Type, int num)
{
- switch (num) {
+ switch (num) {
#ifdef MS_WINDOWS
- case MP_STANDARD_ERROR:
- if (Type == NULL)
- Type = PyExc_WindowsError;
- PyErr_SetExcFromWindowsErr(Type, 0);
- break;
- case MP_SOCKET_ERROR:
- if (Type == NULL)
- Type = PyExc_WindowsError;
- PyErr_SetExcFromWindowsErr(Type, WSAGetLastError());
- break;
+ case MP_STANDARD_ERROR:
+ if (Type == NULL)
+ Type = PyExc_WindowsError;
+ PyErr_SetExcFromWindowsErr(Type, 0);
+ break;
+ case MP_SOCKET_ERROR:
+ if (Type == NULL)
+ Type = PyExc_WindowsError;
+ PyErr_SetExcFromWindowsErr(Type, WSAGetLastError());
+ break;
#else /* !MS_WINDOWS */
- case MP_STANDARD_ERROR:
- case MP_SOCKET_ERROR:
- if (Type == NULL)
- Type = PyExc_OSError;
- PyErr_SetFromErrno(Type);
- break;
+ case MP_STANDARD_ERROR:
+ case MP_SOCKET_ERROR:
+ if (Type == NULL)
+ Type = PyExc_OSError;
+ PyErr_SetFromErrno(Type);
+ break;
#endif /* !MS_WINDOWS */
- case MP_MEMORY_ERROR:
- PyErr_NoMemory();
- break;
- case MP_END_OF_FILE:
- PyErr_SetNone(PyExc_EOFError);
- break;
- case MP_EARLY_END_OF_FILE:
- PyErr_SetString(PyExc_IOError,
- "got end of file during message");
- break;
- case MP_BAD_MESSAGE_LENGTH:
- PyErr_SetString(PyExc_IOError, "bad message length");
- break;
- case MP_EXCEPTION_HAS_BEEN_SET:
- break;
- default:
- PyErr_Format(PyExc_RuntimeError,
- "unkown error number %d", num);
- }
- return NULL;
+ case MP_MEMORY_ERROR:
+ PyErr_NoMemory();
+ break;
+ case MP_END_OF_FILE:
+ PyErr_SetNone(PyExc_EOFError);
+ break;
+ case MP_EARLY_END_OF_FILE:
+ PyErr_SetString(PyExc_IOError,
+ "got end of file during message");
+ break;
+ case MP_BAD_MESSAGE_LENGTH:
+ PyErr_SetString(PyExc_IOError, "bad message length");
+ break;
+ case MP_EXCEPTION_HAS_BEEN_SET:
+ break;
+ default:
+ PyErr_Format(PyExc_RuntimeError,
+ "unkown error number %d", num);
+ }
+ return NULL;
}
@@ -82,8 +82,8 @@ HANDLE sigint_event = NULL;
static BOOL WINAPI
ProcessingCtrlHandler(DWORD dwCtrlType)
{
- SetEvent(sigint_event);
- return FALSE;
+ SetEvent(sigint_event);
+ return FALSE;
}
/*
@@ -101,72 +101,72 @@ ProcessingCtrlHandler(DWORD dwCtrlType)
static PyObject *
multiprocessing_sendfd(PyObject *self, PyObject *args)
{
- int conn, fd, res;
- char dummy_char;
- char buf[CMSG_SPACE(sizeof(int))];
- struct msghdr msg = {0};
- struct iovec dummy_iov;
- struct cmsghdr *cmsg;
-
- if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
- return NULL;
-
- dummy_iov.iov_base = &dummy_char;
- dummy_iov.iov_len = 1;
- msg.msg_control = buf;
- msg.msg_controllen = sizeof(buf);
- msg.msg_iov = &dummy_iov;
- msg.msg_iovlen = 1;
- cmsg = CMSG_FIRSTHDR(&msg);
- cmsg->cmsg_level = SOL_SOCKET;
- cmsg->cmsg_type = SCM_RIGHTS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(int));
- msg.msg_controllen = cmsg->cmsg_len;
- *(int*)CMSG_DATA(cmsg) = fd;
-
- Py_BEGIN_ALLOW_THREADS
- res = sendmsg(conn, &msg, 0);
- Py_END_ALLOW_THREADS
-
- if (res < 0)
- return PyErr_SetFromErrno(PyExc_OSError);
- Py_RETURN_NONE;
+ int conn, fd, res;
+ char dummy_char;
+ char buf[CMSG_SPACE(sizeof(int))];
+ struct msghdr msg = {0};
+ struct iovec dummy_iov;
+ struct cmsghdr *cmsg;
+
+ if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
+ return NULL;
+
+ dummy_iov.iov_base = &dummy_char;
+ dummy_iov.iov_len = 1;
+ msg.msg_control = buf;
+ msg.msg_controllen = sizeof(buf);
+ msg.msg_iov = &dummy_iov;
+ msg.msg_iovlen = 1;
+ cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+ msg.msg_controllen = cmsg->cmsg_len;
+ *(int*)CMSG_DATA(cmsg) = fd;
+
+ Py_BEGIN_ALLOW_THREADS
+ res = sendmsg(conn, &msg, 0);
+ Py_END_ALLOW_THREADS
+
+ if (res < 0)
+ return PyErr_SetFromErrno(PyExc_OSError);
+ Py_RETURN_NONE;
}
static PyObject *
multiprocessing_recvfd(PyObject *self, PyObject *args)
{
- int conn, fd, res;
- char dummy_char;
- char buf[CMSG_SPACE(sizeof(int))];
- struct msghdr msg = {0};
- struct iovec dummy_iov;
- struct cmsghdr *cmsg;
-
- if (!PyArg_ParseTuple(args, "i", &conn))
- return NULL;
-
- dummy_iov.iov_base = &dummy_char;
- dummy_iov.iov_len = 1;
- msg.msg_control = buf;
- msg.msg_controllen = sizeof(buf);
- msg.msg_iov = &dummy_iov;
- msg.msg_iovlen = 1;
- cmsg = CMSG_FIRSTHDR(&msg);
- cmsg->cmsg_level = SOL_SOCKET;
- cmsg->cmsg_type = SCM_RIGHTS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(int));
- msg.msg_controllen = cmsg->cmsg_len;
-
- Py_BEGIN_ALLOW_THREADS
- res = recvmsg(conn, &msg, 0);
- Py_END_ALLOW_THREADS
-
- if (res < 0)
- return PyErr_SetFromErrno(PyExc_OSError);
-
- fd = *(int*)CMSG_DATA(cmsg);
- return Py_BuildValue("i", fd);
+ int conn, fd, res;
+ char dummy_char;
+ char buf[CMSG_SPACE(sizeof(int))];
+ struct msghdr msg = {0};
+ struct iovec dummy_iov;
+ struct cmsghdr *cmsg;
+
+ if (!PyArg_ParseTuple(args, "i", &conn))
+ return NULL;
+
+ dummy_iov.iov_base = &dummy_char;
+ dummy_iov.iov_len = 1;
+ msg.msg_control = buf;
+ msg.msg_controllen = sizeof(buf);
+ msg.msg_iov = &dummy_iov;
+ msg.msg_iovlen = 1;
+ cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+ msg.msg_controllen = cmsg->cmsg_len;
+
+ Py_BEGIN_ALLOW_THREADS
+ res = recvmsg(conn, &msg, 0);
+ Py_END_ALLOW_THREADS
+
+ if (res < 0)
+ return PyErr_SetFromErrno(PyExc_OSError);
+
+ fd = *(int*)CMSG_DATA(cmsg);
+ return Py_BuildValue("i", fd);
}
#endif /* HAVE_FD_TRANSFER */
@@ -181,14 +181,14 @@ multiprocessing_recvfd(PyObject *self, PyObject *args)
static PyObject*
multiprocessing_address_of_buffer(PyObject *self, PyObject *obj)
{
- void *buffer;
- Py_ssize_t buffer_len;
+ void *buffer;
+ Py_ssize_t buffer_len;
- if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0)
- return NULL;
+ if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0)
+ return NULL;
- return Py_BuildValue("N" F_PY_SSIZE_T,
- PyLong_FromVoidPtr(buffer), buffer_len);
+ return Py_BuildValue("N" F_PY_SSIZE_T,
+ PyLong_FromVoidPtr(buffer), buffer_len);
}
@@ -197,20 +197,20 @@ multiprocessing_address_of_buffer(PyObject *self, PyObject *obj)
*/
static PyMethodDef module_methods[] = {
- {"address_of_buffer", multiprocessing_address_of_buffer, METH_O,
- "address_of_buffer(obj) -> int\n"
- "Return address of obj assuming obj supports buffer inteface"},
+ {"address_of_buffer", multiprocessing_address_of_buffer, METH_O,
+ "address_of_buffer(obj) -> int\n"
+ "Return address of obj assuming obj supports buffer inteface"},
#if HAVE_FD_TRANSFER
- {"sendfd", multiprocessing_sendfd, METH_VARARGS,
- "sendfd(sockfd, fd) -> None\n"
- "Send file descriptor given by fd over the unix domain socket\n"
- "whose file decriptor is sockfd"},
- {"recvfd", multiprocessing_recvfd, METH_VARARGS,
- "recvfd(sockfd) -> fd\n"
- "Receive a file descriptor over a unix domain socket\n"
- "whose file decriptor is sockfd"},
+ {"sendfd", multiprocessing_sendfd, METH_VARARGS,
+ "sendfd(sockfd, fd) -> None\n"
+ "Send file descriptor given by fd over the unix domain socket\n"
+ "whose file decriptor is sockfd"},
+ {"recvfd", multiprocessing_recvfd, METH_VARARGS,
+ "recvfd(sockfd) -> fd\n"
+ "Receive a file descriptor over a unix domain socket\n"
+ "whose file decriptor is sockfd"},
#endif
- {NULL}
+ {NULL}
};
@@ -219,117 +219,117 @@ static PyMethodDef module_methods[] = {
*/
static struct PyModuleDef multiprocessing_module = {
- PyModuleDef_HEAD_INIT,
- "_multiprocessing",
- NULL,
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_multiprocessing",
+ NULL,
+ -1,
+ module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
-PyMODINIT_FUNC
+PyMODINIT_FUNC
PyInit__multiprocessing(void)
{
- PyObject *module, *temp, *value;
-
- /* Initialize module */
- module = PyModule_Create(&multiprocessing_module);
- if (!module)
- return NULL;
-
- /* Get copy of objects from pickle */
- temp = PyImport_ImportModule(PICKLE_MODULE);
- if (!temp)
- return NULL;
- pickle_dumps = PyObject_GetAttrString(temp, "dumps");
- pickle_loads = PyObject_GetAttrString(temp, "loads");
- pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
- Py_XDECREF(temp);
-
- /* Get copy of BufferTooShort */
- temp = PyImport_ImportModule("multiprocessing");
- if (!temp)
- return NULL;
- BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
- Py_XDECREF(temp);
-
- /* Add connection type to module */
- if (PyType_Ready(&ConnectionType) < 0)
- return NULL;
- Py_INCREF(&ConnectionType);
- PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
-
-#if defined(MS_WINDOWS) || \
+ PyObject *module, *temp, *value;
+
+ /* Initialize module */
+ module = PyModule_Create(&multiprocessing_module);
+ if (!module)
+ return NULL;
+
+ /* Get copy of objects from pickle */
+ temp = PyImport_ImportModule(PICKLE_MODULE);
+ if (!temp)
+ return NULL;
+ pickle_dumps = PyObject_GetAttrString(temp, "dumps");
+ pickle_loads = PyObject_GetAttrString(temp, "loads");
+ pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
+ Py_XDECREF(temp);
+
+ /* Get copy of BufferTooShort */
+ temp = PyImport_ImportModule("multiprocessing");
+ if (!temp)
+ return NULL;
+ BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
+ Py_XDECREF(temp);
+
+ /* Add connection type to module */
+ if (PyType_Ready(&ConnectionType) < 0)
+ return NULL;
+ Py_INCREF(&ConnectionType);
+ PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
+
+#if defined(MS_WINDOWS) || \
(defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
- /* Add SemLock type to module */
- if (PyType_Ready(&SemLockType) < 0)
- return NULL;
- Py_INCREF(&SemLockType);
- PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
- Py_BuildValue("i", SEM_VALUE_MAX));
- PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
+ /* Add SemLock type to module */
+ if (PyType_Ready(&SemLockType) < 0)
+ return NULL;
+ Py_INCREF(&SemLockType);
+ PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
+ Py_BuildValue("i", SEM_VALUE_MAX));
+ PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
#endif
#ifdef MS_WINDOWS
- /* Add PipeConnection to module */
- if (PyType_Ready(&PipeConnectionType) < 0)
- return NULL;
- Py_INCREF(&PipeConnectionType);
- PyModule_AddObject(module, "PipeConnection",
- (PyObject*)&PipeConnectionType);
-
- /* Initialize win32 class and add to multiprocessing */
- temp = create_win32_namespace();
- if (!temp)
- return NULL;
- PyModule_AddObject(module, "win32", temp);
-
- /* Initialize the event handle used to signal Ctrl-C */
- sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
- if (!sigint_event) {
- PyErr_SetFromWindowsErr(0);
- return NULL;
- }
- if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
- PyErr_SetFromWindowsErr(0);
- return NULL;
- }
+ /* Add PipeConnection to module */
+ if (PyType_Ready(&PipeConnectionType) < 0)
+ return NULL;
+ Py_INCREF(&PipeConnectionType);
+ PyModule_AddObject(module, "PipeConnection",
+ (PyObject*)&PipeConnectionType);
+
+ /* Initialize win32 class and add to multiprocessing */
+ temp = create_win32_namespace();
+ if (!temp)
+ return NULL;
+ PyModule_AddObject(module, "win32", temp);
+
+ /* Initialize the event handle used to signal Ctrl-C */
+ sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
+ if (!sigint_event) {
+ PyErr_SetFromWindowsErr(0);
+ return NULL;
+ }
+ if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
+ PyErr_SetFromWindowsErr(0);
+ return NULL;
+ }
#endif
- /* Add configuration macros */
- temp = PyDict_New();
- if (!temp)
- return NULL;
-
-#define ADD_FLAG(name) \
- value = Py_BuildValue("i", name); \
- if (value == NULL) { Py_DECREF(temp); return NULL; } \
- if (PyDict_SetItemString(temp, #name, value) < 0) { \
- Py_DECREF(temp); Py_DECREF(value); return NULL; } \
- Py_DECREF(value)
-
+ /* Add configuration macros */
+ temp = PyDict_New();
+ if (!temp)
+ return NULL;
+
+#define ADD_FLAG(name) \
+ value = Py_BuildValue("i", name); \
+ if (value == NULL) { Py_DECREF(temp); return NULL; } \
+ if (PyDict_SetItemString(temp, #name, value) < 0) { \
+ Py_DECREF(temp); Py_DECREF(value); return NULL; } \
+ Py_DECREF(value)
+
#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
- ADD_FLAG(HAVE_SEM_OPEN);
+ ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
- ADD_FLAG(HAVE_SEM_TIMEDWAIT);
+ ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
- ADD_FLAG(HAVE_FD_TRANSFER);
+ ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
- ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
+ ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
- ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
+ ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif
- if (PyModule_AddObject(module, "flags", temp) < 0)
- return NULL;
+ if (PyModule_AddObject(module, "flags", temp) < 0)
+ return NULL;
- return module;
+ return module;
}
diff --git a/Modules/_multiprocessing/multiprocessing.h b/Modules/_multiprocessing/multiprocessing.h
index 3dd0199..c149634 100644
--- a/Modules/_multiprocessing/multiprocessing.h
+++ b/Modules/_multiprocessing/multiprocessing.h
@@ -15,7 +15,7 @@
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <winsock2.h>
-# include <process.h> /* getpid() */
+# include <process.h> /* getpid() */
# ifdef Py_DEBUG
# include <crtdbg.h>
# endif
@@ -45,15 +45,15 @@
* Issue 3110 - Solaris does not define SEM_VALUE_MAX
*/
#ifndef SEM_VALUE_MAX
- #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX)
- # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX)
- #elif defined(_SEM_VALUE_MAX)
- # define SEM_VALUE_MAX _SEM_VALUE_MAX
- #elif defined(_POSIX_SEM_VALUE_MAX)
- # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX
- #else
- # define SEM_VALUE_MAX INT_MAX
- #endif
+ #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX)
+ # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX)
+ #elif defined(_SEM_VALUE_MAX)
+ # define SEM_VALUE_MAX _SEM_VALUE_MAX
+ #elif defined(_POSIX_SEM_VALUE_MAX)
+ # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX
+ #else
+ # define SEM_VALUE_MAX INT_MAX
+ #endif
#endif
@@ -162,11 +162,11 @@ extern HANDLE sigint_event;
#define CONNECTION_BUFFER_SIZE 1024
typedef struct {
- PyObject_HEAD
- HANDLE handle;
- int flags;
- PyObject *weakreflist;
- char buffer[CONNECTION_BUFFER_SIZE];
+ PyObject_HEAD
+ HANDLE handle;
+ int flags;
+ PyObject *weakreflist;
+ char buffer[CONNECTION_BUFFER_SIZE];
} ConnectionObject;
/*
diff --git a/Modules/_multiprocessing/pipe_connection.c b/Modules/_multiprocessing/pipe_connection.c
index 66947c8..05dde0c 100644
--- a/Modules/_multiprocessing/pipe_connection.c
+++ b/Modules/_multiprocessing/pipe_connection.c
@@ -17,19 +17,19 @@
static Py_ssize_t
conn_send_string(ConnectionObject *conn, char *string, size_t length)
{
- DWORD amount_written;
- BOOL ret;
+ DWORD amount_written;
+ BOOL ret;
- Py_BEGIN_ALLOW_THREADS
- ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
+ Py_END_ALLOW_THREADS
- if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) {
- PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length);
- return MP_STANDARD_ERROR;
- }
+ if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) {
+ PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length);
+ return MP_STANDARD_ERROR;
+ }
- return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
+ return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
}
/*
@@ -39,50 +39,50 @@ conn_send_string(ConnectionObject *conn, char *string, size_t length)
*/
static Py_ssize_t
-conn_recv_string(ConnectionObject *conn, char *buffer,
- size_t buflength, char **newbuffer, size_t maxlength)
+conn_recv_string(ConnectionObject *conn, char *buffer,
+ size_t buflength, char **newbuffer, size_t maxlength)
{
- DWORD left, length, full_length, err;
- BOOL ret;
- *newbuffer = NULL;
-
- Py_BEGIN_ALLOW_THREADS
- ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength),
- &length, NULL);
- Py_END_ALLOW_THREADS
- if (ret)
- return length;
-
- err = GetLastError();
- if (err != ERROR_MORE_DATA) {
- if (err == ERROR_BROKEN_PIPE)
- return MP_END_OF_FILE;
- return MP_STANDARD_ERROR;
- }
-
- if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left))
- return MP_STANDARD_ERROR;
-
- full_length = length + left;
- if (full_length > maxlength)
- return MP_BAD_MESSAGE_LENGTH;
-
- *newbuffer = PyMem_Malloc(full_length);
- if (*newbuffer == NULL)
- return MP_MEMORY_ERROR;
-
- memcpy(*newbuffer, buffer, length);
-
- Py_BEGIN_ALLOW_THREADS
- ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL);
- Py_END_ALLOW_THREADS
- if (ret) {
- assert(length == left);
- return full_length;
- } else {
- PyMem_Free(*newbuffer);
- return MP_STANDARD_ERROR;
- }
+ DWORD left, length, full_length, err;
+ BOOL ret;
+ *newbuffer = NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength),
+ &length, NULL);
+ Py_END_ALLOW_THREADS
+ if (ret)
+ return length;
+
+ err = GetLastError();
+ if (err != ERROR_MORE_DATA) {
+ if (err == ERROR_BROKEN_PIPE)
+ return MP_END_OF_FILE;
+ return MP_STANDARD_ERROR;
+ }
+
+ if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left))
+ return MP_STANDARD_ERROR;
+
+ full_length = length + left;
+ if (full_length > maxlength)
+ return MP_BAD_MESSAGE_LENGTH;
+
+ *newbuffer = PyMem_Malloc(full_length);
+ if (*newbuffer == NULL)
+ return MP_MEMORY_ERROR;
+
+ memcpy(*newbuffer, buffer, length);
+
+ Py_BEGIN_ALLOW_THREADS
+ ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL);
+ Py_END_ALLOW_THREADS
+ if (ret) {
+ assert(length == left);
+ return full_length;
+ } else {
+ PyMem_Free(*newbuffer);
+ return MP_STANDARD_ERROR;
+ }
}
/*
@@ -92,51 +92,51 @@ conn_recv_string(ConnectionObject *conn, char *buffer,
static int
conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save)
{
- DWORD bytes, deadline, delay;
- int difference, res;
- BOOL block = FALSE;
-
- if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
- return MP_STANDARD_ERROR;
-
- if (timeout == 0.0)
- return bytes > 0;
-
- if (timeout < 0.0)
- block = TRUE;
- else
- /* XXX does not check for overflow */
- deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5);
-
- Sleep(0);
-
- for (delay = 1 ; ; delay += 1) {
- if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
- return MP_STANDARD_ERROR;
- else if (bytes > 0)
- return TRUE;
-
- if (!block) {
- difference = deadline - GetTickCount();
- if (difference < 0)
- return FALSE;
- if ((int)delay > difference)
- delay = difference;
- }
-
- if (delay > 20)
- delay = 20;
-
- Sleep(delay);
-
- /* check for signals */
- Py_BLOCK_THREADS
- res = PyErr_CheckSignals();
- Py_UNBLOCK_THREADS
-
- if (res)
- return MP_EXCEPTION_HAS_BEEN_SET;
- }
+ DWORD bytes, deadline, delay;
+ int difference, res;
+ BOOL block = FALSE;
+
+ if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
+ return MP_STANDARD_ERROR;
+
+ if (timeout == 0.0)
+ return bytes > 0;
+
+ if (timeout < 0.0)
+ block = TRUE;
+ else
+ /* XXX does not check for overflow */
+ deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5);
+
+ Sleep(0);
+
+ for (delay = 1 ; ; delay += 1) {
+ if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
+ return MP_STANDARD_ERROR;
+ else if (bytes > 0)
+ return TRUE;
+
+ if (!block) {
+ difference = deadline - GetTickCount();
+ if (difference < 0)
+ return FALSE;
+ if ((int)delay > difference)
+ delay = difference;
+ }
+
+ if (delay > 20)
+ delay = 20;
+
+ Sleep(delay);
+
+ /* check for signals */
+ Py_BLOCK_THREADS
+ res = PyErr_CheckSignals();
+ Py_UNBLOCK_THREADS
+
+ if (res)
+ return MP_EXCEPTION_HAS_BEEN_SET;
+ }
}
/*
diff --git a/Modules/_multiprocessing/semaphore.c b/Modules/_multiprocessing/semaphore.c
index c0944c9..3ab0314 100644
--- a/Modules/_multiprocessing/semaphore.c
+++ b/Modules/_multiprocessing/semaphore.c
@@ -11,12 +11,12 @@
enum { RECURSIVE_MUTEX, SEMAPHORE };
typedef struct {
- PyObject_HEAD
- SEM_HANDLE handle;
- long last_tid;
- int count;
- int maxvalue;
- int kind;
+ PyObject_HEAD
+ SEM_HANDLE handle;
+ long last_tid;
+ int count;
+ int maxvalue;
+ int kind;
} SemLockObject;
#define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid)
@@ -40,148 +40,148 @@ typedef struct {
static int
_GetSemaphoreValue(HANDLE handle, long *value)
{
- long previous;
-
- switch (WaitForSingleObject(handle, 0)) {
- case WAIT_OBJECT_0:
- if (!ReleaseSemaphore(handle, 1, &previous))
- return MP_STANDARD_ERROR;
- *value = previous + 1;
- return 0;
- case WAIT_TIMEOUT:
- *value = 0;
- return 0;
- default:
- return MP_STANDARD_ERROR;
- }
+ long previous;
+
+ switch (WaitForSingleObject(handle, 0)) {
+ case WAIT_OBJECT_0:
+ if (!ReleaseSemaphore(handle, 1, &previous))
+ return MP_STANDARD_ERROR;
+ *value = previous + 1;
+ return 0;
+ case WAIT_TIMEOUT:
+ *value = 0;
+ return 0;
+ default:
+ return MP_STANDARD_ERROR;
+ }
}
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
- int blocking = 1;
- double timeout;
- PyObject *timeout_obj = Py_None;
- DWORD res, full_msecs, msecs, start, ticks;
-
- static char *kwlist[] = {"block", "timeout", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
- &blocking, &timeout_obj))
- return NULL;
-
- /* calculate timeout */
- if (!blocking) {
- full_msecs = 0;
- } else if (timeout_obj == Py_None) {
- full_msecs = INFINITE;
- } else {
- timeout = PyFloat_AsDouble(timeout_obj);
- if (PyErr_Occurred())
- return NULL;
- timeout *= 1000.0; /* convert to millisecs */
- if (timeout < 0.0) {
- timeout = 0.0;
- } else if (timeout >= 0.5 * INFINITE) { /* 25 days */
- PyErr_SetString(PyExc_OverflowError,
- "timeout is too large");
- return NULL;
- }
- full_msecs = (DWORD)(timeout + 0.5);
- }
-
- /* check whether we already own the lock */
- if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
- ++self->count;
- Py_RETURN_TRUE;
- }
-
- /* check whether we can acquire without blocking */
- if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
- self->last_tid = GetCurrentThreadId();
- ++self->count;
- Py_RETURN_TRUE;
- }
-
- msecs = full_msecs;
- start = GetTickCount();
-
- for ( ; ; ) {
- HANDLE handles[2] = {self->handle, sigint_event};
-
- /* do the wait */
- Py_BEGIN_ALLOW_THREADS
- ResetEvent(sigint_event);
- res = WaitForMultipleObjects(2, handles, FALSE, msecs);
- Py_END_ALLOW_THREADS
-
- /* handle result */
- if (res != WAIT_OBJECT_0 + 1)
- break;
-
- /* got SIGINT so give signal handler a chance to run */
- Sleep(1);
-
- /* if this is main thread let KeyboardInterrupt be raised */
- if (PyErr_CheckSignals())
- return NULL;
-
- /* recalculate timeout */
- if (msecs != INFINITE) {
- ticks = GetTickCount();
- if ((DWORD)(ticks - start) >= full_msecs)
- Py_RETURN_FALSE;
- msecs = full_msecs - (ticks - start);
- }
- }
-
- /* handle result */
- switch (res) {
- case WAIT_TIMEOUT:
- Py_RETURN_FALSE;
- case WAIT_OBJECT_0:
- self->last_tid = GetCurrentThreadId();
- ++self->count;
- Py_RETURN_TRUE;
- case WAIT_FAILED:
- return PyErr_SetFromWindowsErr(0);
- default:
- PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
- "WaitForMultipleObjects() gave unrecognized "
- "value %d", res);
- return NULL;
- }
+ int blocking = 1;
+ double timeout;
+ PyObject *timeout_obj = Py_None;
+ DWORD res, full_msecs, msecs, start, ticks;
+
+ static char *kwlist[] = {"block", "timeout", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
+ &blocking, &timeout_obj))
+ return NULL;
+
+ /* calculate timeout */
+ if (!blocking) {
+ full_msecs = 0;
+ } else if (timeout_obj == Py_None) {
+ full_msecs = INFINITE;
+ } else {
+ timeout = PyFloat_AsDouble(timeout_obj);
+ if (PyErr_Occurred())
+ return NULL;
+ timeout *= 1000.0; /* convert to millisecs */
+ if (timeout < 0.0) {
+ timeout = 0.0;
+ } else if (timeout >= 0.5 * INFINITE) { /* 25 days */
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout is too large");
+ return NULL;
+ }
+ full_msecs = (DWORD)(timeout + 0.5);
+ }
+
+ /* check whether we already own the lock */
+ if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
+ ++self->count;
+ Py_RETURN_TRUE;
+ }
+
+ /* check whether we can acquire without blocking */
+ if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
+ self->last_tid = GetCurrentThreadId();
+ ++self->count;
+ Py_RETURN_TRUE;
+ }
+
+ msecs = full_msecs;
+ start = GetTickCount();
+
+ for ( ; ; ) {
+ HANDLE handles[2] = {self->handle, sigint_event};
+
+ /* do the wait */
+ Py_BEGIN_ALLOW_THREADS
+ ResetEvent(sigint_event);
+ res = WaitForMultipleObjects(2, handles, FALSE, msecs);
+ Py_END_ALLOW_THREADS
+
+ /* handle result */
+ if (res != WAIT_OBJECT_0 + 1)
+ break;
+
+ /* got SIGINT so give signal handler a chance to run */
+ Sleep(1);
+
+ /* if this is main thread let KeyboardInterrupt be raised */
+ if (PyErr_CheckSignals())
+ return NULL;
+
+ /* recalculate timeout */
+ if (msecs != INFINITE) {
+ ticks = GetTickCount();
+ if ((DWORD)(ticks - start) >= full_msecs)
+ Py_RETURN_FALSE;
+ msecs = full_msecs - (ticks - start);
+ }
+ }
+
+ /* handle result */
+ switch (res) {
+ case WAIT_TIMEOUT:
+ Py_RETURN_FALSE;
+ case WAIT_OBJECT_0:
+ self->last_tid = GetCurrentThreadId();
+ ++self->count;
+ Py_RETURN_TRUE;
+ case WAIT_FAILED:
+ return PyErr_SetFromWindowsErr(0);
+ default:
+ PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
+ "WaitForMultipleObjects() gave unrecognized "
+ "value %d", res);
+ return NULL;
+ }
}
static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
- if (self->kind == RECURSIVE_MUTEX) {
- if (!ISMINE(self)) {
- PyErr_SetString(PyExc_AssertionError, "attempt to "
- "release recursive lock not owned "
- "by thread");
- return NULL;
- }
- if (self->count > 1) {
- --self->count;
- Py_RETURN_NONE;
- }
- assert(self->count == 1);
- }
-
- if (!ReleaseSemaphore(self->handle, 1, NULL)) {
- if (GetLastError() == ERROR_TOO_MANY_POSTS) {
- PyErr_SetString(PyExc_ValueError, "semaphore or lock "
- "released too many times");
- return NULL;
- } else {
- return PyErr_SetFromWindowsErr(0);
- }
- }
-
- --self->count;
- Py_RETURN_NONE;
+ if (self->kind == RECURSIVE_MUTEX) {
+ if (!ISMINE(self)) {
+ PyErr_SetString(PyExc_AssertionError, "attempt to "
+ "release recursive lock not owned "
+ "by thread");
+ return NULL;
+ }
+ if (self->count > 1) {
+ --self->count;
+ Py_RETURN_NONE;
+ }
+ assert(self->count == 1);
+ }
+
+ if (!ReleaseSemaphore(self->handle, 1, NULL)) {
+ if (GetLastError() == ERROR_TOO_MANY_POSTS) {
+ PyErr_SetString(PyExc_ValueError, "semaphore or lock "
+ "released too many times");
+ return NULL;
+ } else {
+ return PyErr_SetFromWindowsErr(0);
+ }
+ }
+
+ --self->count;
+ Py_RETURN_NONE;
}
#else /* !MS_WINDOWS */
@@ -207,59 +207,59 @@ semlock_release(SemLockObject *self, PyObject *args)
int
sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
{
- int res;
- unsigned long delay, difference;
- struct timeval now, tvdeadline, tvdelay;
-
- errno = 0;
- tvdeadline.tv_sec = deadline->tv_sec;
- tvdeadline.tv_usec = deadline->tv_nsec / 1000;
-
- for (delay = 0 ; ; delay += 1000) {
- /* poll */
- if (sem_trywait(sem) == 0)
- return 0;
- else if (errno != EAGAIN)
- return MP_STANDARD_ERROR;
-
- /* get current time */
- if (gettimeofday(&now, NULL) < 0)
- return MP_STANDARD_ERROR;
-
- /* check for timeout */
- if (tvdeadline.tv_sec < now.tv_sec ||
- (tvdeadline.tv_sec == now.tv_sec &&
- tvdeadline.tv_usec <= now.tv_usec)) {
- errno = ETIMEDOUT;
- return MP_STANDARD_ERROR;
- }
-
- /* calculate how much time is left */
- difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
- (tvdeadline.tv_usec - now.tv_usec);
-
- /* check delay not too long -- maximum is 20 msecs */
- if (delay > 20000)
- delay = 20000;
- if (delay > difference)
- delay = difference;
-
- /* sleep */
- tvdelay.tv_sec = delay / 1000000;
- tvdelay.tv_usec = delay % 1000000;
- if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
- return MP_STANDARD_ERROR;
-
- /* check for signals */
- Py_BLOCK_THREADS
- res = PyErr_CheckSignals();
- Py_UNBLOCK_THREADS
-
- if (res) {
- errno = EINTR;
- return MP_EXCEPTION_HAS_BEEN_SET;
- }
- }
+ int res;
+ unsigned long delay, difference;
+ struct timeval now, tvdeadline, tvdelay;
+
+ errno = 0;
+ tvdeadline.tv_sec = deadline->tv_sec;
+ tvdeadline.tv_usec = deadline->tv_nsec / 1000;
+
+ for (delay = 0 ; ; delay += 1000) {
+ /* poll */
+ if (sem_trywait(sem) == 0)
+ return 0;
+ else if (errno != EAGAIN)
+ return MP_STANDARD_ERROR;
+
+ /* get current time */
+ if (gettimeofday(&now, NULL) < 0)
+ return MP_STANDARD_ERROR;
+
+ /* check for timeout */
+ if (tvdeadline.tv_sec < now.tv_sec ||
+ (tvdeadline.tv_sec == now.tv_sec &&
+ tvdeadline.tv_usec <= now.tv_usec)) {
+ errno = ETIMEDOUT;
+ return MP_STANDARD_ERROR;
+ }
+
+ /* calculate how much time is left */
+ difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
+ (tvdeadline.tv_usec - now.tv_usec);
+
+ /* check delay not too long -- maximum is 20 msecs */
+ if (delay > 20000)
+ delay = 20000;
+ if (delay > difference)
+ delay = difference;
+
+ /* sleep */
+ tvdelay.tv_sec = delay / 1000000;
+ tvdelay.tv_usec = delay % 1000000;
+ if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
+ return MP_STANDARD_ERROR;
+
+ /* check for signals */
+ Py_BLOCK_THREADS
+ res = PyErr_CheckSignals();
+ Py_UNBLOCK_THREADS
+
+ if (res) {
+ errno = EINTR;
+ return MP_EXCEPTION_HAS_BEEN_SET;
+ }
+ }
}
#endif /* !HAVE_SEM_TIMEDWAIT */
@@ -267,129 +267,129 @@ sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
- int blocking = 1, res;
- double timeout;
- PyObject *timeout_obj = Py_None;
- struct timespec deadline = {0};
- struct timeval now;
- long sec, nsec;
-
- static char *kwlist[] = {"block", "timeout", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
- &blocking, &timeout_obj))
- return NULL;
-
- if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
- ++self->count;
- Py_RETURN_TRUE;
- }
-
- if (timeout_obj != Py_None) {
- timeout = PyFloat_AsDouble(timeout_obj);
- if (PyErr_Occurred())
- return NULL;
- if (timeout < 0.0)
- timeout = 0.0;
-
- if (gettimeofday(&now, NULL) < 0) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- sec = (long) timeout;
- nsec = (long) (1e9 * (timeout - sec) + 0.5);
- deadline.tv_sec = now.tv_sec + sec;
- deadline.tv_nsec = now.tv_usec * 1000 + nsec;
- deadline.tv_sec += (deadline.tv_nsec / 1000000000);
- deadline.tv_nsec %= 1000000000;
- }
-
- do {
- Py_BEGIN_ALLOW_THREADS
- if (blocking && timeout_obj == Py_None)
- res = sem_wait(self->handle);
- else if (!blocking)
- res = sem_trywait(self->handle);
- else
- res = sem_timedwait(self->handle, &deadline);
- Py_END_ALLOW_THREADS
- if (res == MP_EXCEPTION_HAS_BEEN_SET)
- break;
- } while (res < 0 && errno == EINTR && !PyErr_CheckSignals());
-
- if (res < 0) {
- if (errno == EAGAIN || errno == ETIMEDOUT)
- Py_RETURN_FALSE;
- else if (errno == EINTR)
- return NULL;
- else
- return PyErr_SetFromErrno(PyExc_OSError);
- }
-
- ++self->count;
- self->last_tid = PyThread_get_thread_ident();
-
- Py_RETURN_TRUE;
+ int blocking = 1, res;
+ double timeout;
+ PyObject *timeout_obj = Py_None;
+ struct timespec deadline = {0};
+ struct timeval now;
+ long sec, nsec;
+
+ static char *kwlist[] = {"block", "timeout", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
+ &blocking, &timeout_obj))
+ return NULL;
+
+ if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
+ ++self->count;
+ Py_RETURN_TRUE;
+ }
+
+ if (timeout_obj != Py_None) {
+ timeout = PyFloat_AsDouble(timeout_obj);
+ if (PyErr_Occurred())
+ return NULL;
+ if (timeout < 0.0)
+ timeout = 0.0;
+
+ if (gettimeofday(&now, NULL) < 0) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ sec = (long) timeout;
+ nsec = (long) (1e9 * (timeout - sec) + 0.5);
+ deadline.tv_sec = now.tv_sec + sec;
+ deadline.tv_nsec = now.tv_usec * 1000 + nsec;
+ deadline.tv_sec += (deadline.tv_nsec / 1000000000);
+ deadline.tv_nsec %= 1000000000;
+ }
+
+ do {
+ Py_BEGIN_ALLOW_THREADS
+ if (blocking && timeout_obj == Py_None)
+ res = sem_wait(self->handle);
+ else if (!blocking)
+ res = sem_trywait(self->handle);
+ else
+ res = sem_timedwait(self->handle, &deadline);
+ Py_END_ALLOW_THREADS
+ if (res == MP_EXCEPTION_HAS_BEEN_SET)
+ break;
+ } while (res < 0 && errno == EINTR && !PyErr_CheckSignals());
+
+ if (res < 0) {
+ if (errno == EAGAIN || errno == ETIMEDOUT)
+ Py_RETURN_FALSE;
+ else if (errno == EINTR)
+ return NULL;
+ else
+ return PyErr_SetFromErrno(PyExc_OSError);
+ }
+
+ ++self->count;
+ self->last_tid = PyThread_get_thread_ident();
+
+ Py_RETURN_TRUE;
}
static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
- if (self->kind == RECURSIVE_MUTEX) {
- if (!ISMINE(self)) {
- PyErr_SetString(PyExc_AssertionError, "attempt to "
- "release recursive lock not owned "
- "by thread");
- return NULL;
- }
- if (self->count > 1) {
- --self->count;
- Py_RETURN_NONE;
- }
- assert(self->count == 1);
- } else {
+ if (self->kind == RECURSIVE_MUTEX) {
+ if (!ISMINE(self)) {
+ PyErr_SetString(PyExc_AssertionError, "attempt to "
+ "release recursive lock not owned "
+ "by thread");
+ return NULL;
+ }
+ if (self->count > 1) {
+ --self->count;
+ Py_RETURN_NONE;
+ }
+ assert(self->count == 1);
+ } else {
#ifdef HAVE_BROKEN_SEM_GETVALUE
- /* We will only check properly the maxvalue == 1 case */
- if (self->maxvalue == 1) {
- /* make sure that already locked */
- if (sem_trywait(self->handle) < 0) {
- if (errno != EAGAIN) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- /* it is already locked as expected */
- } else {
- /* it was not locked so undo wait and raise */
- if (sem_post(self->handle) < 0) {
- PyErr_SetFromErrno(PyExc_OSError);
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "semaphore "
- "or lock released too many "
- "times");
- return NULL;
- }
- }
+ /* We will only check properly the maxvalue == 1 case */
+ if (self->maxvalue == 1) {
+ /* make sure that already locked */
+ if (sem_trywait(self->handle) < 0) {
+ if (errno != EAGAIN) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ /* it is already locked as expected */
+ } else {
+ /* it was not locked so undo wait and raise */
+ if (sem_post(self->handle) < 0) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "semaphore "
+ "or lock released too many "
+ "times");
+ return NULL;
+ }
+ }
#else
- int sval;
-
- /* This check is not an absolute guarantee that the semaphore
- does not rise above maxvalue. */
- if (sem_getvalue(self->handle, &sval) < 0) {
- return PyErr_SetFromErrno(PyExc_OSError);
- } else if (sval >= self->maxvalue) {
- PyErr_SetString(PyExc_ValueError, "semaphore or lock "
- "released too many times");
- return NULL;
- }
+ int sval;
+
+ /* This check is not an absolute guarantee that the semaphore
+ does not rise above maxvalue. */
+ if (sem_getvalue(self->handle, &sval) < 0) {
+ return PyErr_SetFromErrno(PyExc_OSError);
+ } else if (sval >= self->maxvalue) {
+ PyErr_SetString(PyExc_ValueError, "semaphore or lock "
+ "released too many times");
+ return NULL;
+ }
#endif
- }
+ }
- if (sem_post(self->handle) < 0)
- return PyErr_SetFromErrno(PyExc_OSError);
+ if (sem_post(self->handle) < 0)
+ return PyErr_SetFromErrno(PyExc_OSError);
- --self->count;
- Py_RETURN_NONE;
+ --self->count;
+ Py_RETURN_NONE;
}
#endif /* !MS_WINDOWS */
@@ -401,111 +401,111 @@ semlock_release(SemLockObject *self, PyObject *args)
static PyObject *
newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue)
{
- SemLockObject *self;
-
- self = PyObject_New(SemLockObject, type);
- if (!self)
- return NULL;
- self->handle = handle;
- self->kind = kind;
- self->count = 0;
- self->last_tid = 0;
- self->maxvalue = maxvalue;
- return (PyObject*)self;
+ SemLockObject *self;
+
+ self = PyObject_New(SemLockObject, type);
+ if (!self)
+ return NULL;
+ self->handle = handle;
+ self->kind = kind;
+ self->count = 0;
+ self->last_tid = 0;
+ self->maxvalue = maxvalue;
+ return (PyObject*)self;
}
static PyObject *
semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char buffer[256];
- SEM_HANDLE handle = SEM_FAILED;
- int kind, maxvalue, value;
- PyObject *result;
- static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
- static int counter = 0;
+ char buffer[256];
+ SEM_HANDLE handle = SEM_FAILED;
+ int kind, maxvalue, value;
+ PyObject *result;
+ static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
+ static int counter = 0;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
- &kind, &value, &maxvalue))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
+ &kind, &value, &maxvalue))
+ return NULL;
- if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
- PyErr_SetString(PyExc_ValueError, "unrecognized kind");
- return NULL;
- }
+ if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
+ PyErr_SetString(PyExc_ValueError, "unrecognized kind");
+ return NULL;
+ }
- PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++);
+ PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++);
- SEM_CLEAR_ERROR();
- handle = SEM_CREATE(buffer, value, maxvalue);
- /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
- if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
- goto failure;
+ SEM_CLEAR_ERROR();
+ handle = SEM_CREATE(buffer, value, maxvalue);
+ /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
+ if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
+ goto failure;
- if (SEM_UNLINK(buffer) < 0)
- goto failure;
+ if (SEM_UNLINK(buffer) < 0)
+ goto failure;
- result = newsemlockobject(type, handle, kind, maxvalue);
- if (!result)
- goto failure;
+ result = newsemlockobject(type, handle, kind, maxvalue);
+ if (!result)
+ goto failure;
- return result;
+ return result;
failure:
- if (handle != SEM_FAILED)
- SEM_CLOSE(handle);
- mp_SetError(NULL, MP_STANDARD_ERROR);
- return NULL;
+ if (handle != SEM_FAILED)
+ SEM_CLOSE(handle);
+ mp_SetError(NULL, MP_STANDARD_ERROR);
+ return NULL;
}
static PyObject *
semlock_rebuild(PyTypeObject *type, PyObject *args)
{
- SEM_HANDLE handle;
- int kind, maxvalue;
+ SEM_HANDLE handle;
+ int kind, maxvalue;
- if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
- &handle, &kind, &maxvalue))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
+ &handle, &kind, &maxvalue))
+ return NULL;
- return newsemlockobject(type, handle, kind, maxvalue);
+ return newsemlockobject(type, handle, kind, maxvalue);
}
static void
semlock_dealloc(SemLockObject* self)
{
- if (self->handle != SEM_FAILED)
- SEM_CLOSE(self->handle);
- PyObject_Del(self);
+ if (self->handle != SEM_FAILED)
+ SEM_CLOSE(self->handle);
+ PyObject_Del(self);
}
static PyObject *
semlock_count(SemLockObject *self)
{
- return PyInt_FromLong((long)self->count);
+ return PyInt_FromLong((long)self->count);
}
static PyObject *
semlock_ismine(SemLockObject *self)
{
- /* only makes sense for a lock */
- return PyBool_FromLong(ISMINE(self));
+ /* only makes sense for a lock */
+ return PyBool_FromLong(ISMINE(self));
}
static PyObject *
semlock_getvalue(SemLockObject *self)
{
#ifdef HAVE_BROKEN_SEM_GETVALUE
- PyErr_SetNone(PyExc_NotImplementedError);
- return NULL;
+ PyErr_SetNone(PyExc_NotImplementedError);
+ return NULL;
#else
- int sval;
- if (SEM_GETVALUE(self->handle, &sval) < 0)
- return mp_SetError(NULL, MP_STANDARD_ERROR);
- /* some posix implementations use negative numbers to indicate
- the number of waiting threads */
- if (sval < 0)
- sval = 0;
- return PyInt_FromLong((long)sval);
+ int sval;
+ if (SEM_GETVALUE(self->handle, &sval) < 0)
+ return mp_SetError(NULL, MP_STANDARD_ERROR);
+ /* some posix implementations use negative numbers to indicate
+ the number of waiting threads */
+ if (sval < 0)
+ sval = 0;
+ return PyInt_FromLong((long)sval);
#endif
}
@@ -513,28 +513,28 @@ static PyObject *
semlock_iszero(SemLockObject *self)
{
#ifdef HAVE_BROKEN_SEM_GETVALUE
- if (sem_trywait(self->handle) < 0) {
- if (errno == EAGAIN)
- Py_RETURN_TRUE;
- return mp_SetError(NULL, MP_STANDARD_ERROR);
- } else {
- if (sem_post(self->handle) < 0)
- return mp_SetError(NULL, MP_STANDARD_ERROR);
- Py_RETURN_FALSE;
- }
+ if (sem_trywait(self->handle) < 0) {
+ if (errno == EAGAIN)
+ Py_RETURN_TRUE;
+ return mp_SetError(NULL, MP_STANDARD_ERROR);
+ } else {
+ if (sem_post(self->handle) < 0)
+ return mp_SetError(NULL, MP_STANDARD_ERROR);
+ Py_RETURN_FALSE;
+ }
#else
- int sval;
- if (SEM_GETVALUE(self->handle, &sval) < 0)
- return mp_SetError(NULL, MP_STANDARD_ERROR);
- return PyBool_FromLong((long)sval == 0);
+ int sval;
+ if (SEM_GETVALUE(self->handle, &sval) < 0)
+ return mp_SetError(NULL, MP_STANDARD_ERROR);
+ return PyBool_FromLong((long)sval == 0);
#endif
}
static PyObject *
semlock_afterfork(SemLockObject *self)
{
- self->count = 0;
- Py_RETURN_NONE;
+ self->count = 0;
+ Py_RETURN_NONE;
}
/*
@@ -542,27 +542,27 @@ semlock_afterfork(SemLockObject *self)
*/
static PyMethodDef semlock_methods[] = {
- {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
- "acquire the semaphore/lock"},
- {"release", (PyCFunction)semlock_release, METH_NOARGS,
- "release the semaphore/lock"},
+ {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
+ "acquire the semaphore/lock"},
+ {"release", (PyCFunction)semlock_release, METH_NOARGS,
+ "release the semaphore/lock"},
{"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
- "enter the semaphore/lock"},
- {"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
- "exit the semaphore/lock"},
- {"_count", (PyCFunction)semlock_count, METH_NOARGS,
- "num of `acquire()`s minus num of `release()`s for this process"},
- {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
- "whether the lock is owned by this thread"},
- {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
- "get the value of the semaphore"},
- {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
- "returns whether semaphore has value zero"},
- {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
- ""},
- {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
- "rezero the net acquisition count after fork()"},
- {NULL}
+ "enter the semaphore/lock"},
+ {"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
+ "exit the semaphore/lock"},
+ {"_count", (PyCFunction)semlock_count, METH_NOARGS,
+ "num of `acquire()`s minus num of `release()`s for this process"},
+ {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
+ "whether the lock is owned by this thread"},
+ {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
+ "get the value of the semaphore"},
+ {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
+ "returns whether semaphore has value zero"},
+ {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
+ ""},
+ {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
+ "rezero the net acquisition count after fork()"},
+ {NULL}
};
/*
@@ -570,13 +570,13 @@ static PyMethodDef semlock_methods[] = {
*/
static PyMemberDef semlock_members[] = {
- {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
- ""},
- {"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
- ""},
- {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
- ""},
- {NULL}
+ {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
+ ""},
+ {"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
+ ""},
+ {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
+ ""},
+ {NULL}
};
/*
@@ -584,42 +584,42 @@ static PyMemberDef semlock_members[] = {
*/
PyTypeObject SemLockType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* tp_name */ "_multiprocessing.SemLock",
- /* tp_basicsize */ sizeof(SemLockObject),
- /* tp_itemsize */ 0,
- /* tp_dealloc */ (destructor)semlock_dealloc,
- /* tp_print */ 0,
- /* tp_getattr */ 0,
- /* tp_setattr */ 0,
- /* tp_reserved */ 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 */ 0,
- /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- /* tp_doc */ "Semaphore/Mutex type",
- /* tp_traverse */ 0,
- /* tp_clear */ 0,
- /* tp_richcompare */ 0,
- /* tp_weaklistoffset */ 0,
- /* tp_iter */ 0,
- /* tp_iternext */ 0,
- /* tp_methods */ semlock_methods,
- /* tp_members */ semlock_members,
- /* tp_getset */ 0,
- /* tp_base */ 0,
- /* tp_dict */ 0,
- /* tp_descr_get */ 0,
- /* tp_descr_set */ 0,
- /* tp_dictoffset */ 0,
- /* tp_init */ 0,
- /* tp_alloc */ 0,
- /* tp_new */ semlock_new,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* tp_name */ "_multiprocessing.SemLock",
+ /* tp_basicsize */ sizeof(SemLockObject),
+ /* tp_itemsize */ 0,
+ /* tp_dealloc */ (destructor)semlock_dealloc,
+ /* tp_print */ 0,
+ /* tp_getattr */ 0,
+ /* tp_setattr */ 0,
+ /* tp_reserved */ 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 */ 0,
+ /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+ /* tp_doc */ "Semaphore/Mutex type",
+ /* tp_traverse */ 0,
+ /* tp_clear */ 0,
+ /* tp_richcompare */ 0,
+ /* tp_weaklistoffset */ 0,
+ /* tp_iter */ 0,
+ /* tp_iternext */ 0,
+ /* tp_methods */ semlock_methods,
+ /* tp_members */ semlock_members,
+ /* tp_getset */ 0,
+ /* tp_base */ 0,
+ /* tp_dict */ 0,
+ /* tp_descr_get */ 0,
+ /* tp_descr_set */ 0,
+ /* tp_dictoffset */ 0,
+ /* tp_init */ 0,
+ /* tp_alloc */ 0,
+ /* tp_new */ semlock_new,
};
diff --git a/Modules/_multiprocessing/socket_connection.c b/Modules/_multiprocessing/socket_connection.c
index ad4005b..7ebf338 100644
--- a/Modules/_multiprocessing/socket_connection.c
+++ b/Modules/_multiprocessing/socket_connection.c
@@ -25,45 +25,45 @@
static Py_ssize_t
_conn_sendall(HANDLE h, char *string, size_t length)
{
- char *p = string;
- Py_ssize_t res;
-
- while (length > 0) {
- res = WRITE(h, p, length);
- if (res < 0)
- return MP_SOCKET_ERROR;
- length -= res;
- p += res;
- }
-
- return MP_SUCCESS;
+ char *p = string;
+ Py_ssize_t res;
+
+ while (length > 0) {
+ res = WRITE(h, p, length);
+ if (res < 0)
+ return MP_SOCKET_ERROR;
+ length -= res;
+ p += res;
+ }
+
+ return MP_SUCCESS;
}
/*
- * Receive string of exact length from file descriptor
+ * Receive string of exact length from file descriptor
*/
static Py_ssize_t
_conn_recvall(HANDLE h, char *buffer, size_t length)
{
- size_t remaining = length;
- Py_ssize_t temp;
- char *p = buffer;
-
- while (remaining > 0) {
- temp = READ(h, p, remaining);
- if (temp <= 0) {
- if (temp == 0)
- return remaining == length ?
- MP_END_OF_FILE : MP_EARLY_END_OF_FILE;
- else
- return temp;
- }
- remaining -= temp;
- p += temp;
- }
-
- return MP_SUCCESS;
+ size_t remaining = length;
+ Py_ssize_t temp;
+ char *p = buffer;
+
+ while (remaining > 0) {
+ temp = READ(h, p, remaining);
+ if (temp <= 0) {
+ if (temp == 0)
+ return remaining == length ?
+ MP_END_OF_FILE : MP_EARLY_END_OF_FILE;
+ else
+ return temp;
+ }
+ remaining -= temp;
+ p += temp;
+ }
+
+ return MP_SUCCESS;
}
/*
@@ -73,38 +73,38 @@ _conn_recvall(HANDLE h, char *buffer, size_t length)
static Py_ssize_t
conn_send_string(ConnectionObject *conn, char *string, size_t length)
{
- Py_ssize_t res;
- /* The "header" of the message is a 32 bit unsigned number (in
- network order) which specifies the length of the "body". If
- the message is shorter than about 16kb then it is quicker to
- combine the "header" and the "body" of the message and send
- them at once. */
- if (length < (16*1024)) {
- char *message;
-
- message = PyMem_Malloc(length+4);
- if (message == NULL)
- return MP_MEMORY_ERROR;
-
- *(UINT32*)message = htonl((UINT32)length);
- memcpy(message+4, string, length);
- Py_BEGIN_ALLOW_THREADS
- res = _conn_sendall(conn->handle, message, length+4);
- Py_END_ALLOW_THREADS
- PyMem_Free(message);
- } else {
- UINT32 lenbuff;
-
- if (length > MAX_MESSAGE_LENGTH)
- return MP_BAD_MESSAGE_LENGTH;
-
- lenbuff = htonl((UINT32)length);
- Py_BEGIN_ALLOW_THREADS
- res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) ||
- _conn_sendall(conn->handle, string, length);
- Py_END_ALLOW_THREADS
- }
- return res;
+ Py_ssize_t res;
+ /* The "header" of the message is a 32 bit unsigned number (in
+ network order) which specifies the length of the "body". If
+ the message is shorter than about 16kb then it is quicker to
+ combine the "header" and the "body" of the message and send
+ them at once. */
+ if (length < (16*1024)) {
+ char *message;
+
+ message = PyMem_Malloc(length+4);
+ if (message == NULL)
+ return MP_MEMORY_ERROR;
+
+ *(UINT32*)message = htonl((UINT32)length);
+ memcpy(message+4, string, length);
+ Py_BEGIN_ALLOW_THREADS
+ res = _conn_sendall(conn->handle, message, length+4);
+ Py_END_ALLOW_THREADS
+ PyMem_Free(message);
+ } else {
+ UINT32 lenbuff;
+
+ if (length > MAX_MESSAGE_LENGTH)
+ return MP_BAD_MESSAGE_LENGTH;
+
+ lenbuff = htonl((UINT32)length);
+ Py_BEGIN_ALLOW_THREADS
+ res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) ||
+ _conn_sendall(conn->handle, string, length);
+ Py_END_ALLOW_THREADS
+ }
+ return res;
}
/*
@@ -114,38 +114,38 @@ conn_send_string(ConnectionObject *conn, char *string, size_t length)
*/
static Py_ssize_t
-conn_recv_string(ConnectionObject *conn, char *buffer,
- size_t buflength, char **newbuffer, size_t maxlength)
+conn_recv_string(ConnectionObject *conn, char *buffer,
+ size_t buflength, char **newbuffer, size_t maxlength)
{
- int res;
- UINT32 ulength;
-
- *newbuffer = NULL;
-
- Py_BEGIN_ALLOW_THREADS
- res = _conn_recvall(conn->handle, (char*)&ulength, 4);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return res;
-
- ulength = ntohl(ulength);
- if (ulength > maxlength)
- return MP_BAD_MESSAGE_LENGTH;
-
- if (ulength <= buflength) {
- Py_BEGIN_ALLOW_THREADS
- res = _conn_recvall(conn->handle, buffer, (size_t)ulength);
- Py_END_ALLOW_THREADS
- return res < 0 ? res : ulength;
- } else {
- *newbuffer = PyMem_Malloc((size_t)ulength);
- if (*newbuffer == NULL)
- return MP_MEMORY_ERROR;
- Py_BEGIN_ALLOW_THREADS
- res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength);
- Py_END_ALLOW_THREADS
- return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength;
- }
+ int res;
+ UINT32 ulength;
+
+ *newbuffer = NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ res = _conn_recvall(conn->handle, (char*)&ulength, 4);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return res;
+
+ ulength = ntohl(ulength);
+ if (ulength > maxlength)
+ return MP_BAD_MESSAGE_LENGTH;
+
+ if (ulength <= buflength) {
+ Py_BEGIN_ALLOW_THREADS
+ res = _conn_recvall(conn->handle, buffer, (size_t)ulength);
+ Py_END_ALLOW_THREADS
+ return res < 0 ? res : ulength;
+ } else {
+ *newbuffer = PyMem_Malloc((size_t)ulength);
+ if (*newbuffer == NULL)
+ return MP_MEMORY_ERROR;
+ Py_BEGIN_ALLOW_THREADS
+ res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength);
+ Py_END_ALLOW_THREADS
+ return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength;
+ }
}
/*
@@ -155,41 +155,41 @@ conn_recv_string(ConnectionObject *conn, char *buffer,
static int
conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save)
{
- int res;
- fd_set rfds;
-
- /*
- * Verify the handle, issue 3321. Not required for windows.
- */
- #ifndef MS_WINDOWS
- if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) {
- Py_BLOCK_THREADS
- PyErr_SetString(PyExc_IOError, "handle out of range in select()");
- Py_UNBLOCK_THREADS
- return MP_EXCEPTION_HAS_BEEN_SET;
- }
- #endif
-
- FD_ZERO(&rfds);
- FD_SET((SOCKET)conn->handle, &rfds);
-
- if (timeout < 0.0) {
- res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL);
- } else {
- struct timeval tv;
- tv.tv_sec = (long)timeout;
- tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5);
- res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv);
- }
-
- if (res < 0) {
- return MP_SOCKET_ERROR;
- } else if (FD_ISSET(conn->handle, &rfds)) {
- return TRUE;
- } else {
- assert(res == 0);
- return FALSE;
- }
+ int res;
+ fd_set rfds;
+
+ /*
+ * Verify the handle, issue 3321. Not required for windows.
+ */
+ #ifndef MS_WINDOWS
+ if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) {
+ Py_BLOCK_THREADS
+ PyErr_SetString(PyExc_IOError, "handle out of range in select()");
+ Py_UNBLOCK_THREADS
+ return MP_EXCEPTION_HAS_BEEN_SET;
+ }
+ #endif
+
+ FD_ZERO(&rfds);
+ FD_SET((SOCKET)conn->handle, &rfds);
+
+ if (timeout < 0.0) {
+ res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL);
+ } else {
+ struct timeval tv;
+ tv.tv_sec = (long)timeout;
+ tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5);
+ res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv);
+ }
+
+ if (res < 0) {
+ return MP_SOCKET_ERROR;
+ } else if (FD_ISSET(conn->handle, &rfds)) {
+ return TRUE;
+ } else {
+ assert(res == 0);
+ return FALSE;
+ }
}
/*
diff --git a/Modules/_multiprocessing/win32_functions.c b/Modules/_multiprocessing/win32_functions.c
index ba82c23..452d608 100644
--- a/Modules/_multiprocessing/win32_functions.c
+++ b/Modules/_multiprocessing/win32_functions.c
@@ -19,248 +19,248 @@
static PyObject *
win32_CloseHandle(PyObject *self, PyObject *args)
{
- HANDLE hObject;
- BOOL success;
+ HANDLE hObject;
+ BOOL success;
- if (!PyArg_ParseTuple(args, F_HANDLE, &hObject))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_HANDLE, &hObject))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- success = CloseHandle(hObject);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ success = CloseHandle(hObject);
+ Py_END_ALLOW_THREADS
- if (!success)
- return PyErr_SetFromWindowsErr(0);
+ if (!success)
+ return PyErr_SetFromWindowsErr(0);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *
win32_ConnectNamedPipe(PyObject *self, PyObject *args)
{
- HANDLE hNamedPipe;
- LPOVERLAPPED lpOverlapped;
- BOOL success;
+ HANDLE hNamedPipe;
+ LPOVERLAPPED lpOverlapped;
+ BOOL success;
- if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER,
- &hNamedPipe, &lpOverlapped))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER,
+ &hNamedPipe, &lpOverlapped))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- success = ConnectNamedPipe(hNamedPipe, lpOverlapped);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ success = ConnectNamedPipe(hNamedPipe, lpOverlapped);
+ Py_END_ALLOW_THREADS
- if (!success)
- return PyErr_SetFromWindowsErr(0);
+ if (!success)
+ return PyErr_SetFromWindowsErr(0);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *
win32_CreateFile(PyObject *self, PyObject *args)
{
- LPCTSTR lpFileName;
- DWORD dwDesiredAccess;
- DWORD dwShareMode;
- LPSECURITY_ATTRIBUTES lpSecurityAttributes;
- DWORD dwCreationDisposition;
- DWORD dwFlagsAndAttributes;
- HANDLE hTemplateFile;
- HANDLE handle;
-
- if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER
- F_DWORD F_DWORD F_HANDLE,
- &lpFileName, &dwDesiredAccess, &dwShareMode,
- &lpSecurityAttributes, &dwCreationDisposition,
- &dwFlagsAndAttributes, &hTemplateFile))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- handle = CreateFile(lpFileName, dwDesiredAccess,
- dwShareMode, lpSecurityAttributes,
- dwCreationDisposition,
- dwFlagsAndAttributes, hTemplateFile);
- Py_END_ALLOW_THREADS
-
- if (handle == INVALID_HANDLE_VALUE)
- return PyErr_SetFromWindowsErr(0);
-
- return Py_BuildValue(F_HANDLE, handle);
+ LPCTSTR lpFileName;
+ DWORD dwDesiredAccess;
+ DWORD dwShareMode;
+ LPSECURITY_ATTRIBUTES lpSecurityAttributes;
+ DWORD dwCreationDisposition;
+ DWORD dwFlagsAndAttributes;
+ HANDLE hTemplateFile;
+ HANDLE handle;
+
+ if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER
+ F_DWORD F_DWORD F_HANDLE,
+ &lpFileName, &dwDesiredAccess, &dwShareMode,
+ &lpSecurityAttributes, &dwCreationDisposition,
+ &dwFlagsAndAttributes, &hTemplateFile))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ handle = CreateFile(lpFileName, dwDesiredAccess,
+ dwShareMode, lpSecurityAttributes,
+ dwCreationDisposition,
+ dwFlagsAndAttributes, hTemplateFile);
+ Py_END_ALLOW_THREADS
+
+ if (handle == INVALID_HANDLE_VALUE)
+ return PyErr_SetFromWindowsErr(0);
+
+ return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_CreateNamedPipe(PyObject *self, PyObject *args)
{
- LPCTSTR lpName;
- DWORD dwOpenMode;
- DWORD dwPipeMode;
- DWORD nMaxInstances;
- DWORD nOutBufferSize;
- DWORD nInBufferSize;
- DWORD nDefaultTimeOut;
- LPSECURITY_ATTRIBUTES lpSecurityAttributes;
- HANDLE handle;
-
- if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD
- F_DWORD F_DWORD F_DWORD F_POINTER,
- &lpName, &dwOpenMode, &dwPipeMode,
- &nMaxInstances, &nOutBufferSize,
- &nInBufferSize, &nDefaultTimeOut,
- &lpSecurityAttributes))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode,
- nMaxInstances, nOutBufferSize,
- nInBufferSize, nDefaultTimeOut,
- lpSecurityAttributes);
- Py_END_ALLOW_THREADS
-
- if (handle == INVALID_HANDLE_VALUE)
- return PyErr_SetFromWindowsErr(0);
-
- return Py_BuildValue(F_HANDLE, handle);
+ LPCTSTR lpName;
+ DWORD dwOpenMode;
+ DWORD dwPipeMode;
+ DWORD nMaxInstances;
+ DWORD nOutBufferSize;
+ DWORD nInBufferSize;
+ DWORD nDefaultTimeOut;
+ LPSECURITY_ATTRIBUTES lpSecurityAttributes;
+ HANDLE handle;
+
+ if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD
+ F_DWORD F_DWORD F_DWORD F_POINTER,
+ &lpName, &dwOpenMode, &dwPipeMode,
+ &nMaxInstances, &nOutBufferSize,
+ &nInBufferSize, &nDefaultTimeOut,
+ &lpSecurityAttributes))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode,
+ nMaxInstances, nOutBufferSize,
+ nInBufferSize, nDefaultTimeOut,
+ lpSecurityAttributes);
+ Py_END_ALLOW_THREADS
+
+ if (handle == INVALID_HANDLE_VALUE)
+ return PyErr_SetFromWindowsErr(0);
+
+ return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_ExitProcess(PyObject *self, PyObject *args)
{
- UINT uExitCode;
+ UINT uExitCode;
- if (!PyArg_ParseTuple(args, "I", &uExitCode))
- return NULL;
+ if (!PyArg_ParseTuple(args, "I", &uExitCode))
+ return NULL;
- #if defined(Py_DEBUG)
- SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
- _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
- #endif
+ #if defined(Py_DEBUG)
+ SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
+ _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
+ #endif
- ExitProcess(uExitCode);
+ ExitProcess(uExitCode);
- return NULL;
+ return NULL;
}
static PyObject *
win32_GetLastError(PyObject *self, PyObject *args)
{
- return Py_BuildValue(F_DWORD, GetLastError());
+ return Py_BuildValue(F_DWORD, GetLastError());
}
static PyObject *
win32_OpenProcess(PyObject *self, PyObject *args)
{
- DWORD dwDesiredAccess;
- BOOL bInheritHandle;
- DWORD dwProcessId;
- HANDLE handle;
+ DWORD dwDesiredAccess;
+ BOOL bInheritHandle;
+ DWORD dwProcessId;
+ HANDLE handle;
- if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD,
- &dwDesiredAccess, &bInheritHandle, &dwProcessId))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD,
+ &dwDesiredAccess, &bInheritHandle, &dwProcessId))
+ return NULL;
- handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
- if (handle == NULL)
- return PyErr_SetFromWindowsErr(0);
+ handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
+ if (handle == NULL)
+ return PyErr_SetFromWindowsErr(0);
- return Py_BuildValue(F_HANDLE, handle);
+ return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_SetNamedPipeHandleState(PyObject *self, PyObject *args)
{
- HANDLE hNamedPipe;
- PyObject *oArgs[3];
- DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
- int i;
-
- if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
- &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
- return NULL;
-
- PyErr_Clear();
-
- for (i = 0 ; i < 3 ; i++) {
- if (oArgs[i] != Py_None) {
- dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
- if (PyErr_Occurred())
- return NULL;
- pArgs[i] = &dwArgs[i];
- }
- }
-
- if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
- return PyErr_SetFromWindowsErr(0);
-
- Py_RETURN_NONE;
+ HANDLE hNamedPipe;
+ PyObject *oArgs[3];
+ DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
+ int i;
+
+ if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
+ &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
+ return NULL;
+
+ PyErr_Clear();
+
+ for (i = 0 ; i < 3 ; i++) {
+ if (oArgs[i] != Py_None) {
+ dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
+ if (PyErr_Occurred())
+ return NULL;
+ pArgs[i] = &dwArgs[i];
+ }
+ }
+
+ if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
+ return PyErr_SetFromWindowsErr(0);
+
+ Py_RETURN_NONE;
}
static PyObject *
win32_WaitNamedPipe(PyObject *self, PyObject *args)
{
- LPCTSTR lpNamedPipeName;
- DWORD nTimeOut;
- BOOL success;
+ LPCTSTR lpNamedPipeName;
+ DWORD nTimeOut;
+ BOOL success;
- if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- success = WaitNamedPipe(lpNamedPipeName, nTimeOut);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ success = WaitNamedPipe(lpNamedPipeName, nTimeOut);
+ Py_END_ALLOW_THREADS
- if (!success)
- return PyErr_SetFromWindowsErr(0);
+ if (!success)
+ return PyErr_SetFromWindowsErr(0);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyMethodDef win32_methods[] = {
- WIN32_FUNCTION(CloseHandle),
- WIN32_FUNCTION(GetLastError),
- WIN32_FUNCTION(OpenProcess),
- WIN32_FUNCTION(ExitProcess),
- WIN32_FUNCTION(ConnectNamedPipe),
- WIN32_FUNCTION(CreateFile),
- WIN32_FUNCTION(CreateNamedPipe),
- WIN32_FUNCTION(SetNamedPipeHandleState),
- WIN32_FUNCTION(WaitNamedPipe),
- {NULL}
+ WIN32_FUNCTION(CloseHandle),
+ WIN32_FUNCTION(GetLastError),
+ WIN32_FUNCTION(OpenProcess),
+ WIN32_FUNCTION(ExitProcess),
+ WIN32_FUNCTION(ConnectNamedPipe),
+ WIN32_FUNCTION(CreateFile),
+ WIN32_FUNCTION(CreateNamedPipe),
+ WIN32_FUNCTION(SetNamedPipeHandleState),
+ WIN32_FUNCTION(WaitNamedPipe),
+ {NULL}
};
PyTypeObject Win32Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
+ PyVarObject_HEAD_INIT(NULL, 0)
};
PyObject *
create_win32_namespace(void)
{
- Win32Type.tp_name = "_multiprocessing.win32";
- Win32Type.tp_methods = win32_methods;
- if (PyType_Ready(&Win32Type) < 0)
- return NULL;
- Py_INCREF(&Win32Type);
-
- WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
- WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
- WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
- WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
- WIN32_CONSTANT(F_DWORD, GENERIC_READ);
- WIN32_CONSTANT(F_DWORD, GENERIC_WRITE);
- WIN32_CONSTANT(F_DWORD, INFINITE);
- WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
- WIN32_CONSTANT(F_DWORD, OPEN_EXISTING);
- WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
- WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
- WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
- WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
- WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
- WIN32_CONSTANT(F_DWORD, PIPE_WAIT);
- WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
-
- WIN32_CONSTANT("i", NULL);
-
- return (PyObject*)&Win32Type;
+ Win32Type.tp_name = "_multiprocessing.win32";
+ Win32Type.tp_methods = win32_methods;
+ if (PyType_Ready(&Win32Type) < 0)
+ return NULL;
+ Py_INCREF(&Win32Type);
+
+ WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
+ WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
+ WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
+ WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
+ WIN32_CONSTANT(F_DWORD, GENERIC_READ);
+ WIN32_CONSTANT(F_DWORD, GENERIC_WRITE);
+ WIN32_CONSTANT(F_DWORD, INFINITE);
+ WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
+ WIN32_CONSTANT(F_DWORD, OPEN_EXISTING);
+ WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
+ WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
+ WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
+ WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
+ WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
+ WIN32_CONSTANT(F_DWORD, PIPE_WAIT);
+ WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
+
+ WIN32_CONSTANT("i", NULL);
+
+ return (PyObject*)&Win32Type;
}
diff --git a/Modules/_randommodule.c b/Modules/_randommodule.c
index 05c09d8..57f5395 100644
--- a/Modules/_randommodule.c
+++ b/Modules/_randommodule.c
@@ -2,23 +2,23 @@
/* ------------------------------------------------------------------
The code in this module was based on a download from:
- http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
+ http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
It was modified in 2002 by Raymond Hettinger as follows:
- * the principal computational lines untouched except for tabbing.
+ * the principal computational lines untouched except for tabbing.
- * renamed genrand_res53() to random_random() and wrapped
- in python calling/return code.
+ * renamed genrand_res53() to random_random() and wrapped
+ in python calling/return code.
- * genrand_int32() and the helper functions, init_genrand()
- and init_by_array(), were declared static, wrapped in
- Python calling/return code. also, their global data
- references were replaced with structure references.
+ * genrand_int32() and the helper functions, init_genrand()
+ and init_by_array(), were declared static, wrapped in
+ Python calling/return code. also, their global data
+ references were replaced with structure references.
- * unused functions from the original were deleted.
- new, original C python code was added to implement the
- Random() interface.
+ * unused functions from the original were deleted.
+ new, original C python code was added to implement the
+ Random() interface.
The following are the verbatim comments from the original code:
@@ -36,15 +36,15 @@
are met:
1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
+ 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.
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
- products derived from this software without specific prior written
- permission.
+ products derived from this software without specific prior written
+ permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -67,24 +67,24 @@
/* ---------------------------------------------------------------*/
#include "Python.h"
-#include <time.h> /* for seeding to current time */
+#include <time.h> /* for seeding to current time */
/* Period parameters -- These are all magic. Don't change. */
#define N 624
#define M 397
-#define MATRIX_A 0x9908b0dfUL /* constant vector a */
+#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
typedef struct {
- PyObject_HEAD
- unsigned long state[N];
- int index;
+ PyObject_HEAD
+ unsigned long state[N];
+ int index;
} RandomObject;
static PyTypeObject Random_Type;
-#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
+#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
/* Random methods */
@@ -94,28 +94,28 @@ static PyTypeObject Random_Type;
static unsigned long
genrand_int32(RandomObject *self)
{
- unsigned long y;
- static unsigned long mag01[2]={0x0UL, MATRIX_A};
- /* mag01[x] = x * MATRIX_A for x=0,1 */
- unsigned long *mt;
-
- mt = self->state;
- if (self->index >= N) { /* generate N words at one time */
- int kk;
-
- for (kk=0;kk<N-M;kk++) {
- y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
- mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
- }
- for (;kk<N-1;kk++) {
- y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
- mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
- }
- y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
- mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
-
- self->index = 0;
- }
+ unsigned long y;
+ static unsigned long mag01[2]={0x0UL, MATRIX_A};
+ /* mag01[x] = x * MATRIX_A for x=0,1 */
+ unsigned long *mt;
+
+ mt = self->state;
+ if (self->index >= N) { /* generate N words at one time */
+ int kk;
+
+ for (kk=0;kk<N-M;kk++) {
+ y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
+ mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
+ }
+ for (;kk<N-1;kk++) {
+ y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
+ mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
+ }
+ y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
+ mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
+
+ self->index = 0;
+ }
y = mt[self->index++];
y ^= (y >> 11);
@@ -137,31 +137,31 @@ genrand_int32(RandomObject *self)
static PyObject *
random_random(RandomObject *self)
{
- unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
- return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
+ unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
+ return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
/* initializes mt[N] with a seed */
static void
init_genrand(RandomObject *self, unsigned long s)
{
- int mti;
- unsigned long *mt;
-
- mt = self->state;
- mt[0]= s & 0xffffffffUL;
- for (mti=1; mti<N; mti++) {
- mt[mti] =
- (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
- /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
- /* In the previous versions, MSBs of the seed affect */
- /* only MSBs of the array mt[]. */
- /* 2002/01/09 modified by Makoto Matsumoto */
- mt[mti] &= 0xffffffffUL;
- /* for >32 bit machines */
- }
- self->index = mti;
- return;
+ int mti;
+ unsigned long *mt;
+
+ mt = self->state;
+ mt[0]= s & 0xffffffffUL;
+ for (mti=1; mti<N; mti++) {
+ mt[mti] =
+ (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
+ /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
+ /* In the previous versions, MSBs of the seed affect */
+ /* only MSBs of the array mt[]. */
+ /* 2002/01/09 modified by Makoto Matsumoto */
+ mt[mti] &= 0xffffffffUL;
+ /* for >32 bit machines */
+ }
+ self->index = mti;
+ return;
}
/* initialize by an array with array-length */
@@ -170,28 +170,28 @@ init_genrand(RandomObject *self, unsigned long s)
static PyObject *
init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length)
{
- unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */
- unsigned long *mt;
-
- mt = self->state;
- init_genrand(self, 19650218UL);
- i=1; j=0;
- k = (N>key_length ? N : key_length);
- for (; k; k--) {
- mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
- + init_key[j] + j; /* non linear */
- mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++; j++;
- if (i>=N) { mt[0] = mt[N-1]; i=1; }
- if (j>=key_length) j=0;
- }
- for (k=N-1; k; k--) {
- mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- - i; /* non linear */
- mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++;
- if (i>=N) { mt[0] = mt[N-1]; i=1; }
- }
+ unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */
+ unsigned long *mt;
+
+ mt = self->state;
+ init_genrand(self, 19650218UL);
+ i=1; j=0;
+ k = (N>key_length ? N : key_length);
+ for (; k; k--) {
+ mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ + init_key[j] + j; /* non linear */
+ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
+ i++; j++;
+ if (i>=N) { mt[0] = mt[N-1]; i=1; }
+ if (j>=key_length) j=0;
+ }
+ for (k=N-1; k; k--) {
+ mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
+ - i; /* non linear */
+ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
+ i++;
+ if (i>=N) { mt[0] = mt[N-1]; i=1; }
+ }
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
Py_INCREF(Py_None);
@@ -206,291 +206,291 @@ init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_le
static PyObject *
random_seed(RandomObject *self, PyObject *args)
{
- PyObject *result = NULL; /* guilty until proved innocent */
- PyObject *masklower = NULL;
- PyObject *thirtytwo = NULL;
- PyObject *n = NULL;
- unsigned long *key = NULL;
- unsigned long keymax; /* # of allocated slots in key */
- unsigned long keyused; /* # of used slots in key */
- int err;
-
- PyObject *arg = NULL;
-
- if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
- return NULL;
-
- if (arg == NULL || arg == Py_None) {
- time_t now;
-
- time(&now);
- init_genrand(self, (unsigned long)now);
- Py_INCREF(Py_None);
- return Py_None;
- }
- /* If the arg is an int or long, use its absolute value; else use
- * the absolute value of its hash code.
- */
- if (PyLong_Check(arg))
- n = PyNumber_Absolute(arg);
- else {
- long hash = PyObject_Hash(arg);
- if (hash == -1)
- goto Done;
- n = PyLong_FromUnsignedLong((unsigned long)hash);
- }
- if (n == NULL)
- goto Done;
-
- /* Now split n into 32-bit chunks, from the right. Each piece is
- * stored into key, which has a capacity of keymax chunks, of which
- * keyused are filled. Alas, the repeated shifting makes this a
- * quadratic-time algorithm; we'd really like to use
- * _PyLong_AsByteArray here, but then we'd have to break into the
- * long representation to figure out how big an array was needed
- * in advance.
- */
- keymax = 8; /* arbitrary; grows later if needed */
- keyused = 0;
- key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));
- if (key == NULL)
- goto Done;
-
- masklower = PyLong_FromUnsignedLong(0xffffffffU);
- if (masklower == NULL)
- goto Done;
- thirtytwo = PyLong_FromLong(32L);
- if (thirtytwo == NULL)
- goto Done;
- while ((err=PyObject_IsTrue(n))) {
- PyObject *newn;
- PyObject *pychunk;
- unsigned long chunk;
-
- if (err == -1)
- goto Done;
- pychunk = PyNumber_And(n, masklower);
- if (pychunk == NULL)
- goto Done;
- chunk = PyLong_AsUnsignedLong(pychunk);
- Py_DECREF(pychunk);
- if (chunk == (unsigned long)-1 && PyErr_Occurred())
- goto Done;
- newn = PyNumber_Rshift(n, thirtytwo);
- if (newn == NULL)
- goto Done;
- Py_DECREF(n);
- n = newn;
- if (keyused >= keymax) {
- unsigned long bigger = keymax << 1;
- if ((bigger >> 1) != keymax) {
- PyErr_NoMemory();
- goto Done;
- }
- key = (unsigned long *)PyMem_Realloc(key,
- bigger * sizeof(*key));
- if (key == NULL)
- goto Done;
- keymax = bigger;
- }
- assert(keyused < keymax);
- key[keyused++] = chunk;
- }
-
- if (keyused == 0)
- key[keyused++] = 0UL;
- result = init_by_array(self, key, keyused);
+ PyObject *result = NULL; /* guilty until proved innocent */
+ PyObject *masklower = NULL;
+ PyObject *thirtytwo = NULL;
+ PyObject *n = NULL;
+ unsigned long *key = NULL;
+ unsigned long keymax; /* # of allocated slots in key */
+ unsigned long keyused; /* # of used slots in key */
+ int err;
+
+ PyObject *arg = NULL;
+
+ if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
+ return NULL;
+
+ if (arg == NULL || arg == Py_None) {
+ time_t now;
+
+ time(&now);
+ init_genrand(self, (unsigned long)now);
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ /* If the arg is an int or long, use its absolute value; else use
+ * the absolute value of its hash code.
+ */
+ if (PyLong_Check(arg))
+ n = PyNumber_Absolute(arg);
+ else {
+ long hash = PyObject_Hash(arg);
+ if (hash == -1)
+ goto Done;
+ n = PyLong_FromUnsignedLong((unsigned long)hash);
+ }
+ if (n == NULL)
+ goto Done;
+
+ /* Now split n into 32-bit chunks, from the right. Each piece is
+ * stored into key, which has a capacity of keymax chunks, of which
+ * keyused are filled. Alas, the repeated shifting makes this a
+ * quadratic-time algorithm; we'd really like to use
+ * _PyLong_AsByteArray here, but then we'd have to break into the
+ * long representation to figure out how big an array was needed
+ * in advance.
+ */
+ keymax = 8; /* arbitrary; grows later if needed */
+ keyused = 0;
+ key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));
+ if (key == NULL)
+ goto Done;
+
+ masklower = PyLong_FromUnsignedLong(0xffffffffU);
+ if (masklower == NULL)
+ goto Done;
+ thirtytwo = PyLong_FromLong(32L);
+ if (thirtytwo == NULL)
+ goto Done;
+ while ((err=PyObject_IsTrue(n))) {
+ PyObject *newn;
+ PyObject *pychunk;
+ unsigned long chunk;
+
+ if (err == -1)
+ goto Done;
+ pychunk = PyNumber_And(n, masklower);
+ if (pychunk == NULL)
+ goto Done;
+ chunk = PyLong_AsUnsignedLong(pychunk);
+ Py_DECREF(pychunk);
+ if (chunk == (unsigned long)-1 && PyErr_Occurred())
+ goto Done;
+ newn = PyNumber_Rshift(n, thirtytwo);
+ if (newn == NULL)
+ goto Done;
+ Py_DECREF(n);
+ n = newn;
+ if (keyused >= keymax) {
+ unsigned long bigger = keymax << 1;
+ if ((bigger >> 1) != keymax) {
+ PyErr_NoMemory();
+ goto Done;
+ }
+ key = (unsigned long *)PyMem_Realloc(key,
+ bigger * sizeof(*key));
+ if (key == NULL)
+ goto Done;
+ keymax = bigger;
+ }
+ assert(keyused < keymax);
+ key[keyused++] = chunk;
+ }
+
+ if (keyused == 0)
+ key[keyused++] = 0UL;
+ result = init_by_array(self, key, keyused);
Done:
- Py_XDECREF(masklower);
- Py_XDECREF(thirtytwo);
- Py_XDECREF(n);
- PyMem_Free(key);
- return result;
+ Py_XDECREF(masklower);
+ Py_XDECREF(thirtytwo);
+ Py_XDECREF(n);
+ PyMem_Free(key);
+ return result;
}
static PyObject *
random_getstate(RandomObject *self)
{
- PyObject *state;
- PyObject *element;
- int i;
-
- state = PyTuple_New(N+1);
- if (state == NULL)
- return NULL;
- for (i=0; i<N ; i++) {
- element = PyLong_FromUnsignedLong(self->state[i]);
- if (element == NULL)
- goto Fail;
- PyTuple_SET_ITEM(state, i, element);
- }
- element = PyLong_FromLong((long)(self->index));
- if (element == NULL)
- goto Fail;
- PyTuple_SET_ITEM(state, i, element);
- return state;
+ PyObject *state;
+ PyObject *element;
+ int i;
+
+ state = PyTuple_New(N+1);
+ if (state == NULL)
+ return NULL;
+ for (i=0; i<N ; i++) {
+ element = PyLong_FromUnsignedLong(self->state[i]);
+ if (element == NULL)
+ goto Fail;
+ PyTuple_SET_ITEM(state, i, element);
+ }
+ element = PyLong_FromLong((long)(self->index));
+ if (element == NULL)
+ goto Fail;
+ PyTuple_SET_ITEM(state, i, element);
+ return state;
Fail:
- Py_DECREF(state);
- return NULL;
+ Py_DECREF(state);
+ return NULL;
}
static PyObject *
random_setstate(RandomObject *self, PyObject *state)
{
- int i;
- unsigned long element;
- long index;
-
- if (!PyTuple_Check(state)) {
- PyErr_SetString(PyExc_TypeError,
- "state vector must be a tuple");
- return NULL;
- }
- if (PyTuple_Size(state) != N+1) {
- PyErr_SetString(PyExc_ValueError,
- "state vector is the wrong size");
- return NULL;
- }
-
- for (i=0; i<N ; i++) {
- element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
- if (element == (unsigned long)-1 && PyErr_Occurred())
- return NULL;
- self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */
- }
-
- index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
- if (index == -1 && PyErr_Occurred())
- return NULL;
- self->index = (int)index;
-
- Py_INCREF(Py_None);
- return Py_None;
+ int i;
+ unsigned long element;
+ long index;
+
+ if (!PyTuple_Check(state)) {
+ PyErr_SetString(PyExc_TypeError,
+ "state vector must be a tuple");
+ return NULL;
+ }
+ if (PyTuple_Size(state) != N+1) {
+ PyErr_SetString(PyExc_ValueError,
+ "state vector is the wrong size");
+ return NULL;
+ }
+
+ for (i=0; i<N ; i++) {
+ element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
+ if (element == (unsigned long)-1 && PyErr_Occurred())
+ return NULL;
+ self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */
+ }
+
+ index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
+ if (index == -1 && PyErr_Occurred())
+ return NULL;
+ self->index = (int)index;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
random_getrandbits(RandomObject *self, PyObject *args)
{
- int k, i, bytes;
- unsigned long r;
- unsigned char *bytearray;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
- return NULL;
-
- if (k <= 0) {
- PyErr_SetString(PyExc_ValueError,
- "number of bits must be greater than zero");
- return NULL;
- }
-
- bytes = ((k - 1) / 32 + 1) * 4;
- bytearray = (unsigned char *)PyMem_Malloc(bytes);
- if (bytearray == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
-
- /* Fill-out whole words, byte-by-byte to avoid endianness issues */
- for (i=0 ; i<bytes ; i+=4, k-=32) {
- r = genrand_int32(self);
- if (k < 32)
- r >>= (32 - k);
- bytearray[i+0] = (unsigned char)r;
- bytearray[i+1] = (unsigned char)(r >> 8);
- bytearray[i+2] = (unsigned char)(r >> 16);
- bytearray[i+3] = (unsigned char)(r >> 24);
- }
-
- /* little endian order to match bytearray assignment order */
- result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
- PyMem_Free(bytearray);
- return result;
+ int k, i, bytes;
+ unsigned long r;
+ unsigned char *bytearray;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
+ return NULL;
+
+ if (k <= 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "number of bits must be greater than zero");
+ return NULL;
+ }
+
+ bytes = ((k - 1) / 32 + 1) * 4;
+ bytearray = (unsigned char *)PyMem_Malloc(bytes);
+ if (bytearray == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ /* Fill-out whole words, byte-by-byte to avoid endianness issues */
+ for (i=0 ; i<bytes ; i+=4, k-=32) {
+ r = genrand_int32(self);
+ if (k < 32)
+ r >>= (32 - k);
+ bytearray[i+0] = (unsigned char)r;
+ bytearray[i+1] = (unsigned char)(r >> 8);
+ bytearray[i+2] = (unsigned char)(r >> 16);
+ bytearray[i+3] = (unsigned char)(r >> 24);
+ }
+
+ /* little endian order to match bytearray assignment order */
+ result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
+ PyMem_Free(bytearray);
+ return result;
}
static PyObject *
random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- RandomObject *self;
- PyObject *tmp;
-
- if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
- return NULL;
-
- self = (RandomObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
- tmp = random_seed(self, args);
- if (tmp == NULL) {
- Py_DECREF(self);
- return NULL;
- }
- Py_DECREF(tmp);
- return (PyObject *)self;
+ RandomObject *self;
+ PyObject *tmp;
+
+ if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
+ return NULL;
+
+ self = (RandomObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+ tmp = random_seed(self, args);
+ if (tmp == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ Py_DECREF(tmp);
+ return (PyObject *)self;
}
static PyMethodDef random_methods[] = {
- {"random", (PyCFunction)random_random, METH_NOARGS,
- PyDoc_STR("random() -> x in the interval [0, 1).")},
- {"seed", (PyCFunction)random_seed, METH_VARARGS,
- PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
- {"getstate", (PyCFunction)random_getstate, METH_NOARGS,
- PyDoc_STR("getstate() -> tuple containing the current state.")},
- {"setstate", (PyCFunction)random_setstate, METH_O,
- PyDoc_STR("setstate(state) -> None. Restores generator state.")},
- {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
- PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
- "k random bits.")},
- {NULL, NULL} /* sentinel */
+ {"random", (PyCFunction)random_random, METH_NOARGS,
+ PyDoc_STR("random() -> x in the interval [0, 1).")},
+ {"seed", (PyCFunction)random_seed, METH_VARARGS,
+ PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
+ {"getstate", (PyCFunction)random_getstate, METH_NOARGS,
+ PyDoc_STR("getstate() -> tuple containing the current state.")},
+ {"setstate", (PyCFunction)random_setstate, METH_O,
+ PyDoc_STR("setstate(state) -> None. Restores generator state.")},
+ {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
+ PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
+ "k random bits.")},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(random_doc,
"Random() -> create a random number generator with its own internal state.");
static PyTypeObject Random_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_random.Random", /*tp_name*/
- sizeof(RandomObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- 0, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
- random_doc, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- random_methods, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- random_new, /*tp_new*/
- PyObject_Free, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_random.Random", /*tp_name*/
+ sizeof(RandomObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ 0, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ random_doc, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ random_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ random_new, /*tp_new*/
+ PyObject_Free, /*tp_free*/
+ 0, /*tp_is_gc*/
};
PyDoc_STRVAR(module_doc,
@@ -498,28 +498,28 @@ PyDoc_STRVAR(module_doc,
static struct PyModuleDef _randommodule = {
- PyModuleDef_HEAD_INIT,
- "_random",
- module_doc,
- -1,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_random",
+ module_doc,
+ -1,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__random(void)
{
- PyObject *m;
-
- if (PyType_Ready(&Random_Type) < 0)
- return NULL;
- m = PyModule_Create(&_randommodule);
- if (m == NULL)
- return NULL;
- Py_INCREF(&Random_Type);
- PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
- return m;
+ PyObject *m;
+
+ if (PyType_Ready(&Random_Type) < 0)
+ return NULL;
+ m = PyModule_Create(&_randommodule);
+ if (m == NULL)
+ return NULL;
+ Py_INCREF(&Random_Type);
+ PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
+ return m;
}
diff --git a/Modules/_scproxy.c b/Modules/_scproxy.c
index 602fbe3..30afa6a 100644
--- a/Modules/_scproxy.c
+++ b/Modules/_scproxy.c
@@ -5,167 +5,167 @@
#include <Python.h>
#include <SystemConfiguration/SystemConfiguration.h>
-static int32_t
+static int32_t
cfnum_to_int32(CFNumberRef num)
{
- int32_t result;
+ int32_t result;
- CFNumberGetValue(num, kCFNumberSInt32Type, &result);
- return result;
+ CFNumberGetValue(num, kCFNumberSInt32Type, &result);
+ return result;
}
static PyObject*
cfstring_to_pystring(CFStringRef ref)
{
- const char* s;
-
- s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
- if (s) {
- return PyUnicode_DecodeUTF8(
- s, strlen(s), NULL);
-
- } else {
- CFIndex len = CFStringGetLength(ref);
- Boolean ok;
- PyObject* result;
- char* buf;
-
- buf = PyMem_Malloc(len*4);
- if (buf == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
-
- ok = CFStringGetCString(ref,
- buf, len * 4,
- kCFStringEncodingUTF8);
- if (!ok) {
- PyMem_Free(buf);
- return NULL;
- } else {
- result = PyUnicode_DecodeUTF8(
- buf, strlen(buf), NULL);
- PyMem_Free(buf);
- }
- return result;
- }
+ const char* s;
+
+ s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
+ if (s) {
+ return PyUnicode_DecodeUTF8(
+ s, strlen(s), NULL);
+
+ } else {
+ CFIndex len = CFStringGetLength(ref);
+ Boolean ok;
+ PyObject* result;
+ char* buf;
+
+ buf = PyMem_Malloc(len*4);
+ if (buf == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ ok = CFStringGetCString(ref,
+ buf, len * 4,
+ kCFStringEncodingUTF8);
+ if (!ok) {
+ PyMem_Free(buf);
+ return NULL;
+ } else {
+ result = PyUnicode_DecodeUTF8(
+ buf, strlen(buf), NULL);
+ PyMem_Free(buf);
+ }
+ return result;
+ }
}
static PyObject*
get_proxy_settings(PyObject* mod __attribute__((__unused__)))
{
- CFDictionaryRef proxyDict = NULL;
- CFNumberRef aNum = NULL;
- CFArrayRef anArray = NULL;
- PyObject* result = NULL;
- PyObject* v;
- int r;
-
- proxyDict = SCDynamicStoreCopyProxies(NULL);
- if (!proxyDict) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- result = PyDict_New();
- if (result == NULL) goto error;
-
- if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) {
- aNum = CFDictionaryGetValue(proxyDict,
- kSCPropNetProxiesExcludeSimpleHostnames);
- if (aNum == NULL) {
- v = PyBool_FromLong(1);
- } else {
- v = PyBool_FromLong(cfnum_to_int32(aNum));
- }
- } else {
- v = PyBool_FromLong(1);
- }
-
- if (v == NULL) goto error;
-
- r = PyDict_SetItemString(result, "exclude_simple", v);
- Py_DECREF(v); v = NULL;
- if (r == -1) goto error;
-
- anArray = CFDictionaryGetValue(proxyDict,
- kSCPropNetProxiesExceptionsList);
- if (anArray != NULL) {
- CFIndex len = CFArrayGetCount(anArray);
- CFIndex i;
- v = PyTuple_New(len);
- if (v == NULL) goto error;
-
- r = PyDict_SetItemString(result, "exceptions", v);
- Py_DECREF(v);
- if (r == -1) goto error;
-
- for (i = 0; i < len; i++) {
- CFStringRef aString = NULL;
-
- aString = CFArrayGetValueAtIndex(anArray, i);
- if (aString == NULL) {
- PyTuple_SetItem(v, i, Py_None);
- Py_INCREF(Py_None);
- } else {
- PyObject* t = cfstring_to_pystring(aString);
- if (!t) {
- PyTuple_SetItem(v, i, Py_None);
- Py_INCREF(Py_None);
- } else {
- PyTuple_SetItem(v, i, t);
- }
- }
- }
- }
-
- CFRelease(proxyDict);
- return result;
+ CFDictionaryRef proxyDict = NULL;
+ CFNumberRef aNum = NULL;
+ CFArrayRef anArray = NULL;
+ PyObject* result = NULL;
+ PyObject* v;
+ int r;
+
+ proxyDict = SCDynamicStoreCopyProxies(NULL);
+ if (!proxyDict) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ result = PyDict_New();
+ if (result == NULL) goto error;
+
+ if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) {
+ aNum = CFDictionaryGetValue(proxyDict,
+ kSCPropNetProxiesExcludeSimpleHostnames);
+ if (aNum == NULL) {
+ v = PyBool_FromLong(1);
+ } else {
+ v = PyBool_FromLong(cfnum_to_int32(aNum));
+ }
+ } else {
+ v = PyBool_FromLong(1);
+ }
+
+ if (v == NULL) goto error;
+
+ r = PyDict_SetItemString(result, "exclude_simple", v);
+ Py_DECREF(v); v = NULL;
+ if (r == -1) goto error;
+
+ anArray = CFDictionaryGetValue(proxyDict,
+ kSCPropNetProxiesExceptionsList);
+ if (anArray != NULL) {
+ CFIndex len = CFArrayGetCount(anArray);
+ CFIndex i;
+ v = PyTuple_New(len);
+ if (v == NULL) goto error;
+
+ r = PyDict_SetItemString(result, "exceptions", v);
+ Py_DECREF(v);
+ if (r == -1) goto error;
+
+ for (i = 0; i < len; i++) {
+ CFStringRef aString = NULL;
+
+ aString = CFArrayGetValueAtIndex(anArray, i);
+ if (aString == NULL) {
+ PyTuple_SetItem(v, i, Py_None);
+ Py_INCREF(Py_None);
+ } else {
+ PyObject* t = cfstring_to_pystring(aString);
+ if (!t) {
+ PyTuple_SetItem(v, i, Py_None);
+ Py_INCREF(Py_None);
+ } else {
+ PyTuple_SetItem(v, i, t);
+ }
+ }
+ }
+ }
+
+ CFRelease(proxyDict);
+ return result;
error:
- if (proxyDict) CFRelease(proxyDict);
- Py_XDECREF(result);
- return NULL;
+ if (proxyDict) CFRelease(proxyDict);
+ Py_XDECREF(result);
+ return NULL;
}
static int
set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict,
- CFStringRef enabledKey,
- CFStringRef hostKey, CFStringRef portKey)
+ CFStringRef enabledKey,
+ CFStringRef hostKey, CFStringRef portKey)
{
- CFNumberRef aNum;
-
- aNum = CFDictionaryGetValue(proxyDict, enabledKey);
- if (aNum && cfnum_to_int32(aNum)) {
- CFStringRef hostString;
-
- hostString = CFDictionaryGetValue(proxyDict, hostKey);
- aNum = CFDictionaryGetValue(proxyDict, portKey);
-
- if (hostString) {
- int r;
- PyObject* h = cfstring_to_pystring(hostString);
- PyObject* v;
- if (h) {
- if (aNum) {
- int32_t port = cfnum_to_int32(aNum);
- v = PyUnicode_FromFormat("http://%U:%ld",
- h, (long)port);
- } else {
- v = PyUnicode_FromFormat("http://%U", h);
- }
- Py_DECREF(h);
- if (!v) return -1;
- r = PyDict_SetItemString(proxies, proto,
- v);
- Py_DECREF(v);
- return r;
- }
- }
-
- }
- return 0;
+ CFNumberRef aNum;
+
+ aNum = CFDictionaryGetValue(proxyDict, enabledKey);
+ if (aNum && cfnum_to_int32(aNum)) {
+ CFStringRef hostString;
+
+ hostString = CFDictionaryGetValue(proxyDict, hostKey);
+ aNum = CFDictionaryGetValue(proxyDict, portKey);
+
+ if (hostString) {
+ int r;
+ PyObject* h = cfstring_to_pystring(hostString);
+ PyObject* v;
+ if (h) {
+ if (aNum) {
+ int32_t port = cfnum_to_int32(aNum);
+ v = PyUnicode_FromFormat("http://%U:%ld",
+ h, (long)port);
+ } else {
+ v = PyUnicode_FromFormat("http://%U", h);
+ }
+ Py_DECREF(h);
+ if (!v) return -1;
+ r = PyDict_SetItemString(proxies, proto,
+ v);
+ Py_DECREF(v);
+ return r;
+ }
+ }
+
+ }
+ return 0;
}
@@ -173,75 +173,75 @@ set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict,
static PyObject*
get_proxies(PyObject* mod __attribute__((__unused__)))
{
- PyObject* result = NULL;
- int r;
- CFDictionaryRef proxyDict = NULL;
-
- proxyDict = SCDynamicStoreCopyProxies(NULL);
- if (proxyDict == NULL) {
- return PyDict_New();
- }
-
- result = PyDict_New();
- if (result == NULL) goto error;
-
- r = set_proxy(result, "http", proxyDict,
- kSCPropNetProxiesHTTPEnable,
- kSCPropNetProxiesHTTPProxy,
- kSCPropNetProxiesHTTPPort);
- if (r == -1) goto error;
- r = set_proxy(result, "https", proxyDict,
- kSCPropNetProxiesHTTPSEnable,
- kSCPropNetProxiesHTTPSProxy,
- kSCPropNetProxiesHTTPSPort);
- if (r == -1) goto error;
- r = set_proxy(result, "ftp", proxyDict,
- kSCPropNetProxiesFTPEnable,
- kSCPropNetProxiesFTPProxy,
- kSCPropNetProxiesFTPPort);
- if (r == -1) goto error;
- r = set_proxy(result, "gopher", proxyDict,
- kSCPropNetProxiesGopherEnable,
- kSCPropNetProxiesGopherProxy,
- kSCPropNetProxiesGopherPort);
- if (r == -1) goto error;
-
- CFRelease(proxyDict);
- return result;
+ PyObject* result = NULL;
+ int r;
+ CFDictionaryRef proxyDict = NULL;
+
+ proxyDict = SCDynamicStoreCopyProxies(NULL);
+ if (proxyDict == NULL) {
+ return PyDict_New();
+ }
+
+ result = PyDict_New();
+ if (result == NULL) goto error;
+
+ r = set_proxy(result, "http", proxyDict,
+ kSCPropNetProxiesHTTPEnable,
+ kSCPropNetProxiesHTTPProxy,
+ kSCPropNetProxiesHTTPPort);
+ if (r == -1) goto error;
+ r = set_proxy(result, "https", proxyDict,
+ kSCPropNetProxiesHTTPSEnable,
+ kSCPropNetProxiesHTTPSProxy,
+ kSCPropNetProxiesHTTPSPort);
+ if (r == -1) goto error;
+ r = set_proxy(result, "ftp", proxyDict,
+ kSCPropNetProxiesFTPEnable,
+ kSCPropNetProxiesFTPProxy,
+ kSCPropNetProxiesFTPPort);
+ if (r == -1) goto error;
+ r = set_proxy(result, "gopher", proxyDict,
+ kSCPropNetProxiesGopherEnable,
+ kSCPropNetProxiesGopherProxy,
+ kSCPropNetProxiesGopherPort);
+ if (r == -1) goto error;
+
+ CFRelease(proxyDict);
+ return result;
error:
- if (proxyDict) CFRelease(proxyDict);
- Py_XDECREF(result);
- return NULL;
+ if (proxyDict) CFRelease(proxyDict);
+ Py_XDECREF(result);
+ return NULL;
}
static PyMethodDef mod_methods[] = {
- {
- "_get_proxy_settings",
- (PyCFunction)get_proxy_settings,
- METH_NOARGS,
- NULL,
- },
- {
- "_get_proxies",
- (PyCFunction)get_proxies,
- METH_NOARGS,
- NULL,
- },
- { 0, 0, 0, 0 }
+ {
+ "_get_proxy_settings",
+ (PyCFunction)get_proxy_settings,
+ METH_NOARGS,
+ NULL,
+ },
+ {
+ "_get_proxies",
+ (PyCFunction)get_proxies,
+ METH_NOARGS,
+ NULL,
+ },
+ { 0, 0, 0, 0 }
};
static struct PyModuleDef mod_module = {
- PyModuleDef_HEAD_INIT,
- "_scproxy",
- NULL,
- -1,
- mod_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_scproxy",
+ NULL,
+ -1,
+ mod_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
@@ -249,10 +249,10 @@ static struct PyModuleDef mod_module = {
extern "C" {
#endif
-PyObject*
+PyObject*
PyInit__scproxy(void)
{
- return PyModule_Create(&mod_module);
+ return PyModule_Create(&mod_module);
}
#ifdef __cplusplus
diff --git a/Modules/_sqlite/module.c b/Modules/_sqlite/module.c
index ebe6019..db55eaa 100644
--- a/Modules/_sqlite/module.c
+++ b/Modules/_sqlite/module.c
@@ -64,7 +64,7 @@ static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
&database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
{
- return NULL;
+ return NULL;
}
if (factory == NULL) {
@@ -93,7 +93,7 @@ static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
{
- return NULL;
+ return NULL;
}
if (sqlite3_complete(statement)) {
@@ -122,7 +122,7 @@ static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyOb
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
{
- return NULL;
+ return NULL;
}
rc = sqlite3_enable_shared_cache(do_enable);
@@ -302,15 +302,15 @@ static IntConstantPair _int_constants[] = {
static struct PyModuleDef _sqlite3module = {
- PyModuleDef_HEAD_INIT,
- "_sqlite3",
- NULL,
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_sqlite3",
+ NULL,
+ -1,
+ module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC PyInit__sqlite3(void)
@@ -329,7 +329,7 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
(pysqlite_statement_setup_types() < 0) ||
(pysqlite_prepare_protocol_setup_types() < 0)
) {
- Py_DECREF(module);
+ Py_DECREF(module);
return NULL;
}
@@ -448,7 +448,7 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
/* Original comment from _bsddb.c in the Python core. This is also still
* needed nowadays for Python 2.3/2.4.
- *
+ *
* PyEval_InitThreads is called here due to a quirk in python 1.5
* - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
* The global interpreter lock is not initialized until the first
@@ -467,8 +467,8 @@ error:
if (PyErr_Occurred())
{
PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
- Py_DECREF(module);
- module = NULL;
+ Py_DECREF(module);
+ module = NULL;
}
return module;
}
diff --git a/Modules/_struct.c b/Modules/_struct.c
index 6122637..26179cc 100644
--- a/Modules/_struct.c
+++ b/Modules/_struct.c
@@ -14,30 +14,30 @@ static PyTypeObject PyStructType;
/* The translation function for each format character is table driven */
typedef struct _formatdef {
- char format;
- Py_ssize_t size;
- Py_ssize_t alignment;
- PyObject* (*unpack)(const char *,
- const struct _formatdef *);
- int (*pack)(char *, PyObject *,
- const struct _formatdef *);
+ char format;
+ Py_ssize_t size;
+ Py_ssize_t alignment;
+ PyObject* (*unpack)(const char *,
+ const struct _formatdef *);
+ int (*pack)(char *, PyObject *,
+ const struct _formatdef *);
} formatdef;
typedef struct _formatcode {
- const struct _formatdef *fmtdef;
- Py_ssize_t offset;
- Py_ssize_t size;
+ const struct _formatdef *fmtdef;
+ Py_ssize_t offset;
+ Py_ssize_t size;
} formatcode;
/* Struct object interface */
typedef struct {
- PyObject_HEAD
- Py_ssize_t s_size;
- Py_ssize_t s_len;
- formatcode *s_codes;
- PyObject *s_format;
- PyObject *weakreflist; /* List of weak references */
+ PyObject_HEAD
+ Py_ssize_t s_size;
+ Py_ssize_t s_len;
+ formatcode *s_codes;
+ PyObject *s_format;
+ PyObject *weakreflist; /* List of weak references */
} PyStructObject;
@@ -95,25 +95,25 @@ typedef struct { char c; _Bool x; } s_bool;
static PyObject *
get_pylong(PyObject *v)
{
- assert(v != NULL);
- if (!PyLong_Check(v)) {
- /* Not an integer; try to use __index__ to convert. */
- if (PyIndex_Check(v)) {
- v = PyNumber_Index(v);
- if (v == NULL)
- return NULL;
- }
- else {
- PyErr_SetString(StructError,
- "required argument is not an integer");
- return NULL;
- }
- }
- else
- Py_INCREF(v);
-
- assert(PyLong_Check(v));
- return v;
+ assert(v != NULL);
+ if (!PyLong_Check(v)) {
+ /* Not an integer; try to use __index__ to convert. */
+ if (PyIndex_Check(v)) {
+ v = PyNumber_Index(v);
+ if (v == NULL)
+ return NULL;
+ }
+ else {
+ PyErr_SetString(StructError,
+ "required argument is not an integer");
+ return NULL;
+ }
+ }
+ else
+ Py_INCREF(v);
+
+ assert(PyLong_Check(v));
+ return v;
}
/* Helper routine to get a C long and raise the appropriate error if it isn't
@@ -122,22 +122,22 @@ get_pylong(PyObject *v)
static int
get_long(PyObject *v, long *p)
{
- long x;
+ long x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsLong(v);
- Py_DECREF(v);
- if (x == (long)-1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_SetString(StructError,
- "argument out of range");
- return -1;
- }
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsLong(v);
+ Py_DECREF(v);
+ if (x == (long)-1 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_SetString(StructError,
+ "argument out of range");
+ return -1;
+ }
+ *p = x;
+ return 0;
}
@@ -146,22 +146,22 @@ get_long(PyObject *v, long *p)
static int
get_ulong(PyObject *v, unsigned long *p)
{
- unsigned long x;
+ unsigned long x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsUnsignedLong(v);
- Py_DECREF(v);
- if (x == (unsigned long)-1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_SetString(StructError,
- "argument out of range");
- return -1;
- }
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsUnsignedLong(v);
+ Py_DECREF(v);
+ if (x == (unsigned long)-1 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_SetString(StructError,
+ "argument out of range");
+ return -1;
+ }
+ *p = x;
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -171,22 +171,22 @@ get_ulong(PyObject *v, unsigned long *p)
static int
get_longlong(PyObject *v, PY_LONG_LONG *p)
{
- PY_LONG_LONG x;
+ PY_LONG_LONG x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsLongLong(v);
- Py_DECREF(v);
- if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_SetString(StructError,
- "argument out of range");
- return -1;
- }
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsLongLong(v);
+ Py_DECREF(v);
+ if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_SetString(StructError,
+ "argument out of range");
+ return -1;
+ }
+ *p = x;
+ return 0;
}
/* Same, but handling native unsigned long long. */
@@ -194,22 +194,22 @@ get_longlong(PyObject *v, PY_LONG_LONG *p)
static int
get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
{
- unsigned PY_LONG_LONG x;
+ unsigned PY_LONG_LONG x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsUnsignedLongLong(v);
- Py_DECREF(v);
- if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_SetString(StructError,
- "argument out of range");
- return -1;
- }
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsUnsignedLongLong(v);
+ Py_DECREF(v);
+ if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_SetString(StructError,
+ "argument out of range");
+ return -1;
+ }
+ *p = x;
+ return 0;
}
#endif
@@ -222,57 +222,57 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
static PyObject *
unpack_float(const char *p, /* start of 4-byte string */
- int le) /* true for little-endian, false for big-endian */
+ int le) /* true for little-endian, false for big-endian */
{
- double x;
+ double x;
- x = _PyFloat_Unpack4((unsigned char *)p, le);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x);
+ x = _PyFloat_Unpack4((unsigned char *)p, le);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x);
}
static PyObject *
unpack_double(const char *p, /* start of 8-byte string */
- int le) /* true for little-endian, false for big-endian */
+ int le) /* true for little-endian, false for big-endian */
{
- double x;
+ double x;
- x = _PyFloat_Unpack8((unsigned char *)p, le);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x);
+ x = _PyFloat_Unpack8((unsigned char *)p, le);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x);
}
/* Helper to format the range error exceptions */
static int
_range_error(const formatdef *f, int is_unsigned)
{
- /* ulargest is the largest unsigned value with f->size bytes.
- * Note that the simpler:
- * ((size_t)1 << (f->size * 8)) - 1
- * doesn't work when f->size == sizeof(size_t) because C doesn't
- * define what happens when a left shift count is >= the number of
- * bits in the integer being shifted; e.g., on some boxes it doesn't
- * shift at all when they're equal.
- */
- const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
- assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
- if (is_unsigned)
- PyErr_Format(StructError,
- "'%c' format requires 0 <= number <= %zu",
- f->format,
- ulargest);
- else {
- const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
- PyErr_Format(StructError,
- "'%c' format requires %zd <= number <= %zd",
- f->format,
- ~ largest,
- largest);
- }
-
- return -1;
+ /* ulargest is the largest unsigned value with f->size bytes.
+ * Note that the simpler:
+ * ((size_t)1 << (f->size * 8)) - 1
+ * doesn't work when f->size == sizeof(size_t) because C doesn't
+ * define what happens when a left shift count is >= the number of
+ * bits in the integer being shifted; e.g., on some boxes it doesn't
+ * shift at all when they're equal.
+ */
+ const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
+ assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
+ if (is_unsigned)
+ PyErr_Format(StructError,
+ "'%c' format requires 0 <= number <= %zu",
+ f->format,
+ ulargest);
+ else {
+ const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
+ PyErr_Format(StructError,
+ "'%c' format requires %zd <= number <= %zd",
+ f->format,
+ ~ largest,
+ largest);
+ }
+
+ return -1;
}
@@ -299,75 +299,75 @@ _range_error(const formatdef *f, int is_unsigned)
static PyObject *
nu_char(const char *p, const formatdef *f)
{
- return PyBytes_FromStringAndSize(p, 1);
+ return PyBytes_FromStringAndSize(p, 1);
}
static PyObject *
nu_byte(const char *p, const formatdef *f)
{
- return PyLong_FromLong((long) *(signed char *)p);
+ return PyLong_FromLong((long) *(signed char *)p);
}
static PyObject *
nu_ubyte(const char *p, const formatdef *f)
{
- return PyLong_FromLong((long) *(unsigned char *)p);
+ return PyLong_FromLong((long) *(unsigned char *)p);
}
static PyObject *
nu_short(const char *p, const formatdef *f)
{
- short x;
- memcpy((char *)&x, p, sizeof x);
- return PyLong_FromLong((long)x);
+ short x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyLong_FromLong((long)x);
}
static PyObject *
nu_ushort(const char *p, const formatdef *f)
{
- unsigned short x;
- memcpy((char *)&x, p, sizeof x);
- return PyLong_FromLong((long)x);
+ unsigned short x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyLong_FromLong((long)x);
}
static PyObject *
nu_int(const char *p, const formatdef *f)
{
- int x;
- memcpy((char *)&x, p, sizeof x);
- return PyLong_FromLong((long)x);
+ int x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyLong_FromLong((long)x);
}
static PyObject *
nu_uint(const char *p, const formatdef *f)
{
- unsigned int x;
- memcpy((char *)&x, p, sizeof x);
+ unsigned int x;
+ memcpy((char *)&x, p, sizeof x);
#if (SIZEOF_LONG > SIZEOF_INT)
- return PyLong_FromLong((long)x);
+ return PyLong_FromLong((long)x);
#else
- if (x <= ((unsigned int)LONG_MAX))
- return PyLong_FromLong((long)x);
- return PyLong_FromUnsignedLong((unsigned long)x);
+ if (x <= ((unsigned int)LONG_MAX))
+ return PyLong_FromLong((long)x);
+ return PyLong_FromUnsignedLong((unsigned long)x);
#endif
}
static PyObject *
nu_long(const char *p, const formatdef *f)
{
- long x;
- memcpy((char *)&x, p, sizeof x);
- return PyLong_FromLong(x);
+ long x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyLong_FromLong(x);
}
static PyObject *
nu_ulong(const char *p, const formatdef *f)
{
- unsigned long x;
- memcpy((char *)&x, p, sizeof x);
- if (x <= LONG_MAX)
- return PyLong_FromLong((long)x);
- return PyLong_FromUnsignedLong(x);
+ unsigned long x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x <= LONG_MAX)
+ return PyLong_FromLong((long)x);
+ return PyLong_FromUnsignedLong(x);
}
/* Native mode doesn't support q or Q unless the platform C supports
@@ -378,21 +378,21 @@ nu_ulong(const char *p, const formatdef *f)
static PyObject *
nu_longlong(const char *p, const formatdef *f)
{
- PY_LONG_LONG x;
- memcpy((char *)&x, p, sizeof x);
- if (x >= LONG_MIN && x <= LONG_MAX)
- return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
- return PyLong_FromLongLong(x);
+ PY_LONG_LONG x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x >= LONG_MIN && x <= LONG_MAX)
+ return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
+ return PyLong_FromLongLong(x);
}
static PyObject *
nu_ulonglong(const char *p, const formatdef *f)
{
- unsigned PY_LONG_LONG x;
- memcpy((char *)&x, p, sizeof x);
- if (x <= LONG_MAX)
- return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
- return PyLong_FromUnsignedLongLong(x);
+ unsigned PY_LONG_LONG x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x <= LONG_MAX)
+ return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
}
#endif
@@ -400,168 +400,168 @@ nu_ulonglong(const char *p, const formatdef *f)
static PyObject *
nu_bool(const char *p, const formatdef *f)
{
- BOOL_TYPE x;
- memcpy((char *)&x, p, sizeof x);
- return PyBool_FromLong(x != 0);
+ BOOL_TYPE x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyBool_FromLong(x != 0);
}
static PyObject *
nu_float(const char *p, const formatdef *f)
{
- float x;
- memcpy((char *)&x, p, sizeof x);
- return PyFloat_FromDouble((double)x);
+ float x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyFloat_FromDouble((double)x);
}
static PyObject *
nu_double(const char *p, const formatdef *f)
{
- double x;
- memcpy((char *)&x, p, sizeof x);
- return PyFloat_FromDouble(x);
+ double x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyFloat_FromDouble(x);
}
static PyObject *
nu_void_p(const char *p, const formatdef *f)
{
- void *x;
- memcpy((char *)&x, p, sizeof x);
- return PyLong_FromVoidPtr(x);
+ void *x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyLong_FromVoidPtr(x);
}
static int
np_byte(char *p, PyObject *v, const formatdef *f)
{
- long x;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < -128 || x > 127){
- PyErr_SetString(StructError,
- "byte format requires -128 <= number <= 127");
- return -1;
- }
- *p = (char)x;
- return 0;
+ long x;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < -128 || x > 127){
+ PyErr_SetString(StructError,
+ "byte format requires -128 <= number <= 127");
+ return -1;
+ }
+ *p = (char)x;
+ return 0;
}
static int
np_ubyte(char *p, PyObject *v, const formatdef *f)
{
- long x;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < 0 || x > 255){
- PyErr_SetString(StructError,
- "ubyte format requires 0 <= number <= 255");
- return -1;
- }
- *p = (char)x;
- return 0;
+ long x;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < 0 || x > 255){
+ PyErr_SetString(StructError,
+ "ubyte format requires 0 <= number <= 255");
+ return -1;
+ }
+ *p = (char)x;
+ return 0;
}
static int
np_char(char *p, PyObject *v, const formatdef *f)
{
- if (PyUnicode_Check(v)) {
- v = _PyUnicode_AsDefaultEncodedString(v, NULL);
- if (v == NULL)
- return -1;
- }
- if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
- PyErr_SetString(StructError,
- "char format requires bytes or string of length 1");
- return -1;
- }
- *p = *PyBytes_AsString(v);
- return 0;
+ if (PyUnicode_Check(v)) {
+ v = _PyUnicode_AsDefaultEncodedString(v, NULL);
+ if (v == NULL)
+ return -1;
+ }
+ if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
+ PyErr_SetString(StructError,
+ "char format requires bytes or string of length 1");
+ return -1;
+ }
+ *p = *PyBytes_AsString(v);
+ return 0;
}
static int
np_short(char *p, PyObject *v, const formatdef *f)
{
- long x;
- short y;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < SHRT_MIN || x > SHRT_MAX){
- PyErr_SetString(StructError,
- "short format requires " STRINGIFY(SHRT_MIN)
- " <= number <= " STRINGIFY(SHRT_MAX));
- return -1;
- }
- y = (short)x;
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ long x;
+ short y;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < SHRT_MIN || x > SHRT_MAX){
+ PyErr_SetString(StructError,
+ "short format requires " STRINGIFY(SHRT_MIN)
+ " <= number <= " STRINGIFY(SHRT_MAX));
+ return -1;
+ }
+ y = (short)x;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_ushort(char *p, PyObject *v, const formatdef *f)
{
- long x;
- unsigned short y;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < 0 || x > USHRT_MAX){
- PyErr_SetString(StructError,
- "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
- return -1;
- }
- y = (unsigned short)x;
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ long x;
+ unsigned short y;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < 0 || x > USHRT_MAX){
+ PyErr_SetString(StructError,
+ "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
+ return -1;
+ }
+ y = (unsigned short)x;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_int(char *p, PyObject *v, const formatdef *f)
{
- long x;
- int y;
- if (get_long(v, &x) < 0)
- return -1;
+ long x;
+ int y;
+ if (get_long(v, &x) < 0)
+ return -1;
#if (SIZEOF_LONG > SIZEOF_INT)
- if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
- RANGE_ERROR(x, f, 0, -1);
+ if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
+ RANGE_ERROR(x, f, 0, -1);
#endif
- y = (int)x;
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ y = (int)x;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_uint(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- unsigned int y;
- if (get_ulong(v, &x) < 0)
- return -1;
- y = (unsigned int)x;
+ unsigned long x;
+ unsigned int y;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ y = (unsigned int)x;
#if (SIZEOF_LONG > SIZEOF_INT)
- if (x > ((unsigned long)UINT_MAX))
- RANGE_ERROR(y, f, 1, -1);
+ if (x > ((unsigned long)UINT_MAX))
+ RANGE_ERROR(y, f, 1, -1);
#endif
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_long(char *p, PyObject *v, const formatdef *f)
{
- long x;
- if (get_long(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ long x;
+ if (get_long(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static int
np_ulong(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- if (get_ulong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ unsigned long x;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -569,21 +569,21 @@ np_ulong(char *p, PyObject *v, const formatdef *f)
static int
np_longlong(char *p, PyObject *v, const formatdef *f)
{
- PY_LONG_LONG x;
- if (get_longlong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ PY_LONG_LONG x;
+ if (get_longlong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static int
np_ulonglong(char *p, PyObject *v, const formatdef *f)
{
- unsigned PY_LONG_LONG x;
- if (get_ulonglong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ unsigned PY_LONG_LONG x;
+ if (get_ulonglong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
#endif
@@ -591,77 +591,77 @@ np_ulonglong(char *p, PyObject *v, const formatdef *f)
static int
np_bool(char *p, PyObject *v, const formatdef *f)
{
- BOOL_TYPE y;
- y = PyObject_IsTrue(v);
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ BOOL_TYPE y;
+ y = PyObject_IsTrue(v);
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_float(char *p, PyObject *v, const formatdef *f)
{
- float x = (float)PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ float x = (float)PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static int
np_double(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- memcpy(p, (char *)&x, sizeof(double));
- return 0;
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ memcpy(p, (char *)&x, sizeof(double));
+ return 0;
}
static int
np_void_p(char *p, PyObject *v, const formatdef *f)
{
- void *x;
+ void *x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsVoidPtr(v);
- Py_DECREF(v);
- if (x == NULL && PyErr_Occurred())
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsVoidPtr(v);
+ Py_DECREF(v);
+ if (x == NULL && PyErr_Occurred())
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static formatdef native_table[] = {
- {'x', sizeof(char), 0, NULL},
- {'b', sizeof(char), 0, nu_byte, np_byte},
- {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
- {'c', sizeof(char), 0, nu_char, np_char},
- {'s', sizeof(char), 0, NULL},
- {'p', sizeof(char), 0, NULL},
- {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
- {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
- {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
- {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
- {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
- {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
+ {'x', sizeof(char), 0, NULL},
+ {'b', sizeof(char), 0, nu_byte, np_byte},
+ {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
+ {'c', sizeof(char), 0, nu_char, np_char},
+ {'s', sizeof(char), 0, NULL},
+ {'p', sizeof(char), 0, NULL},
+ {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
+ {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
+ {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
+ {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
+ {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
+ {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
#ifdef HAVE_LONG_LONG
- {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
- {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
+ {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
+ {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
#endif
- {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
- {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
- {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
- {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
- {0}
+ {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
+ {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
+ {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
+ {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
+ {0}
};
/* Big-endian routines. *****************************************************/
@@ -669,53 +669,53 @@ static formatdef native_table[] = {
static PyObject *
bu_int(const char *p, const formatdef *f)
{
- long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG > f->size)
- x |= -(x & (1L << ((8 * f->size) - 1)));
- return PyLong_FromLong(x);
+ long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG > f->size)
+ x |= -(x & (1L << ((8 * f->size) - 1)));
+ return PyLong_FromLong(x);
}
static PyObject *
bu_uint(const char *p, const formatdef *f)
{
- unsigned long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- if (x <= LONG_MAX)
- return PyLong_FromLong((long)x);
- return PyLong_FromUnsignedLong(x);
+ unsigned long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ if (x <= LONG_MAX)
+ return PyLong_FromLong((long)x);
+ return PyLong_FromUnsignedLong(x);
}
static PyObject *
bu_longlong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG_LONG > f->size)
- x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
- if (x >= LONG_MIN && x <= LONG_MAX)
- return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
- return PyLong_FromLongLong(x);
+ PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG_LONG > f->size)
+ x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
+ if (x >= LONG_MIN && x <= LONG_MAX)
+ return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
+ return PyLong_FromLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 0, /* little-endian */
- 1 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 0, /* little-endian */
+ 1 /* signed */);
#endif
}
@@ -723,171 +723,171 @@ static PyObject *
bu_ulonglong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- unsigned PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- if (x <= LONG_MAX)
- return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
- return PyLong_FromUnsignedLongLong(x);
+ unsigned PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ if (x <= LONG_MAX)
+ return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 0, /* little-endian */
- 0 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 0, /* little-endian */
+ 0 /* signed */);
#endif
}
static PyObject *
bu_float(const char *p, const formatdef *f)
{
- return unpack_float(p, 0);
+ return unpack_float(p, 0);
}
static PyObject *
bu_double(const char *p, const formatdef *f)
{
- return unpack_double(p, 0);
+ return unpack_double(p, 0);
}
static PyObject *
bu_bool(const char *p, const formatdef *f)
{
- char x;
- memcpy((char *)&x, p, sizeof x);
- return PyBool_FromLong(x != 0);
+ char x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyBool_FromLong(x != 0);
}
static int
bp_int(char *p, PyObject *v, const formatdef *f)
{
- long x;
- Py_ssize_t i;
- if (get_long(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- if ((i == 2) && (x < -32768 || x > 32767))
- RANGE_ERROR(x, f, 0, 0xffffL);
+ long x;
+ Py_ssize_t i;
+ if (get_long(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ if ((i == 2) && (x < -32768 || x > 32767))
+ RANGE_ERROR(x, f, 0, 0xffffL);
#if (SIZEOF_LONG != 4)
- else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
- RANGE_ERROR(x, f, 0, 0xffffffffL);
+ else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
+ RANGE_ERROR(x, f, 0, 0xffffffffL);
#endif
- }
- do {
- p[--i] = (char)x;
- x >>= 8;
- } while (i > 0);
- return 0;
+ }
+ do {
+ p[--i] = (char)x;
+ x >>= 8;
+ } while (i > 0);
+ return 0;
}
static int
bp_uint(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- Py_ssize_t i;
- if (get_ulong(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- unsigned long maxint = 1;
- maxint <<= (unsigned long)(i * 8);
- if (x >= maxint)
- RANGE_ERROR(x, f, 1, maxint - 1);
- }
- do {
- p[--i] = (char)x;
- x >>= 8;
- } while (i > 0);
- return 0;
+ unsigned long x;
+ Py_ssize_t i;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ unsigned long maxint = 1;
+ maxint <<= (unsigned long)(i * 8);
+ if (x >= maxint)
+ RANGE_ERROR(x, f, 1, maxint - 1);
+ }
+ do {
+ p[--i] = (char)x;
+ x >>= 8;
+ } while (i > 0);
+ return 0;
}
static int
bp_longlong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject *)v,
- (unsigned char *)p,
- 8,
- 0, /* little_endian */
- 1 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject *)v,
+ (unsigned char *)p,
+ 8,
+ 0, /* little_endian */
+ 1 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
bp_ulonglong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject *)v,
- (unsigned char *)p,
- 8,
- 0, /* little_endian */
- 0 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject *)v,
+ (unsigned char *)p,
+ 8,
+ 0, /* little_endian */
+ 0 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
bp_float(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack4(x, (unsigned char *)p, 0);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack4(x, (unsigned char *)p, 0);
}
static int
bp_double(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack8(x, (unsigned char *)p, 0);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack8(x, (unsigned char *)p, 0);
}
static int
bp_bool(char *p, PyObject *v, const formatdef *f)
{
- char y;
- y = PyObject_IsTrue(v);
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ char y;
+ y = PyObject_IsTrue(v);
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static formatdef bigendian_table[] = {
- {'x', 1, 0, NULL},
- {'b', 1, 0, nu_byte, np_byte},
- {'B', 1, 0, nu_ubyte, np_ubyte},
- {'c', 1, 0, nu_char, np_char},
- {'s', 1, 0, NULL},
- {'p', 1, 0, NULL},
- {'h', 2, 0, bu_int, bp_int},
- {'H', 2, 0, bu_uint, bp_uint},
- {'i', 4, 0, bu_int, bp_int},
- {'I', 4, 0, bu_uint, bp_uint},
- {'l', 4, 0, bu_int, bp_int},
- {'L', 4, 0, bu_uint, bp_uint},
- {'q', 8, 0, bu_longlong, bp_longlong},
- {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
- {'?', 1, 0, bu_bool, bp_bool},
- {'f', 4, 0, bu_float, bp_float},
- {'d', 8, 0, bu_double, bp_double},
- {0}
+ {'x', 1, 0, NULL},
+ {'b', 1, 0, nu_byte, np_byte},
+ {'B', 1, 0, nu_ubyte, np_ubyte},
+ {'c', 1, 0, nu_char, np_char},
+ {'s', 1, 0, NULL},
+ {'p', 1, 0, NULL},
+ {'h', 2, 0, bu_int, bp_int},
+ {'H', 2, 0, bu_uint, bp_uint},
+ {'i', 4, 0, bu_int, bp_int},
+ {'I', 4, 0, bu_uint, bp_uint},
+ {'l', 4, 0, bu_int, bp_int},
+ {'L', 4, 0, bu_uint, bp_uint},
+ {'q', 8, 0, bu_longlong, bp_longlong},
+ {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
+ {'?', 1, 0, bu_bool, bp_bool},
+ {'f', 4, 0, bu_float, bp_float},
+ {'d', 8, 0, bu_double, bp_double},
+ {0}
};
/* Little-endian routines. *****************************************************/
@@ -895,53 +895,53 @@ static formatdef bigendian_table[] = {
static PyObject *
lu_int(const char *p, const formatdef *f)
{
- long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG > f->size)
- x |= -(x & (1L << ((8 * f->size) - 1)));
- return PyLong_FromLong(x);
+ long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG > f->size)
+ x |= -(x & (1L << ((8 * f->size) - 1)));
+ return PyLong_FromLong(x);
}
static PyObject *
lu_uint(const char *p, const formatdef *f)
{
- unsigned long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- if (x <= LONG_MAX)
- return PyLong_FromLong((long)x);
- return PyLong_FromUnsignedLong((long)x);
+ unsigned long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ if (x <= LONG_MAX)
+ return PyLong_FromLong((long)x);
+ return PyLong_FromUnsignedLong((long)x);
}
static PyObject *
lu_longlong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG_LONG > f->size)
- x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
- if (x >= LONG_MIN && x <= LONG_MAX)
- return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
- return PyLong_FromLongLong(x);
+ PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG_LONG > f->size)
+ x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
+ if (x >= LONG_MIN && x <= LONG_MAX)
+ return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
+ return PyLong_FromLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 1, /* little-endian */
- 1 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 1, /* little-endian */
+ 1 /* signed */);
#endif
}
@@ -949,182 +949,182 @@ static PyObject *
lu_ulonglong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- unsigned PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- if (x <= LONG_MAX)
- return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
- return PyLong_FromUnsignedLongLong(x);
+ unsigned PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ if (x <= LONG_MAX)
+ return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 1, /* little-endian */
- 0 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 1, /* little-endian */
+ 0 /* signed */);
#endif
}
static PyObject *
lu_float(const char *p, const formatdef *f)
{
- return unpack_float(p, 1);
+ return unpack_float(p, 1);
}
static PyObject *
lu_double(const char *p, const formatdef *f)
{
- return unpack_double(p, 1);
+ return unpack_double(p, 1);
}
static int
lp_int(char *p, PyObject *v, const formatdef *f)
{
- long x;
- Py_ssize_t i;
- if (get_long(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- if ((i == 2) && (x < -32768 || x > 32767))
- RANGE_ERROR(x, f, 0, 0xffffL);
+ long x;
+ Py_ssize_t i;
+ if (get_long(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ if ((i == 2) && (x < -32768 || x > 32767))
+ RANGE_ERROR(x, f, 0, 0xffffL);
#if (SIZEOF_LONG != 4)
- else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
- RANGE_ERROR(x, f, 0, 0xffffffffL);
+ else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
+ RANGE_ERROR(x, f, 0, 0xffffffffL);
#endif
- }
- do {
- *p++ = (char)x;
- x >>= 8;
- } while (--i > 0);
- return 0;
+ }
+ do {
+ *p++ = (char)x;
+ x >>= 8;
+ } while (--i > 0);
+ return 0;
}
static int
lp_uint(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- Py_ssize_t i;
- if (get_ulong(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- unsigned long maxint = 1;
- maxint <<= (unsigned long)(i * 8);
- if (x >= maxint)
- RANGE_ERROR(x, f, 1, maxint - 1);
- }
- do {
- *p++ = (char)x;
- x >>= 8;
- } while (--i > 0);
- return 0;
+ unsigned long x;
+ Py_ssize_t i;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ unsigned long maxint = 1;
+ maxint <<= (unsigned long)(i * 8);
+ if (x >= maxint)
+ RANGE_ERROR(x, f, 1, maxint - 1);
+ }
+ do {
+ *p++ = (char)x;
+ x >>= 8;
+ } while (--i > 0);
+ return 0;
}
static int
lp_longlong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject*)v,
- (unsigned char *)p,
- 8,
- 1, /* little_endian */
- 1 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject*)v,
+ (unsigned char *)p,
+ 8,
+ 1, /* little_endian */
+ 1 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
lp_ulonglong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject*)v,
- (unsigned char *)p,
- 8,
- 1, /* little_endian */
- 0 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject*)v,
+ (unsigned char *)p,
+ 8,
+ 1, /* little_endian */
+ 0 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
lp_float(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack4(x, (unsigned char *)p, 1);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack4(x, (unsigned char *)p, 1);
}
static int
lp_double(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack8(x, (unsigned char *)p, 1);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack8(x, (unsigned char *)p, 1);
}
static formatdef lilendian_table[] = {
- {'x', 1, 0, NULL},
- {'b', 1, 0, nu_byte, np_byte},
- {'B', 1, 0, nu_ubyte, np_ubyte},
- {'c', 1, 0, nu_char, np_char},
- {'s', 1, 0, NULL},
- {'p', 1, 0, NULL},
- {'h', 2, 0, lu_int, lp_int},
- {'H', 2, 0, lu_uint, lp_uint},
- {'i', 4, 0, lu_int, lp_int},
- {'I', 4, 0, lu_uint, lp_uint},
- {'l', 4, 0, lu_int, lp_int},
- {'L', 4, 0, lu_uint, lp_uint},
- {'q', 8, 0, lu_longlong, lp_longlong},
- {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
- {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
- but potentially different from native rep -- reuse bx_bool funcs. */
- {'f', 4, 0, lu_float, lp_float},
- {'d', 8, 0, lu_double, lp_double},
- {0}
+ {'x', 1, 0, NULL},
+ {'b', 1, 0, nu_byte, np_byte},
+ {'B', 1, 0, nu_ubyte, np_ubyte},
+ {'c', 1, 0, nu_char, np_char},
+ {'s', 1, 0, NULL},
+ {'p', 1, 0, NULL},
+ {'h', 2, 0, lu_int, lp_int},
+ {'H', 2, 0, lu_uint, lp_uint},
+ {'i', 4, 0, lu_int, lp_int},
+ {'I', 4, 0, lu_uint, lp_uint},
+ {'l', 4, 0, lu_int, lp_int},
+ {'L', 4, 0, lu_uint, lp_uint},
+ {'q', 8, 0, lu_longlong, lp_longlong},
+ {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
+ {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
+ but potentially different from native rep -- reuse bx_bool funcs. */
+ {'f', 4, 0, lu_float, lp_float},
+ {'d', 8, 0, lu_double, lp_double},
+ {0}
};
static const formatdef *
whichtable(char **pfmt)
{
- const char *fmt = (*pfmt)++; /* May be backed out of later */
- switch (*fmt) {
- case '<':
- return lilendian_table;
- case '>':
- case '!': /* Network byte order is big-endian */
- return bigendian_table;
- case '=': { /* Host byte order -- different from native in aligment! */
- int n = 1;
- char *p = (char *) &n;
- if (*p == 1)
- return lilendian_table;
- else
- return bigendian_table;
- }
- default:
- --*pfmt; /* Back out of pointer increment */
- /* Fall through */
- case '@':
- return native_table;
- }
+ const char *fmt = (*pfmt)++; /* May be backed out of later */
+ switch (*fmt) {
+ case '<':
+ return lilendian_table;
+ case '>':
+ case '!': /* Network byte order is big-endian */
+ return bigendian_table;
+ case '=': { /* Host byte order -- different from native in aligment! */
+ int n = 1;
+ char *p = (char *) &n;
+ if (*p == 1)
+ return lilendian_table;
+ else
+ return bigendian_table;
+ }
+ default:
+ --*pfmt; /* Back out of pointer increment */
+ /* Fall through */
+ case '@':
+ return native_table;
+ }
}
@@ -1133,13 +1133,13 @@ whichtable(char **pfmt)
static const formatdef *
getentry(int c, const formatdef *f)
{
- for (; f->format != '\0'; f++) {
- if (f->format == c) {
- return f;
- }
- }
- PyErr_SetString(StructError, "bad char in struct format");
- return NULL;
+ for (; f->format != '\0'; f++) {
+ if (f->format == c) {
+ return f;
+ }
+ }
+ PyErr_SetString(StructError, "bad char in struct format");
+ return NULL;
}
@@ -1148,14 +1148,14 @@ getentry(int c, const formatdef *f)
static int
align(Py_ssize_t size, char c, const formatdef *e)
{
- if (e->format == c) {
- if (e->alignment) {
- size = ((size + e->alignment - 1)
- / e->alignment)
- * e->alignment;
- }
- }
- return size;
+ if (e->format == c) {
+ if (e->alignment) {
+ size = ((size + e->alignment - 1)
+ / e->alignment)
+ * e->alignment;
+ }
+ }
+ return size;
}
@@ -1164,224 +1164,224 @@ align(Py_ssize_t size, char c, const formatdef *e)
static int
prepare_s(PyStructObject *self)
{
- const formatdef *f;
- const formatdef *e;
- formatcode *codes;
-
- const char *s;
- const char *fmt;
- char c;
- Py_ssize_t size, len, num, itemsize, x;
-
- fmt = PyBytes_AS_STRING(self->s_format);
-
- f = whichtable((char **)&fmt);
-
- s = fmt;
- size = 0;
- len = 0;
- while ((c = *s++) != '\0') {
- if (isspace(Py_CHARMASK(c)))
- continue;
- if ('0' <= c && c <= '9') {
- num = c - '0';
- while ('0' <= (c = *s++) && c <= '9') {
- x = num*10 + (c - '0');
- if (x/10 != num) {
- PyErr_SetString(
- StructError,
- "overflow in item count");
- return -1;
- }
- num = x;
- }
- if (c == '\0')
- break;
- }
- else
- num = 1;
-
- e = getentry(c, f);
- if (e == NULL)
- return -1;
-
- switch (c) {
- case 's': /* fall through */
- case 'p': len++; break;
- case 'x': break;
- default: len += num; break;
- }
-
- itemsize = e->size;
- size = align(size, c, e);
- x = num * itemsize;
- size += x;
- if (x/itemsize != num || size < 0) {
- PyErr_SetString(StructError,
- "total struct size too long");
- return -1;
- }
- }
-
- /* check for overflow */
- if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
- PyErr_NoMemory();
- return -1;
- }
-
- self->s_size = size;
- self->s_len = len;
- codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
- if (codes == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- self->s_codes = codes;
-
- s = fmt;
- size = 0;
- while ((c = *s++) != '\0') {
- if (isspace(Py_CHARMASK(c)))
- continue;
- if ('0' <= c && c <= '9') {
- num = c - '0';
- while ('0' <= (c = *s++) && c <= '9')
- num = num*10 + (c - '0');
- if (c == '\0')
- break;
- }
- else
- num = 1;
-
- e = getentry(c, f);
-
- size = align(size, c, e);
- if (c == 's' || c == 'p') {
- codes->offset = size;
- codes->size = num;
- codes->fmtdef = e;
- codes++;
- size += num;
- } else if (c == 'x') {
- size += num;
- } else {
- while (--num >= 0) {
- codes->offset = size;
- codes->size = e->size;
- codes->fmtdef = e;
- codes++;
- size += e->size;
- }
- }
- }
- codes->fmtdef = NULL;
- codes->offset = size;
- codes->size = 0;
-
- return 0;
+ const formatdef *f;
+ const formatdef *e;
+ formatcode *codes;
+
+ const char *s;
+ const char *fmt;
+ char c;
+ Py_ssize_t size, len, num, itemsize, x;
+
+ fmt = PyBytes_AS_STRING(self->s_format);
+
+ f = whichtable((char **)&fmt);
+
+ s = fmt;
+ size = 0;
+ len = 0;
+ while ((c = *s++) != '\0') {
+ if (isspace(Py_CHARMASK(c)))
+ continue;
+ if ('0' <= c && c <= '9') {
+ num = c - '0';
+ while ('0' <= (c = *s++) && c <= '9') {
+ x = num*10 + (c - '0');
+ if (x/10 != num) {
+ PyErr_SetString(
+ StructError,
+ "overflow in item count");
+ return -1;
+ }
+ num = x;
+ }
+ if (c == '\0')
+ break;
+ }
+ else
+ num = 1;
+
+ e = getentry(c, f);
+ if (e == NULL)
+ return -1;
+
+ switch (c) {
+ case 's': /* fall through */
+ case 'p': len++; break;
+ case 'x': break;
+ default: len += num; break;
+ }
+
+ itemsize = e->size;
+ size = align(size, c, e);
+ x = num * itemsize;
+ size += x;
+ if (x/itemsize != num || size < 0) {
+ PyErr_SetString(StructError,
+ "total struct size too long");
+ return -1;
+ }
+ }
+
+ /* check for overflow */
+ if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ self->s_size = size;
+ self->s_len = len;
+ codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
+ if (codes == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->s_codes = codes;
+
+ s = fmt;
+ size = 0;
+ while ((c = *s++) != '\0') {
+ if (isspace(Py_CHARMASK(c)))
+ continue;
+ if ('0' <= c && c <= '9') {
+ num = c - '0';
+ while ('0' <= (c = *s++) && c <= '9')
+ num = num*10 + (c - '0');
+ if (c == '\0')
+ break;
+ }
+ else
+ num = 1;
+
+ e = getentry(c, f);
+
+ size = align(size, c, e);
+ if (c == 's' || c == 'p') {
+ codes->offset = size;
+ codes->size = num;
+ codes->fmtdef = e;
+ codes++;
+ size += num;
+ } else if (c == 'x') {
+ size += num;
+ } else {
+ while (--num >= 0) {
+ codes->offset = size;
+ codes->size = e->size;
+ codes->fmtdef = e;
+ codes++;
+ size += e->size;
+ }
+ }
+ }
+ codes->fmtdef = NULL;
+ codes->offset = size;
+ codes->size = 0;
+
+ return 0;
}
static PyObject *
s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *self;
+ PyObject *self;
- assert(type != NULL && type->tp_alloc != NULL);
+ assert(type != NULL && type->tp_alloc != NULL);
- self = type->tp_alloc(type, 0);
- if (self != NULL) {
- PyStructObject *s = (PyStructObject*)self;
- Py_INCREF(Py_None);
- s->s_format = Py_None;
- s->s_codes = NULL;
- s->s_size = -1;
- s->s_len = -1;
- }
- return self;
+ self = type->tp_alloc(type, 0);
+ if (self != NULL) {
+ PyStructObject *s = (PyStructObject*)self;
+ Py_INCREF(Py_None);
+ s->s_format = Py_None;
+ s->s_codes = NULL;
+ s->s_size = -1;
+ s->s_len = -1;
+ }
+ return self;
}
static int
s_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyStructObject *soself = (PyStructObject *)self;
- PyObject *o_format = NULL;
- int ret = 0;
- static char *kwlist[] = {"format", 0};
+ PyStructObject *soself = (PyStructObject *)self;
+ PyObject *o_format = NULL;
+ int ret = 0;
+ static char *kwlist[] = {"format", 0};
- assert(PyStruct_Check(self));
+ assert(PyStruct_Check(self));
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
- &o_format))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
+ &o_format))
+ return -1;
- if (PyUnicode_Check(o_format)) {
- o_format = PyUnicode_AsASCIIString(o_format);
- if (o_format == NULL)
- return -1;
- }
- /* XXX support buffer interface, too */
- else {
- Py_INCREF(o_format);
- }
+ if (PyUnicode_Check(o_format)) {
+ o_format = PyUnicode_AsASCIIString(o_format);
+ if (o_format == NULL)
+ return -1;
+ }
+ /* XXX support buffer interface, too */
+ else {
+ Py_INCREF(o_format);
+ }
- if (!PyBytes_Check(o_format)) {
- Py_DECREF(o_format);
- PyErr_Format(PyExc_TypeError,
- "Struct() argument 1 must be bytes, not %.200s",
- Py_TYPE(o_format)->tp_name);
- return -1;
- }
+ if (!PyBytes_Check(o_format)) {
+ Py_DECREF(o_format);
+ PyErr_Format(PyExc_TypeError,
+ "Struct() argument 1 must be bytes, not %.200s",
+ Py_TYPE(o_format)->tp_name);
+ return -1;
+ }
- Py_CLEAR(soself->s_format);
- soself->s_format = o_format;
+ Py_CLEAR(soself->s_format);
+ soself->s_format = o_format;
- ret = prepare_s(soself);
- return ret;
+ ret = prepare_s(soself);
+ return ret;
}
static void
s_dealloc(PyStructObject *s)
{
- if (s->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *)s);
- if (s->s_codes != NULL) {
- PyMem_FREE(s->s_codes);
- }
- Py_XDECREF(s->s_format);
- Py_TYPE(s)->tp_free((PyObject *)s);
+ if (s->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *)s);
+ if (s->s_codes != NULL) {
+ PyMem_FREE(s->s_codes);
+ }
+ Py_XDECREF(s->s_format);
+ Py_TYPE(s)->tp_free((PyObject *)s);
}
static PyObject *
s_unpack_internal(PyStructObject *soself, char *startfrom) {
- formatcode *code;
- Py_ssize_t i = 0;
- PyObject *result = PyTuple_New(soself->s_len);
- if (result == NULL)
- return NULL;
-
- for (code = soself->s_codes; code->fmtdef != NULL; code++) {
- PyObject *v;
- const formatdef *e = code->fmtdef;
- const char *res = startfrom + code->offset;
- if (e->format == 's') {
- v = PyBytes_FromStringAndSize(res, code->size);
- } else if (e->format == 'p') {
- Py_ssize_t n = *(unsigned char*)res;
- if (n >= code->size)
- n = code->size - 1;
- v = PyBytes_FromStringAndSize(res + 1, n);
- } else {
- v = e->unpack(res, e);
- }
- if (v == NULL)
- goto fail;
- PyTuple_SET_ITEM(result, i++, v);
- }
-
- return result;
+ formatcode *code;
+ Py_ssize_t i = 0;
+ PyObject *result = PyTuple_New(soself->s_len);
+ if (result == NULL)
+ return NULL;
+
+ for (code = soself->s_codes; code->fmtdef != NULL; code++) {
+ PyObject *v;
+ const formatdef *e = code->fmtdef;
+ const char *res = startfrom + code->offset;
+ if (e->format == 's') {
+ v = PyBytes_FromStringAndSize(res, code->size);
+ } else if (e->format == 'p') {
+ Py_ssize_t n = *(unsigned char*)res;
+ if (n >= code->size)
+ n = code->size - 1;
+ v = PyBytes_FromStringAndSize(res + 1, n);
+ } else {
+ v = e->unpack(res, e);
+ }
+ if (v == NULL)
+ goto fail;
+ PyTuple_SET_ITEM(result, i++, v);
+ }
+
+ return result;
fail:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
@@ -1395,24 +1395,24 @@ strings.");
static PyObject *
s_unpack(PyObject *self, PyObject *input)
{
- Py_buffer vbuf;
- PyObject *result;
- PyStructObject *soself = (PyStructObject *)self;
-
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
- return NULL;
- if (vbuf.len != soself->s_size) {
- PyErr_Format(StructError,
- "unpack requires a bytes argument of length %zd",
- soself->s_size);
- PyBuffer_Release(&vbuf);
- return NULL;
- }
- result = s_unpack_internal(soself, vbuf.buf);
- PyBuffer_Release(&vbuf);
- return result;
+ Py_buffer vbuf;
+ PyObject *result;
+ PyStructObject *soself = (PyStructObject *)self;
+
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
+ return NULL;
+ if (vbuf.len != soself->s_size) {
+ PyErr_Format(StructError,
+ "unpack requires a bytes argument of length %zd",
+ soself->s_size);
+ PyBuffer_Release(&vbuf);
+ return NULL;
+ }
+ result = s_unpack_internal(soself, vbuf.buf);
+ PyBuffer_Release(&vbuf);
+ return result;
}
PyDoc_STRVAR(s_unpack_from__doc__,
@@ -1426,35 +1426,35 @@ See struct.__doc__ for more on format strings.");
static PyObject *
s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"buffer", "offset", 0};
-
- PyObject *input;
- Py_ssize_t offset = 0;
- Py_buffer vbuf;
- PyObject *result;
- PyStructObject *soself = (PyStructObject *)self;
-
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds,
- "O|n:unpack_from", kwlist,
- &input, &offset))
- return NULL;
- if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
- return NULL;
- if (offset < 0)
- offset += vbuf.len;
- if (offset < 0 || vbuf.len - offset < soself->s_size) {
- PyErr_Format(StructError,
- "unpack_from requires a buffer of at least %zd bytes",
- soself->s_size);
- PyBuffer_Release(&vbuf);
- return NULL;
- }
- result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
- PyBuffer_Release(&vbuf);
- return result;
+ static char *kwlist[] = {"buffer", "offset", 0};
+
+ PyObject *input;
+ Py_ssize_t offset = 0;
+ Py_buffer vbuf;
+ PyObject *result;
+ PyStructObject *soself = (PyStructObject *)self;
+
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds,
+ "O|n:unpack_from", kwlist,
+ &input, &offset))
+ return NULL;
+ if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
+ return NULL;
+ if (offset < 0)
+ offset += vbuf.len;
+ if (offset < 0 || vbuf.len - offset < soself->s_size) {
+ PyErr_Format(StructError,
+ "unpack_from requires a buffer of at least %zd bytes",
+ soself->s_size);
+ PyBuffer_Release(&vbuf);
+ return NULL;
+ }
+ result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
+ PyBuffer_Release(&vbuf);
+ return result;
}
@@ -1471,85 +1471,85 @@ s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
static int
s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
{
- formatcode *code;
- /* XXX(nnorwitz): why does i need to be a local? can we use
- the offset parameter or do we need the wider width? */
- Py_ssize_t i;
-
- memset(buf, '\0', soself->s_size);
- i = offset;
- for (code = soself->s_codes; code->fmtdef != NULL; code++) {
- Py_ssize_t n;
- PyObject *v = PyTuple_GET_ITEM(args, i++);
- const formatdef *e = code->fmtdef;
- char *res = buf + code->offset;
- if (e->format == 's') {
- int isstring;
- void *p;
- if (PyUnicode_Check(v)) {
- v = _PyUnicode_AsDefaultEncodedString(v, NULL);
- if (v == NULL)
- return -1;
- }
- isstring = PyBytes_Check(v);
- if (!isstring && !PyByteArray_Check(v)) {
- PyErr_SetString(StructError,
- "argument for 's' must be a bytes or string");
- return -1;
- }
- if (isstring) {
- n = PyBytes_GET_SIZE(v);
- p = PyBytes_AS_STRING(v);
- }
- else {
- n = PyByteArray_GET_SIZE(v);
- p = PyByteArray_AS_STRING(v);
- }
- if (n > code->size)
- n = code->size;
- if (n > 0)
- memcpy(res, p, n);
- } else if (e->format == 'p') {
- int isstring;
- void *p;
- if (PyUnicode_Check(v)) {
- v = _PyUnicode_AsDefaultEncodedString(v, NULL);
- if (v == NULL)
- return -1;
- }
- isstring = PyBytes_Check(v);
- if (!isstring && !PyByteArray_Check(v)) {
- PyErr_SetString(StructError,
- "argument for 'p' must be a bytes or string");
- return -1;
- }
- if (isstring) {
- n = PyBytes_GET_SIZE(v);
- p = PyBytes_AS_STRING(v);
- }
- else {
- n = PyByteArray_GET_SIZE(v);
- p = PyByteArray_AS_STRING(v);
- }
- if (n > (code->size - 1))
- n = code->size - 1;
- if (n > 0)
- memcpy(res + 1, p, n);
- if (n > 255)
- n = 255;
- *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
- } else {
- if (e->pack(res, v, e) < 0) {
- if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_SetString(StructError,
- "long too large to convert to int");
- return -1;
- }
- }
- }
-
- /* Success */
- return 0;
+ formatcode *code;
+ /* XXX(nnorwitz): why does i need to be a local? can we use
+ the offset parameter or do we need the wider width? */
+ Py_ssize_t i;
+
+ memset(buf, '\0', soself->s_size);
+ i = offset;
+ for (code = soself->s_codes; code->fmtdef != NULL; code++) {
+ Py_ssize_t n;
+ PyObject *v = PyTuple_GET_ITEM(args, i++);
+ const formatdef *e = code->fmtdef;
+ char *res = buf + code->offset;
+ if (e->format == 's') {
+ int isstring;
+ void *p;
+ if (PyUnicode_Check(v)) {
+ v = _PyUnicode_AsDefaultEncodedString(v, NULL);
+ if (v == NULL)
+ return -1;
+ }
+ isstring = PyBytes_Check(v);
+ if (!isstring && !PyByteArray_Check(v)) {
+ PyErr_SetString(StructError,
+ "argument for 's' must be a bytes or string");
+ return -1;
+ }
+ if (isstring) {
+ n = PyBytes_GET_SIZE(v);
+ p = PyBytes_AS_STRING(v);
+ }
+ else {
+ n = PyByteArray_GET_SIZE(v);
+ p = PyByteArray_AS_STRING(v);
+ }
+ if (n > code->size)
+ n = code->size;
+ if (n > 0)
+ memcpy(res, p, n);
+ } else if (e->format == 'p') {
+ int isstring;
+ void *p;
+ if (PyUnicode_Check(v)) {
+ v = _PyUnicode_AsDefaultEncodedString(v, NULL);
+ if (v == NULL)
+ return -1;
+ }
+ isstring = PyBytes_Check(v);
+ if (!isstring && !PyByteArray_Check(v)) {
+ PyErr_SetString(StructError,
+ "argument for 'p' must be a bytes or string");
+ return -1;
+ }
+ if (isstring) {
+ n = PyBytes_GET_SIZE(v);
+ p = PyBytes_AS_STRING(v);
+ }
+ else {
+ n = PyByteArray_GET_SIZE(v);
+ p = PyByteArray_AS_STRING(v);
+ }
+ if (n > (code->size - 1))
+ n = code->size - 1;
+ if (n > 0)
+ memcpy(res + 1, p, n);
+ if (n > 255)
+ n = 255;
+ *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
+ } else {
+ if (e->pack(res, v, e) < 0) {
+ if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_SetString(StructError,
+ "long too large to convert to int");
+ return -1;
+ }
+ }
+ }
+
+ /* Success */
+ return 0;
}
@@ -1562,32 +1562,32 @@ Struct's format. See struct.__doc__ for more on format strings.");
static PyObject *
s_pack(PyObject *self, PyObject *args)
{
- PyStructObject *soself;
- PyObject *result;
+ PyStructObject *soself;
+ PyObject *result;
- /* Validate arguments. */
- soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (PyTuple_GET_SIZE(args) != soself->s_len)
- {
- PyErr_Format(StructError,
- "pack requires exactly %zd arguments", soself->s_len);
- return NULL;
- }
+ /* Validate arguments. */
+ soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (PyTuple_GET_SIZE(args) != soself->s_len)
+ {
+ PyErr_Format(StructError,
+ "pack requires exactly %zd arguments", soself->s_len);
+ return NULL;
+ }
- /* Allocate a new string */
- result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
- if (result == NULL)
- return NULL;
+ /* Allocate a new string */
+ result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
+ if (result == NULL)
+ return NULL;
- /* Call the guts */
- if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
- Py_DECREF(result);
- return NULL;
- }
+ /* Call the guts */
+ if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
+ Py_DECREF(result);
+ return NULL;
+ }
- return result;
+ return result;
}
PyDoc_STRVAR(s_pack_into__doc__,
@@ -1601,59 +1601,59 @@ more on format strings.");
static PyObject *
s_pack_into(PyObject *self, PyObject *args)
{
- PyStructObject *soself;
- char *buffer;
- Py_ssize_t buffer_len, offset;
-
- /* Validate arguments. +1 is for the first arg as buffer. */
- soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
- {
- PyErr_Format(StructError,
- "pack_into requires exactly %zd arguments",
- (soself->s_len + 2));
- return NULL;
- }
-
- /* Extract a writable memory buffer from the first argument */
- if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
- (void**)&buffer, &buffer_len) == -1 ) {
- return NULL;
- }
- assert( buffer_len >= 0 );
-
- /* Extract the offset from the first argument */
- offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
-
- /* Support negative offsets. */
- if (offset < 0)
- offset += buffer_len;
-
- /* Check boundaries */
- if (offset < 0 || (buffer_len - offset) < soself->s_size) {
- PyErr_Format(StructError,
- "pack_into requires a buffer of at least %zd bytes",
- soself->s_size);
- return NULL;
- }
-
- /* Call the guts */
- if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
- return NULL;
- }
-
- Py_RETURN_NONE;
+ PyStructObject *soself;
+ char *buffer;
+ Py_ssize_t buffer_len, offset;
+
+ /* Validate arguments. +1 is for the first arg as buffer. */
+ soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
+ {
+ PyErr_Format(StructError,
+ "pack_into requires exactly %zd arguments",
+ (soself->s_len + 2));
+ return NULL;
+ }
+
+ /* Extract a writable memory buffer from the first argument */
+ if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
+ (void**)&buffer, &buffer_len) == -1 ) {
+ return NULL;
+ }
+ assert( buffer_len >= 0 );
+
+ /* Extract the offset from the first argument */
+ offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+
+ /* Support negative offsets. */
+ if (offset < 0)
+ offset += buffer_len;
+
+ /* Check boundaries */
+ if (offset < 0 || (buffer_len - offset) < soself->s_size) {
+ PyErr_Format(StructError,
+ "pack_into requires a buffer of at least %zd bytes",
+ soself->s_size);
+ return NULL;
+ }
+
+ /* Call the guts */
+ if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
static PyObject *
s_get_format(PyStructObject *self, void *unused)
{
- Py_INCREF(self->s_format);
- return self->s_format;
+ Py_INCREF(self->s_format);
+ return self->s_format;
}
static PyObject *
@@ -1665,12 +1665,12 @@ s_get_size(PyStructObject *self, void *unused)
/* List of functions */
static struct PyMethodDef s_methods[] = {
- {"pack", s_pack, METH_VARARGS, s_pack__doc__},
- {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
- {"unpack", s_unpack, METH_O, s_unpack__doc__},
- {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
- s_unpack_from__doc__},
- {NULL, NULL} /* sentinel */
+ {"pack", s_pack, METH_VARARGS, s_pack__doc__},
+ {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
+ {"unpack", s_unpack, METH_O, s_unpack__doc__},
+ {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
+ s_unpack_from__doc__},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(s__doc__, "Compiled struct object");
@@ -1678,52 +1678,52 @@ PyDoc_STRVAR(s__doc__, "Compiled struct object");
#define OFF(x) offsetof(PyStructObject, x)
static PyGetSetDef s_getsetlist[] = {
- {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
- {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
- {NULL} /* sentinel */
+ {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
+ {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
+ {NULL} /* sentinel */
};
static
PyTypeObject PyStructType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Struct",
- sizeof(PyStructObject),
- 0,
- (destructor)s_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- s__doc__, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- s_methods, /* tp_methods */
- NULL, /* tp_members */
- s_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- s_init, /* tp_init */
- PyType_GenericAlloc,/* tp_alloc */
- s_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "Struct",
+ sizeof(PyStructObject),
+ 0,
+ (destructor)s_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ s__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ s_methods, /* tp_methods */
+ NULL, /* tp_members */
+ s_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ s_init, /* tp_init */
+ PyType_GenericAlloc,/* tp_alloc */
+ s_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -1735,29 +1735,29 @@ static PyObject *cache = NULL;
static PyObject *
cache_struct(PyObject *fmt)
{
- PyObject * s_object;
+ PyObject * s_object;
- if (cache == NULL) {
- cache = PyDict_New();
- if (cache == NULL)
- return NULL;
- }
+ if (cache == NULL) {
+ cache = PyDict_New();
+ if (cache == NULL)
+ return NULL;
+ }
- s_object = PyDict_GetItem(cache, fmt);
- if (s_object != NULL) {
- Py_INCREF(s_object);
- return s_object;
- }
+ s_object = PyDict_GetItem(cache, fmt);
+ if (s_object != NULL) {
+ Py_INCREF(s_object);
+ return s_object;
+ }
- s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
- if (s_object != NULL) {
- if (PyDict_Size(cache) >= MAXCACHE)
- PyDict_Clear(cache);
- /* Attempt to cache the result */
- if (PyDict_SetItem(cache, fmt, s_object) == -1)
- PyErr_Clear();
- }
- return s_object;
+ s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
+ if (s_object != NULL) {
+ if (PyDict_Size(cache) >= MAXCACHE)
+ PyDict_Clear(cache);
+ /* Attempt to cache the result */
+ if (PyDict_SetItem(cache, fmt, s_object) == -1)
+ PyErr_Clear();
+ }
+ return s_object;
}
PyDoc_STRVAR(clearcache_doc,
@@ -1766,8 +1766,8 @@ PyDoc_STRVAR(clearcache_doc,
static PyObject *
clearcache(PyObject *self)
{
- Py_CLEAR(cache);
- Py_RETURN_NONE;
+ Py_CLEAR(cache);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(calcsize_doc,
@@ -1776,13 +1776,13 @@ PyDoc_STRVAR(calcsize_doc,
static PyObject *
calcsize(PyObject *self, PyObject *fmt)
{
- Py_ssize_t n;
- PyObject *s_object = cache_struct(fmt);
- if (s_object == NULL)
- return NULL;
- n = ((PyStructObject *)s_object)->s_size;
- Py_DECREF(s_object);
- return PyLong_FromSsize_t(n);
+ Py_ssize_t n;
+ PyObject *s_object = cache_struct(fmt);
+ if (s_object == NULL)
+ return NULL;
+ n = ((PyStructObject *)s_object)->s_size;
+ Py_DECREF(s_object);
+ return PyLong_FromSsize_t(n);
}
PyDoc_STRVAR(pack_doc,
@@ -1791,27 +1791,27 @@ PyDoc_STRVAR(pack_doc,
static PyObject *
pack(PyObject *self, PyObject *args)
{
- PyObject *s_object, *fmt, *newargs, *result;
- Py_ssize_t n = PyTuple_GET_SIZE(args);
-
- if (n == 0) {
- PyErr_SetString(PyExc_TypeError, "missing format argument");
- return NULL;
- }
- fmt = PyTuple_GET_ITEM(args, 0);
- newargs = PyTuple_GetSlice(args, 1, n);
- if (newargs == NULL)
- return NULL;
-
- s_object = cache_struct(fmt);
- if (s_object == NULL) {
- Py_DECREF(newargs);
- return NULL;
- }
- result = s_pack(s_object, newargs);
- Py_DECREF(newargs);
- Py_DECREF(s_object);
- return result;
+ PyObject *s_object, *fmt, *newargs, *result;
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+
+ if (n == 0) {
+ PyErr_SetString(PyExc_TypeError, "missing format argument");
+ return NULL;
+ }
+ fmt = PyTuple_GET_ITEM(args, 0);
+ newargs = PyTuple_GetSlice(args, 1, n);
+ if (newargs == NULL)
+ return NULL;
+
+ s_object = cache_struct(fmt);
+ if (s_object == NULL) {
+ Py_DECREF(newargs);
+ return NULL;
+ }
+ result = s_pack(s_object, newargs);
+ Py_DECREF(newargs);
+ Py_DECREF(s_object);
+ return result;
}
PyDoc_STRVAR(pack_into_doc,
@@ -1821,27 +1821,27 @@ Write the packed bytes into the writable buffer buf starting at offset.");
static PyObject *
pack_into(PyObject *self, PyObject *args)
{
- PyObject *s_object, *fmt, *newargs, *result;
- Py_ssize_t n = PyTuple_GET_SIZE(args);
-
- if (n == 0) {
- PyErr_SetString(PyExc_TypeError, "missing format argument");
- return NULL;
- }
- fmt = PyTuple_GET_ITEM(args, 0);
- newargs = PyTuple_GetSlice(args, 1, n);
- if (newargs == NULL)
- return NULL;
-
- s_object = cache_struct(fmt);
- if (s_object == NULL) {
- Py_DECREF(newargs);
- return NULL;
- }
- result = s_pack_into(s_object, newargs);
- Py_DECREF(newargs);
- Py_DECREF(s_object);
- return result;
+ PyObject *s_object, *fmt, *newargs, *result;
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+
+ if (n == 0) {
+ PyErr_SetString(PyExc_TypeError, "missing format argument");
+ return NULL;
+ }
+ fmt = PyTuple_GET_ITEM(args, 0);
+ newargs = PyTuple_GetSlice(args, 1, n);
+ if (newargs == NULL)
+ return NULL;
+
+ s_object = cache_struct(fmt);
+ if (s_object == NULL) {
+ Py_DECREF(newargs);
+ return NULL;
+ }
+ result = s_pack_into(s_object, newargs);
+ Py_DECREF(newargs);
+ Py_DECREF(s_object);
+ return result;
}
PyDoc_STRVAR(unpack_doc,
@@ -1851,17 +1851,17 @@ Requires len(bytes) == calcsize(fmt).");
static PyObject *
unpack(PyObject *self, PyObject *args)
{
- PyObject *s_object, *fmt, *inputstr, *result;
+ PyObject *s_object, *fmt, *inputstr, *result;
- if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
+ return NULL;
- s_object = cache_struct(fmt);
- if (s_object == NULL)
- return NULL;
- result = s_unpack(s_object, inputstr);
- Py_DECREF(s_object);
- return result;
+ s_object = cache_struct(fmt);
+ if (s_object == NULL)
+ return NULL;
+ result = s_unpack(s_object, inputstr);
+ Py_DECREF(s_object);
+ return result;
}
PyDoc_STRVAR(unpack_from_doc,
@@ -1871,38 +1871,38 @@ fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
static PyObject *
unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *s_object, *fmt, *newargs, *result;
- Py_ssize_t n = PyTuple_GET_SIZE(args);
-
- if (n == 0) {
- PyErr_SetString(PyExc_TypeError, "missing format argument");
- return NULL;
- }
- fmt = PyTuple_GET_ITEM(args, 0);
- newargs = PyTuple_GetSlice(args, 1, n);
- if (newargs == NULL)
- return NULL;
-
- s_object = cache_struct(fmt);
- if (s_object == NULL) {
- Py_DECREF(newargs);
- return NULL;
- }
- result = s_unpack_from(s_object, newargs, kwds);
- Py_DECREF(newargs);
- Py_DECREF(s_object);
- return result;
+ PyObject *s_object, *fmt, *newargs, *result;
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+
+ if (n == 0) {
+ PyErr_SetString(PyExc_TypeError, "missing format argument");
+ return NULL;
+ }
+ fmt = PyTuple_GET_ITEM(args, 0);
+ newargs = PyTuple_GetSlice(args, 1, n);
+ if (newargs == NULL)
+ return NULL;
+
+ s_object = cache_struct(fmt);
+ if (s_object == NULL) {
+ Py_DECREF(newargs);
+ return NULL;
+ }
+ result = s_unpack_from(s_object, newargs, kwds);
+ Py_DECREF(newargs);
+ Py_DECREF(s_object);
+ return result;
}
static struct PyMethodDef module_functions[] = {
- {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
- {"calcsize", calcsize, METH_O, calcsize_doc},
- {"pack", pack, METH_VARARGS, pack_doc},
- {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
- {"unpack", unpack, METH_VARARGS, unpack_doc},
- {"unpack_from", (PyCFunction)unpack_from,
- METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
- {NULL, NULL} /* sentinel */
+ {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
+ {"calcsize", calcsize, METH_O, calcsize_doc},
+ {"pack", pack, METH_VARARGS, pack_doc},
+ {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
+ {"unpack", unpack, METH_VARARGS, unpack_doc},
+ {"unpack_from", (PyCFunction)unpack_from,
+ METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1939,87 +1939,87 @@ The variable struct.error is an exception raised on errors.\n");
static struct PyModuleDef _structmodule = {
- PyModuleDef_HEAD_INIT,
- "_struct",
- module_doc,
- -1,
- module_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_struct",
+ module_doc,
+ -1,
+ module_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__struct(void)
{
- PyObject *ver, *m;
-
- ver = PyBytes_FromString("0.3");
- if (ver == NULL)
- return NULL;
-
- m = PyModule_Create(&_structmodule);
- if (m == NULL)
- return NULL;
-
- Py_TYPE(&PyStructType) = &PyType_Type;
- if (PyType_Ready(&PyStructType) < 0)
- return NULL;
-
- /* Check endian and swap in faster functions */
- {
- int one = 1;
- formatdef *native = native_table;
- formatdef *other, *ptr;
- if ((int)*(unsigned char*)&one)
- other = lilendian_table;
- else
- other = bigendian_table;
- /* Scan through the native table, find a matching
- entry in the endian table and swap in the
- native implementations whenever possible
- (64-bit platforms may not have "standard" sizes) */
- while (native->format != '\0' && other->format != '\0') {
- ptr = other;
- while (ptr->format != '\0') {
- if (ptr->format == native->format) {
- /* Match faster when formats are
- listed in the same order */
- if (ptr == other)
- other++;
- /* Only use the trick if the
- size matches */
- if (ptr->size != native->size)
- break;
- /* Skip float and double, could be
- "unknown" float format */
- if (ptr->format == 'd' || ptr->format == 'f')
- break;
- ptr->pack = native->pack;
- ptr->unpack = native->unpack;
- break;
- }
- ptr++;
- }
- native++;
- }
- }
-
- /* Add some symbolic constants to the module */
- if (StructError == NULL) {
- StructError = PyErr_NewException("struct.error", NULL, NULL);
- if (StructError == NULL)
- return NULL;
- }
-
- Py_INCREF(StructError);
- PyModule_AddObject(m, "error", StructError);
-
- Py_INCREF((PyObject*)&PyStructType);
- PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
-
- PyModule_AddObject(m, "__version__", ver);
-
- return m;
+ PyObject *ver, *m;
+
+ ver = PyBytes_FromString("0.3");
+ if (ver == NULL)
+ return NULL;
+
+ m = PyModule_Create(&_structmodule);
+ if (m == NULL)
+ return NULL;
+
+ Py_TYPE(&PyStructType) = &PyType_Type;
+ if (PyType_Ready(&PyStructType) < 0)
+ return NULL;
+
+ /* Check endian and swap in faster functions */
+ {
+ int one = 1;
+ formatdef *native = native_table;
+ formatdef *other, *ptr;
+ if ((int)*(unsigned char*)&one)
+ other = lilendian_table;
+ else
+ other = bigendian_table;
+ /* Scan through the native table, find a matching
+ entry in the endian table and swap in the
+ native implementations whenever possible
+ (64-bit platforms may not have "standard" sizes) */
+ while (native->format != '\0' && other->format != '\0') {
+ ptr = other;
+ while (ptr->format != '\0') {
+ if (ptr->format == native->format) {
+ /* Match faster when formats are
+ listed in the same order */
+ if (ptr == other)
+ other++;
+ /* Only use the trick if the
+ size matches */
+ if (ptr->size != native->size)
+ break;
+ /* Skip float and double, could be
+ "unknown" float format */
+ if (ptr->format == 'd' || ptr->format == 'f')
+ break;
+ ptr->pack = native->pack;
+ ptr->unpack = native->unpack;
+ break;
+ }
+ ptr++;
+ }
+ native++;
+ }
+ }
+
+ /* Add some symbolic constants to the module */
+ if (StructError == NULL) {
+ StructError = PyErr_NewException("struct.error", NULL, NULL);
+ if (StructError == NULL)
+ return NULL;
+ }
+
+ Py_INCREF(StructError);
+ PyModule_AddObject(m, "error", StructError);
+
+ Py_INCREF((PyObject*)&PyStructType);
+ PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
+
+ PyModule_AddObject(m, "__version__", ver);
+
+ return m;
}
diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c
index ea0b1c7..2868014 100644
--- a/Modules/_testcapimodule.c
+++ b/Modules/_testcapimodule.c
@@ -15,22 +15,22 @@
#ifdef WITH_THREAD
#include "pythread.h"
#endif /* WITH_THREAD */
-static PyObject *TestError; /* set to exception object in init */
+static PyObject *TestError; /* set to exception object in init */
/* Raise TestError with test_name + ": " + msg, and return NULL. */
static PyObject *
raiseTestError(const char* test_name, const char* msg)
{
- char buf[2048];
+ char buf[2048];
- if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
- PyErr_SetString(TestError, "internal error msg too large");
- else {
- PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
- PyErr_SetString(TestError, buf);
- }
- return NULL;
+ if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
+ PyErr_SetString(TestError, "internal error msg too large");
+ else {
+ PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
+ PyErr_SetString(TestError, buf);
+ }
+ return NULL;
}
/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
@@ -41,138 +41,138 @@ raiseTestError(const char* test_name, const char* msg)
*/
static PyObject*
sizeof_error(const char* fatname, const char* typname,
- int expected, int got)
+ int expected, int got)
{
- char buf[1024];
- PyOS_snprintf(buf, sizeof(buf),
- "%.200s #define == %d but sizeof(%.200s) == %d",
- fatname, expected, typname, got);
- PyErr_SetString(TestError, buf);
- return (PyObject*)NULL;
+ char buf[1024];
+ PyOS_snprintf(buf, sizeof(buf),
+ "%.200s #define == %d but sizeof(%.200s) == %d",
+ fatname, expected, typname, got);
+ PyErr_SetString(TestError, buf);
+ return (PyObject*)NULL;
}
static PyObject*
test_config(PyObject *self)
{
#define CHECK_SIZEOF(FATNAME, TYPE) \
- if (FATNAME != sizeof(TYPE)) \
- return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
-
- CHECK_SIZEOF(SIZEOF_SHORT, short);
- CHECK_SIZEOF(SIZEOF_INT, int);
- CHECK_SIZEOF(SIZEOF_LONG, long);
- CHECK_SIZEOF(SIZEOF_VOID_P, void*);
- CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
+ if (FATNAME != sizeof(TYPE)) \
+ return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
+
+ CHECK_SIZEOF(SIZEOF_SHORT, short);
+ CHECK_SIZEOF(SIZEOF_INT, int);
+ CHECK_SIZEOF(SIZEOF_LONG, long);
+ CHECK_SIZEOF(SIZEOF_VOID_P, void*);
+ CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
#ifdef HAVE_LONG_LONG
- CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
+ CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
#endif
#undef CHECK_SIZEOF
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject*
test_list_api(PyObject *self)
{
- PyObject* list;
- int i;
+ PyObject* list;
+ int i;
- /* SF bug 132008: PyList_Reverse segfaults */
+ /* SF bug 132008: PyList_Reverse segfaults */
#define NLIST 30
- list = PyList_New(NLIST);
- if (list == (PyObject*)NULL)
- return (PyObject*)NULL;
- /* list = range(NLIST) */
- for (i = 0; i < NLIST; ++i) {
- PyObject* anint = PyLong_FromLong(i);
- if (anint == (PyObject*)NULL) {
- Py_DECREF(list);
- return (PyObject*)NULL;
- }
- PyList_SET_ITEM(list, i, anint);
- }
- /* list.reverse(), via PyList_Reverse() */
- i = PyList_Reverse(list); /* should not blow up! */
- if (i != 0) {
- Py_DECREF(list);
- return (PyObject*)NULL;
- }
- /* Check that list == range(29, -1, -1) now */
- for (i = 0; i < NLIST; ++i) {
- PyObject* anint = PyList_GET_ITEM(list, i);
- if (PyLong_AS_LONG(anint) != NLIST-1-i) {
- PyErr_SetString(TestError,
- "test_list_api: reverse screwed up");
- Py_DECREF(list);
- return (PyObject*)NULL;
- }
- }
- Py_DECREF(list);
+ list = PyList_New(NLIST);
+ if (list == (PyObject*)NULL)
+ return (PyObject*)NULL;
+ /* list = range(NLIST) */
+ for (i = 0; i < NLIST; ++i) {
+ PyObject* anint = PyLong_FromLong(i);
+ if (anint == (PyObject*)NULL) {
+ Py_DECREF(list);
+ return (PyObject*)NULL;
+ }
+ PyList_SET_ITEM(list, i, anint);
+ }
+ /* list.reverse(), via PyList_Reverse() */
+ i = PyList_Reverse(list); /* should not blow up! */
+ if (i != 0) {
+ Py_DECREF(list);
+ return (PyObject*)NULL;
+ }
+ /* Check that list == range(29, -1, -1) now */
+ for (i = 0; i < NLIST; ++i) {
+ PyObject* anint = PyList_GET_ITEM(list, i);
+ if (PyLong_AS_LONG(anint) != NLIST-1-i) {
+ PyErr_SetString(TestError,
+ "test_list_api: reverse screwed up");
+ Py_DECREF(list);
+ return (PyObject*)NULL;
+ }
+ }
+ Py_DECREF(list);
#undef NLIST
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static int
test_dict_inner(int count)
{
- Py_ssize_t pos = 0, iterations = 0;
- int i;
- PyObject *dict = PyDict_New();
- PyObject *v, *k;
-
- if (dict == NULL)
- return -1;
-
- for (i = 0; i < count; i++) {
- v = PyLong_FromLong(i);
- PyDict_SetItem(dict, v, v);
- Py_DECREF(v);
- }
-
- while (PyDict_Next(dict, &pos, &k, &v)) {
- PyObject *o;
- iterations++;
-
- i = PyLong_AS_LONG(v) + 1;
- o = PyLong_FromLong(i);
- if (o == NULL)
- return -1;
- if (PyDict_SetItem(dict, k, o) < 0) {
- Py_DECREF(o);
- return -1;
- }
- Py_DECREF(o);
- }
-
- Py_DECREF(dict);
-
- if (iterations != count) {
- PyErr_SetString(
- TestError,
- "test_dict_iteration: dict iteration went wrong ");
- return -1;
- } else {
- return 0;
- }
+ Py_ssize_t pos = 0, iterations = 0;
+ int i;
+ PyObject *dict = PyDict_New();
+ PyObject *v, *k;
+
+ if (dict == NULL)
+ return -1;
+
+ for (i = 0; i < count; i++) {
+ v = PyLong_FromLong(i);
+ PyDict_SetItem(dict, v, v);
+ Py_DECREF(v);
+ }
+
+ while (PyDict_Next(dict, &pos, &k, &v)) {
+ PyObject *o;
+ iterations++;
+
+ i = PyLong_AS_LONG(v) + 1;
+ o = PyLong_FromLong(i);
+ if (o == NULL)
+ return -1;
+ if (PyDict_SetItem(dict, k, o) < 0) {
+ Py_DECREF(o);
+ return -1;
+ }
+ Py_DECREF(o);
+ }
+
+ Py_DECREF(dict);
+
+ if (iterations != count) {
+ PyErr_SetString(
+ TestError,
+ "test_dict_iteration: dict iteration went wrong ");
+ return -1;
+ } else {
+ return 0;
+ }
}
static PyObject*
test_dict_iteration(PyObject* self)
{
- int i;
+ int i;
- for (i = 0; i < 200; i++) {
- if (test_dict_inner(i) < 0) {
- return NULL;
- }
- }
+ for (i = 0; i < 200; i++) {
+ if (test_dict_inner(i) < 0) {
+ return NULL;
+ }
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -180,107 +180,107 @@ test_dict_iteration(PyObject* self)
* PyType_Ready if it hasn't already been called
*/
static PyTypeObject _HashInheritanceTester_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "hashinheritancetester", /* Name of this type */
- sizeof(PyObject), /* Basic object size */
- 0, /* Item size for varobject */
- (destructor)PyObject_Del, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "hashinheritancetester", /* Name of this type */
+ sizeof(PyObject), /* Basic object size */
+ 0, /* Item size for varobject */
+ (destructor)PyObject_Del, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
};
static PyObject*
test_lazy_hash_inheritance(PyObject* self)
{
- PyTypeObject *type;
- PyObject *obj;
- long hash;
-
- type = &_HashInheritanceTester_Type;
-
- if (type->tp_dict != NULL)
- /* The type has already been initialized. This probably means
- -R is being used. */
- Py_RETURN_NONE;
-
-
- obj = PyObject_New(PyObject, type);
- if (obj == NULL) {
- PyErr_Clear();
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: failed to create object");
- return NULL;
- }
-
- if (type->tp_dict != NULL) {
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: type initialised too soon");
- Py_DECREF(obj);
- return NULL;
- }
-
- hash = PyObject_Hash(obj);
- if ((hash == -1) && PyErr_Occurred()) {
- PyErr_Clear();
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: could not hash object");
- Py_DECREF(obj);
- return NULL;
- }
-
- if (type->tp_dict == NULL) {
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: type not initialised by hash()");
- Py_DECREF(obj);
- return NULL;
- }
-
- if (type->tp_hash != PyType_Type.tp_hash) {
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: unexpected hash function");
- Py_DECREF(obj);
- return NULL;
- }
-
- Py_DECREF(obj);
-
- Py_RETURN_NONE;
+ PyTypeObject *type;
+ PyObject *obj;
+ long hash;
+
+ type = &_HashInheritanceTester_Type;
+
+ if (type->tp_dict != NULL)
+ /* The type has already been initialized. This probably means
+ -R is being used. */
+ Py_RETURN_NONE;
+
+
+ obj = PyObject_New(PyObject, type);
+ if (obj == NULL) {
+ PyErr_Clear();
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: failed to create object");
+ return NULL;
+ }
+
+ if (type->tp_dict != NULL) {
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: type initialised too soon");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ hash = PyObject_Hash(obj);
+ if ((hash == -1) && PyErr_Occurred()) {
+ PyErr_Clear();
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: could not hash object");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ if (type->tp_dict == NULL) {
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: type not initialised by hash()");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ if (type->tp_hash != PyType_Type.tp_hash) {
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: unexpected hash function");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ Py_DECREF(obj);
+
+ Py_RETURN_NONE;
}
@@ -291,85 +291,85 @@ test_lazy_hash_inheritance(PyObject* self)
static int
broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags)
{
- PyErr_SetString(
- TestError,
- "test_broken_memoryview: expected error in bf_getbuffer");
- return -1;
+ PyErr_SetString(
+ TestError,
+ "test_broken_memoryview: expected error in bf_getbuffer");
+ return -1;
}
static PyBufferProcs memoryviewtester_as_buffer = {
- (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
- 0, /* bf_releasebuffer */
+ (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
+ 0, /* bf_releasebuffer */
};
static PyTypeObject _MemoryViewTester_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "memoryviewtester", /* Name of this type */
- sizeof(PyObject), /* Basic object size */
- 0, /* Item size for varobject */
- (destructor)PyObject_Del, /* 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 */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- &memoryviewtester_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "memoryviewtester", /* Name of this type */
+ sizeof(PyObject), /* Basic object size */
+ 0, /* Item size for varobject */
+ (destructor)PyObject_Del, /* 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 */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ &memoryviewtester_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
};
static PyObject*
test_broken_memoryview(PyObject* self)
{
- PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
- PyObject *res;
-
- if (obj == NULL) {
- PyErr_Clear();
- PyErr_SetString(
- TestError,
- "test_broken_memoryview: failed to create object");
- return NULL;
- }
-
- res = PyMemoryView_FromObject(obj);
- if (res || !PyErr_Occurred()){
- PyErr_SetString(
- TestError,
- "test_broken_memoryview: memoryview() didn't raise an Exception");
- Py_XDECREF(res);
- Py_DECREF(obj);
- return NULL;
- }
+ PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
+ PyObject *res;
+
+ if (obj == NULL) {
+ PyErr_Clear();
+ PyErr_SetString(
+ TestError,
+ "test_broken_memoryview: failed to create object");
+ return NULL;
+ }
+
+ res = PyMemoryView_FromObject(obj);
+ if (res || !PyErr_Occurred()){
+ PyErr_SetString(
+ TestError,
+ "test_broken_memoryview: memoryview() didn't raise an Exception");
+ Py_XDECREF(res);
+ Py_DECREF(obj);
+ return NULL;
+ }
- PyErr_Clear();
- Py_DECREF(obj);
- Py_RETURN_NONE;
+ PyErr_Clear();
+ Py_DECREF(obj);
+ Py_RETURN_NONE;
}
@@ -393,22 +393,22 @@ test_broken_memoryview(PyObject* self)
static PyObject *
raise_test_long_error(const char* msg)
{
- return raiseTestError("test_long_api", msg);
+ return raiseTestError("test_long_api", msg);
}
-#define TESTNAME test_long_api_inner
-#define TYPENAME long
-#define F_S_TO_PY PyLong_FromLong
-#define F_PY_TO_S PyLong_AsLong
-#define F_U_TO_PY PyLong_FromUnsignedLong
-#define F_PY_TO_U PyLong_AsUnsignedLong
+#define TESTNAME test_long_api_inner
+#define TYPENAME long
+#define F_S_TO_PY PyLong_FromLong
+#define F_PY_TO_S PyLong_AsLong
+#define F_U_TO_PY PyLong_FromUnsignedLong
+#define F_PY_TO_U PyLong_AsUnsignedLong
#include "testcapi_long.h"
static PyObject *
test_long_api(PyObject* self)
{
- return TESTNAME(raise_test_long_error);
+ return TESTNAME(raise_test_long_error);
}
#undef TESTNAME
@@ -423,22 +423,22 @@ test_long_api(PyObject* self)
static PyObject *
raise_test_longlong_error(const char* msg)
{
- return raiseTestError("test_longlong_api", msg);
+ return raiseTestError("test_longlong_api", msg);
}
-#define TESTNAME test_longlong_api_inner
-#define TYPENAME PY_LONG_LONG
-#define F_S_TO_PY PyLong_FromLongLong
-#define F_PY_TO_S PyLong_AsLongLong
-#define F_U_TO_PY PyLong_FromUnsignedLongLong
-#define F_PY_TO_U PyLong_AsUnsignedLongLong
+#define TESTNAME test_longlong_api_inner
+#define TYPENAME PY_LONG_LONG
+#define F_S_TO_PY PyLong_FromLongLong
+#define F_PY_TO_S PyLong_AsLongLong
+#define F_U_TO_PY PyLong_FromUnsignedLongLong
+#define F_PY_TO_U PyLong_AsUnsignedLongLong
#include "testcapi_long.h"
static PyObject *
test_longlong_api(PyObject* self, PyObject *args)
{
- return TESTNAME(raise_test_longlong_error);
+ return TESTNAME(raise_test_longlong_error);
}
#undef TESTNAME
@@ -456,161 +456,161 @@ test_longlong_api(PyObject* self, PyObject *args)
static PyObject *
test_long_and_overflow(PyObject *self)
{
- PyObject *num, *one, *temp;
- long value;
- int overflow;
-
- /* Test that overflow is set properly for a large value. */
- /* num is a number larger than LONG_MAX even on 64-bit platforms */
- num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to 1");
-
- /* Same again, with num = LONG_MAX + 1 */
- num = PyLong_FromLong(LONG_MAX);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Add(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to 1");
-
- /* Test that overflow is set properly for a large negative value. */
- /* num is a number smaller than LONG_MIN even on 64-bit platforms */
- num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to -1");
-
- /* Same again, with num = LONG_MIN - 1 */
- num = PyLong_FromLong(LONG_MIN);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Subtract(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to -1");
-
- /* Test that overflow is cleared properly for small values. */
- num = PyLong_FromString("FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != 0xFF)
- return raiseTestError("test_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromString("-FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -0xFF)
- return raiseTestError("test_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was set incorrectly");
-
- num = PyLong_FromLong(LONG_MAX);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != LONG_MAX)
- return raiseTestError("test_long_and_overflow",
- "expected return value LONG_MAX");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromLong(LONG_MIN);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != LONG_MIN)
- return raiseTestError("test_long_and_overflow",
- "expected return value LONG_MIN");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was not cleared");
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *num, *one, *temp;
+ long value;
+ int overflow;
+
+ /* Test that overflow is set properly for a large value. */
+ /* num is a number larger than LONG_MAX even on 64-bit platforms */
+ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Same again, with num = LONG_MAX + 1 */
+ num = PyLong_FromLong(LONG_MAX);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Add(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Test that overflow is set properly for a large negative value. */
+ /* num is a number smaller than LONG_MIN even on 64-bit platforms */
+ num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Same again, with num = LONG_MIN - 1 */
+ num = PyLong_FromLong(LONG_MIN);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Subtract(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Test that overflow is cleared properly for small values. */
+ num = PyLong_FromString("FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != 0xFF)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromString("-FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -0xFF)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was set incorrectly");
+
+ num = PyLong_FromLong(LONG_MAX);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != LONG_MAX)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value LONG_MAX");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromLong(LONG_MIN);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != LONG_MIN)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value LONG_MIN");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not cleared");
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test the PyLong_AsLongLongAndOverflow API. General conversion to
@@ -621,161 +621,161 @@ test_long_and_overflow(PyObject *self)
static PyObject *
test_long_long_and_overflow(PyObject *self)
{
- PyObject *num, *one, *temp;
- PY_LONG_LONG value;
- int overflow;
-
- /* Test that overflow is set properly for a large value. */
- /* num is a number larger than PY_LLONG_MAX on a typical machine. */
- num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to 1");
-
- /* Same again, with num = PY_LLONG_MAX + 1 */
- num = PyLong_FromLongLong(PY_LLONG_MAX);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Add(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to 1");
-
- /* Test that overflow is set properly for a large negative value. */
- /* num is a number smaller than PY_LLONG_MIN on a typical platform */
- num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to -1");
-
- /* Same again, with num = PY_LLONG_MIN - 1 */
- num = PyLong_FromLongLong(PY_LLONG_MIN);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Subtract(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to -1");
-
- /* Test that overflow is cleared properly for small values. */
- num = PyLong_FromString("FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != 0xFF)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromString("-FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -0xFF)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was set incorrectly");
-
- num = PyLong_FromLongLong(PY_LLONG_MAX);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != PY_LLONG_MAX)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value PY_LLONG_MAX");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromLongLong(PY_LLONG_MIN);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != PY_LLONG_MIN)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value PY_LLONG_MIN");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not cleared");
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *num, *one, *temp;
+ PY_LONG_LONG value;
+ int overflow;
+
+ /* Test that overflow is set properly for a large value. */
+ /* num is a number larger than PY_LLONG_MAX on a typical machine. */
+ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Same again, with num = PY_LLONG_MAX + 1 */
+ num = PyLong_FromLongLong(PY_LLONG_MAX);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Add(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Test that overflow is set properly for a large negative value. */
+ /* num is a number smaller than PY_LLONG_MIN on a typical platform */
+ num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Same again, with num = PY_LLONG_MIN - 1 */
+ num = PyLong_FromLongLong(PY_LLONG_MIN);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Subtract(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Test that overflow is cleared properly for small values. */
+ num = PyLong_FromString("FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != 0xFF)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromString("-FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -0xFF)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was set incorrectly");
+
+ num = PyLong_FromLongLong(PY_LLONG_MAX);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != PY_LLONG_MAX)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value PY_LLONG_MAX");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromLongLong(PY_LLONG_MIN);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != PY_LLONG_MIN)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value PY_LLONG_MIN");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not cleared");
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG
@@ -785,71 +785,71 @@ test_long_long_and_overflow(PyObject *self)
static PyObject *
test_L_code(PyObject *self)
{
- PyObject *tuple, *num;
- PY_LONG_LONG value;
+ PyObject *tuple, *num;
+ PY_LONG_LONG value;
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
- num = PyLong_FromLong(42);
- if (num == NULL)
- return NULL;
+ num = PyLong_FromLong(42);
+ if (num == NULL)
+ return NULL;
- PyTuple_SET_ITEM(tuple, 0, num);
+ PyTuple_SET_ITEM(tuple, 0, num);
- value = -1;
- if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
- return NULL;
- if (value != 42)
- return raiseTestError("test_L_code",
- "L code returned wrong value for long 42");
+ value = -1;
+ if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
+ return NULL;
+ if (value != 42)
+ return raiseTestError("test_L_code",
+ "L code returned wrong value for long 42");
- Py_DECREF(num);
- num = PyLong_FromLong(42);
- if (num == NULL)
- return NULL;
+ Py_DECREF(num);
+ num = PyLong_FromLong(42);
+ if (num == NULL)
+ return NULL;
- PyTuple_SET_ITEM(tuple, 0, num);
+ PyTuple_SET_ITEM(tuple, 0, num);
- value = -1;
- if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
- return NULL;
- if (value != 42)
- return raiseTestError("test_L_code",
- "L code returned wrong value for int 42");
+ value = -1;
+ if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
+ return NULL;
+ if (value != 42)
+ return raiseTestError("test_L_code",
+ "L code returned wrong value for int 42");
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
-#endif /* ifdef HAVE_LONG_LONG */
+#endif /* ifdef HAVE_LONG_LONG */
/* Test tuple argument processing */
static PyObject *
getargs_tuple(PyObject *self, PyObject *args)
{
- int a, b, c;
- if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
- return NULL;
- return Py_BuildValue("iii", a, b, c);
+ int a, b, c;
+ if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
+ return NULL;
+ return Py_BuildValue("iii", a, b, c);
}
/* test PyArg_ParseTupleAndKeywords */
static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
{
- static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
- static char *fmt="(ii)i|(i(ii))(iii)i";
- int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
+ static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
+ static char *fmt="(ii)i|(i(ii))(iii)i";
+ int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
- &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
- &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
- return NULL;
- return Py_BuildValue("iiiiiiiiii",
- int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
- int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
+ &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
+ &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
+ return NULL;
+ return Py_BuildValue("iiiiiiiiii",
+ int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
+ int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
}
/* Functions to call PyArg_ParseTuple with integer format codes,
@@ -858,101 +858,101 @@ static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwar
static PyObject *
getargs_b(PyObject *self, PyObject *args)
{
- unsigned char value;
- if (!PyArg_ParseTuple(args, "b", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned char value;
+ if (!PyArg_ParseTuple(args, "b", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_B(PyObject *self, PyObject *args)
{
- unsigned char value;
- if (!PyArg_ParseTuple(args, "B", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned char value;
+ if (!PyArg_ParseTuple(args, "B", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_h(PyObject *self, PyObject *args)
{
- short value;
- if (!PyArg_ParseTuple(args, "h", &value))
- return NULL;
- return PyLong_FromLong((long)value);
+ short value;
+ if (!PyArg_ParseTuple(args, "h", &value))
+ return NULL;
+ return PyLong_FromLong((long)value);
}
static PyObject *
getargs_H(PyObject *self, PyObject *args)
{
- unsigned short value;
- if (!PyArg_ParseTuple(args, "H", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned short value;
+ if (!PyArg_ParseTuple(args, "H", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_I(PyObject *self, PyObject *args)
{
- unsigned int value;
- if (!PyArg_ParseTuple(args, "I", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned int value;
+ if (!PyArg_ParseTuple(args, "I", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_k(PyObject *self, PyObject *args)
{
- unsigned long value;
- if (!PyArg_ParseTuple(args, "k", &value))
- return NULL;
- return PyLong_FromUnsignedLong(value);
+ unsigned long value;
+ if (!PyArg_ParseTuple(args, "k", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong(value);
}
static PyObject *
getargs_i(PyObject *self, PyObject *args)
{
- int value;
- if (!PyArg_ParseTuple(args, "i", &value))
- return NULL;
- return PyLong_FromLong((long)value);
+ int value;
+ if (!PyArg_ParseTuple(args, "i", &value))
+ return NULL;
+ return PyLong_FromLong((long)value);
}
static PyObject *
getargs_l(PyObject *self, PyObject *args)
{
- long value;
- if (!PyArg_ParseTuple(args, "l", &value))
- return NULL;
- return PyLong_FromLong(value);
+ long value;
+ if (!PyArg_ParseTuple(args, "l", &value))
+ return NULL;
+ return PyLong_FromLong(value);
}
static PyObject *
getargs_n(PyObject *self, PyObject *args)
{
- Py_ssize_t value;
- if (!PyArg_ParseTuple(args, "n", &value))
- return NULL;
- return PyLong_FromSsize_t(value);
+ Py_ssize_t value;
+ if (!PyArg_ParseTuple(args, "n", &value))
+ return NULL;
+ return PyLong_FromSsize_t(value);
}
#ifdef HAVE_LONG_LONG
static PyObject *
getargs_L(PyObject *self, PyObject *args)
{
- PY_LONG_LONG value;
- if (!PyArg_ParseTuple(args, "L", &value))
- return NULL;
- return PyLong_FromLongLong(value);
+ PY_LONG_LONG value;
+ if (!PyArg_ParseTuple(args, "L", &value))
+ return NULL;
+ return PyLong_FromLongLong(value);
}
static PyObject *
getargs_K(PyObject *self, PyObject *args)
{
- unsigned PY_LONG_LONG value;
- if (!PyArg_ParseTuple(args, "K", &value))
- return NULL;
- return PyLong_FromUnsignedLongLong(value);
+ unsigned PY_LONG_LONG value;
+ if (!PyArg_ParseTuple(args, "K", &value))
+ return NULL;
+ return PyLong_FromUnsignedLongLong(value);
}
#endif
@@ -961,54 +961,54 @@ getargs_K(PyObject *self, PyObject *args)
static PyObject *
test_k_code(PyObject *self)
{
- PyObject *tuple, *num;
- unsigned long value;
+ PyObject *tuple, *num;
+ unsigned long value;
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
- /* a number larger than ULONG_MAX even on 64-bit platforms */
- num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
+ /* a number larger than ULONG_MAX even on 64-bit platforms */
+ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
- value = PyLong_AsUnsignedLongMask(num);
- if (value != ULONG_MAX)
- return raiseTestError("test_k_code",
- "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
+ value = PyLong_AsUnsignedLongMask(num);
+ if (value != ULONG_MAX)
+ return raiseTestError("test_k_code",
+ "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
- PyTuple_SET_ITEM(tuple, 0, num);
+ PyTuple_SET_ITEM(tuple, 0, num);
- value = 0;
- if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
- return NULL;
- if (value != ULONG_MAX)
- return raiseTestError("test_k_code",
- "k code returned wrong value for long 0xFFF...FFF");
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
+ return NULL;
+ if (value != ULONG_MAX)
+ return raiseTestError("test_k_code",
+ "k code returned wrong value for long 0xFFF...FFF");
- Py_DECREF(num);
- num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
- if (num == NULL)
- return NULL;
+ Py_DECREF(num);
+ num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
+ if (num == NULL)
+ return NULL;
- value = PyLong_AsUnsignedLongMask(num);
- if (value != (unsigned long)-0x42)
- return raiseTestError("test_k_code",
- "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
+ value = PyLong_AsUnsignedLongMask(num);
+ if (value != (unsigned long)-0x42)
+ return raiseTestError("test_k_code",
+ "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
- PyTuple_SET_ITEM(tuple, 0, num);
+ PyTuple_SET_ITEM(tuple, 0, num);
- value = 0;
- if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
- return NULL;
- if (value != (unsigned long)-0x42)
- return raiseTestError("test_k_code",
- "k code returned wrong value for long -0xFFF..000042");
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
+ return NULL;
+ if (value != (unsigned long)-0x42)
+ return raiseTestError("test_k_code",
+ "k code returned wrong value for long -0xFFF..000042");
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -1023,23 +1023,23 @@ test_s_code(PyObject *self)
tuple = PyTuple_New(1);
if (tuple == NULL)
- return NULL;
+ return NULL;
obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"),
- "latin-1", NULL);
+ "latin-1", NULL);
if (obj == NULL)
- return NULL;
+ return NULL;
PyTuple_SET_ITEM(tuple, 0, obj);
/* These two blocks used to raise a TypeError:
- * "argument must be string without null bytes, not str"
+ * "argument must be string without null bytes, not str"
*/
if (PyArg_ParseTuple(tuple, "s:test_s_code1", &value) < 0)
- return NULL;
+ return NULL;
if (PyArg_ParseTuple(tuple, "z:test_s_code2", &value) < 0)
- return NULL;
+ return NULL;
Py_DECREF(tuple);
Py_RETURN_NONE;
@@ -1048,46 +1048,46 @@ test_s_code(PyObject *self)
static PyObject *
test_bug_7414(PyObject *self)
{
- /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being
- skipped properly in skipitem() */
- int a = 0, b = 0, result;
- char *kwlist[] = {"a", "b", NULL};
- PyObject *tuple = NULL, *dict = NULL, *b_str;
-
- tuple = PyTuple_New(0);
- if (tuple == NULL)
- goto failure;
- dict = PyDict_New();
- if (dict == NULL)
- goto failure;
- b_str = PyUnicode_FromString("b");
- if (b_str == NULL)
- goto failure;
- result = PyDict_SetItemString(dict, "b", b_str);
- Py_DECREF(b_str);
- if (result < 0)
- goto failure;
-
- result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC",
- kwlist, &a, &b);
- if (!result)
- goto failure;
-
- if (a != 0)
- return raiseTestError("test_bug_7414",
- "C format code not skipped properly");
- if (b != 'b')
- return raiseTestError("test_bug_7414",
- "C format code returned wrong value");
-
- Py_DECREF(dict);
- Py_DECREF(tuple);
- Py_RETURN_NONE;
+ /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being
+ skipped properly in skipitem() */
+ int a = 0, b = 0, result;
+ char *kwlist[] = {"a", "b", NULL};
+ PyObject *tuple = NULL, *dict = NULL, *b_str;
+
+ tuple = PyTuple_New(0);
+ if (tuple == NULL)
+ goto failure;
+ dict = PyDict_New();
+ if (dict == NULL)
+ goto failure;
+ b_str = PyUnicode_FromString("b");
+ if (b_str == NULL)
+ goto failure;
+ result = PyDict_SetItemString(dict, "b", b_str);
+ Py_DECREF(b_str);
+ if (result < 0)
+ goto failure;
+
+ result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC",
+ kwlist, &a, &b);
+ if (!result)
+ goto failure;
+
+ if (a != 0)
+ return raiseTestError("test_bug_7414",
+ "C format code not skipped properly");
+ if (b != 'b')
+ return raiseTestError("test_bug_7414",
+ "C format code returned wrong value");
+
+ Py_DECREF(dict);
+ Py_DECREF(tuple);
+ Py_RETURN_NONE;
failure:
- Py_XDECREF(dict);
- Py_XDECREF(tuple);
- return NULL;
+ Py_XDECREF(dict);
+ Py_XDECREF(tuple);
+ return NULL;
}
@@ -1099,185 +1099,185 @@ static volatile int x;
static PyObject *
test_u_code(PyObject *self)
{
- PyObject *tuple, *obj;
- Py_UNICODE *value;
- Py_ssize_t len;
-
- /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
- /* Just use the macro and check that it compiles */
- x = Py_UNICODE_ISSPACE(25);
-
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
-
- obj = PyUnicode_Decode("test", strlen("test"),
- "ascii", NULL);
- if (obj == NULL)
- return NULL;
-
- PyTuple_SET_ITEM(tuple, 0, obj);
-
- value = 0;
- if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
- return NULL;
- if (value != PyUnicode_AS_UNICODE(obj))
- return raiseTestError("test_u_code",
- "u code returned wrong value for u'test'");
- value = 0;
- if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
- return NULL;
- if (value != PyUnicode_AS_UNICODE(obj) ||
- len != PyUnicode_GET_SIZE(obj))
- return raiseTestError("test_u_code",
- "u# code returned wrong values for u'test'");
-
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *tuple, *obj;
+ Py_UNICODE *value;
+ Py_ssize_t len;
+
+ /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
+ /* Just use the macro and check that it compiles */
+ x = Py_UNICODE_ISSPACE(25);
+
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
+
+ obj = PyUnicode_Decode("test", strlen("test"),
+ "ascii", NULL);
+ if (obj == NULL)
+ return NULL;
+
+ PyTuple_SET_ITEM(tuple, 0, obj);
+
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
+ return NULL;
+ if (value != PyUnicode_AS_UNICODE(obj))
+ return raiseTestError("test_u_code",
+ "u code returned wrong value for u'test'");
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
+ return NULL;
+ if (value != PyUnicode_AS_UNICODE(obj) ||
+ len != PyUnicode_GET_SIZE(obj))
+ return raiseTestError("test_u_code",
+ "u# code returned wrong values for u'test'");
+
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test Z and Z# codes for PyArg_ParseTuple */
static PyObject *
test_Z_code(PyObject *self)
{
- PyObject *tuple, *obj;
- Py_UNICODE *value1, *value2;
- Py_ssize_t len1, len2;
-
- tuple = PyTuple_New(2);
- if (tuple == NULL)
- return NULL;
-
- obj = PyUnicode_FromString("test");
- PyTuple_SET_ITEM(tuple, 0, obj);
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(tuple, 1, Py_None);
-
- /* swap values on purpose */
- value1 = NULL;
- value2 = PyUnicode_AS_UNICODE(obj);
-
- /* Test Z for both values */
- if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0)
- return NULL;
- if (value1 != PyUnicode_AS_UNICODE(obj))
- return raiseTestError("test_Z_code",
- "Z code returned wrong value for 'test'");
- if (value2 != NULL)
- return raiseTestError("test_Z_code",
- "Z code returned wrong value for None");
-
- value1 = NULL;
- value2 = PyUnicode_AS_UNICODE(obj);
- len1 = -1;
- len2 = -1;
-
- /* Test Z# for both values */
- if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1,
- &value2, &len2) < 0)
- return NULL;
- if (value1 != PyUnicode_AS_UNICODE(obj) ||
- len1 != PyUnicode_GET_SIZE(obj))
- return raiseTestError("test_Z_code",
- "Z# code returned wrong values for 'test'");
- if (value2 != NULL ||
- len2 != 0)
- return raiseTestError("test_Z_code",
- "Z# code returned wrong values for None'");
-
- Py_DECREF(tuple);
- Py_RETURN_NONE;
+ PyObject *tuple, *obj;
+ Py_UNICODE *value1, *value2;
+ Py_ssize_t len1, len2;
+
+ tuple = PyTuple_New(2);
+ if (tuple == NULL)
+ return NULL;
+
+ obj = PyUnicode_FromString("test");
+ PyTuple_SET_ITEM(tuple, 0, obj);
+ Py_INCREF(Py_None);
+ PyTuple_SET_ITEM(tuple, 1, Py_None);
+
+ /* swap values on purpose */
+ value1 = NULL;
+ value2 = PyUnicode_AS_UNICODE(obj);
+
+ /* Test Z for both values */
+ if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0)
+ return NULL;
+ if (value1 != PyUnicode_AS_UNICODE(obj))
+ return raiseTestError("test_Z_code",
+ "Z code returned wrong value for 'test'");
+ if (value2 != NULL)
+ return raiseTestError("test_Z_code",
+ "Z code returned wrong value for None");
+
+ value1 = NULL;
+ value2 = PyUnicode_AS_UNICODE(obj);
+ len1 = -1;
+ len2 = -1;
+
+ /* Test Z# for both values */
+ if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1,
+ &value2, &len2) < 0)
+ return NULL;
+ if (value1 != PyUnicode_AS_UNICODE(obj) ||
+ len1 != PyUnicode_GET_SIZE(obj))
+ return raiseTestError("test_Z_code",
+ "Z# code returned wrong values for 'test'");
+ if (value2 != NULL ||
+ len2 != 0)
+ return raiseTestError("test_Z_code",
+ "Z# code returned wrong values for None'");
+
+ Py_DECREF(tuple);
+ Py_RETURN_NONE;
}
static PyObject *
test_widechar(PyObject *self)
{
#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
- const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
- size_t wtextlen = 1;
+ const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
+ size_t wtextlen = 1;
#else
- const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
- size_t wtextlen = 2;
+ const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
+ size_t wtextlen = 2;
#endif
- PyObject *wide, *utf8;
-
- wide = PyUnicode_FromWideChar(wtext, wtextlen);
- if (wide == NULL)
- return NULL;
-
- utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
- if (utf8 == NULL) {
- Py_DECREF(wide);
- return NULL;
- }
-
- if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
- Py_DECREF(wide);
- Py_DECREF(utf8);
- return raiseTestError("test_widechar",
- "wide string and utf8 string "
- "have different length");
- }
- if (PyUnicode_Compare(wide, utf8)) {
- Py_DECREF(wide);
- Py_DECREF(utf8);
- if (PyErr_Occurred())
- return NULL;
- return raiseTestError("test_widechar",
- "wide string and utf8 string "
- "are different");
- }
-
- Py_DECREF(wide);
- Py_DECREF(utf8);
- Py_RETURN_NONE;
+ PyObject *wide, *utf8;
+
+ wide = PyUnicode_FromWideChar(wtext, wtextlen);
+ if (wide == NULL)
+ return NULL;
+
+ utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
+ if (utf8 == NULL) {
+ Py_DECREF(wide);
+ return NULL;
+ }
+
+ if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
+ Py_DECREF(wide);
+ Py_DECREF(utf8);
+ return raiseTestError("test_widechar",
+ "wide string and utf8 string "
+ "have different length");
+ }
+ if (PyUnicode_Compare(wide, utf8)) {
+ Py_DECREF(wide);
+ Py_DECREF(utf8);
+ if (PyErr_Occurred())
+ return NULL;
+ return raiseTestError("test_widechar",
+ "wide string and utf8 string "
+ "are different");
+ }
+
+ Py_DECREF(wide);
+ Py_DECREF(utf8);
+ Py_RETURN_NONE;
}
static PyObject *
test_empty_argparse(PyObject *self)
{
- /* Test that formats can begin with '|'. See issue #4720. */
- PyObject *tuple, *dict = NULL;
- static char *kwlist[] = {NULL};
- int result;
- tuple = PyTuple_New(0);
- if (!tuple)
- return NULL;
- if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
- goto done;
- dict = PyDict_New();
- if (!dict)
- goto done;
- result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
+ /* Test that formats can begin with '|'. See issue #4720. */
+ PyObject *tuple, *dict = NULL;
+ static char *kwlist[] = {NULL};
+ int result;
+ tuple = PyTuple_New(0);
+ if (!tuple)
+ return NULL;
+ if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
+ goto done;
+ dict = PyDict_New();
+ if (!dict)
+ goto done;
+ result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
done:
- Py_DECREF(tuple);
- Py_XDECREF(dict);
- if (result < 0)
- return NULL;
- else {
- Py_RETURN_NONE;
- }
+ Py_DECREF(tuple);
+ Py_XDECREF(dict);
+ if (result < 0)
+ return NULL;
+ else {
+ Py_RETURN_NONE;
+ }
}
static PyObject *
codec_incrementalencoder(PyObject *self, PyObject *args)
{
- const char *encoding, *errors = NULL;
- if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
- &encoding, &errors))
- return NULL;
- return PyCodec_IncrementalEncoder(encoding, errors);
+ const char *encoding, *errors = NULL;
+ if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
+ &encoding, &errors))
+ return NULL;
+ return PyCodec_IncrementalEncoder(encoding, errors);
}
static PyObject *
codec_incrementaldecoder(PyObject *self, PyObject *args)
{
- const char *encoding, *errors = NULL;
- if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
- &encoding, &errors))
- return NULL;
- return PyCodec_IncrementalDecoder(encoding, errors);
+ const char *encoding, *errors = NULL;
+ if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
+ &encoding, &errors))
+ return NULL;
+ return PyCodec_IncrementalDecoder(encoding, errors);
}
@@ -1285,42 +1285,42 @@ codec_incrementaldecoder(PyObject *self, PyObject *args)
static PyObject *
test_long_numbits(PyObject *self)
{
- struct triple {
- long input;
- size_t nbits;
- int sign;
- } testcases[] = {{0, 0, 0},
- {1L, 1, 1},
- {-1L, 1, -1},
- {2L, 2, 1},
- {-2L, 2, -1},
- {3L, 2, 1},
- {-3L, 2, -1},
- {4L, 3, 1},
- {-4L, 3, -1},
- {0x7fffL, 15, 1}, /* one Python long digit */
- {-0x7fffL, 15, -1},
- {0xffffL, 16, 1},
- {-0xffffL, 16, -1},
- {0xfffffffL, 28, 1},
- {-0xfffffffL, 28, -1}};
- int i;
-
- for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
- PyObject *plong = PyLong_FromLong(testcases[i].input);
- size_t nbits = _PyLong_NumBits(plong);
- int sign = _PyLong_Sign(plong);
-
- Py_DECREF(plong);
- if (nbits != testcases[i].nbits)
- return raiseTestError("test_long_numbits",
- "wrong result for _PyLong_NumBits");
- if (sign != testcases[i].sign)
- return raiseTestError("test_long_numbits",
- "wrong result for _PyLong_Sign");
- }
- Py_INCREF(Py_None);
- return Py_None;
+ struct triple {
+ long input;
+ size_t nbits;
+ int sign;
+ } testcases[] = {{0, 0, 0},
+ {1L, 1, 1},
+ {-1L, 1, -1},
+ {2L, 2, 1},
+ {-2L, 2, -1},
+ {3L, 2, 1},
+ {-3L, 2, -1},
+ {4L, 3, 1},
+ {-4L, 3, -1},
+ {0x7fffL, 15, 1}, /* one Python long digit */
+ {-0x7fffL, 15, -1},
+ {0xffffL, 16, 1},
+ {-0xffffL, 16, -1},
+ {0xfffffffL, 28, 1},
+ {-0xfffffffL, 28, -1}};
+ int i;
+
+ for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
+ PyObject *plong = PyLong_FromLong(testcases[i].input);
+ size_t nbits = _PyLong_NumBits(plong);
+ int sign = _PyLong_Sign(plong);
+
+ Py_DECREF(plong);
+ if (nbits != testcases[i].nbits)
+ return raiseTestError("test_long_numbits",
+ "wrong result for _PyLong_NumBits");
+ if (sign != testcases[i].sign)
+ return raiseTestError("test_long_numbits",
+ "wrong result for _PyLong_Sign");
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Example passing NULLs to PyObject_Str(NULL). */
@@ -1328,38 +1328,38 @@ test_long_numbits(PyObject *self)
static PyObject *
test_null_strings(PyObject *self)
{
- PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL);
- PyObject *tuple = PyTuple_Pack(2, o1, o2);
- Py_XDECREF(o1);
- Py_XDECREF(o2);
- return tuple;
+ PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL);
+ PyObject *tuple = PyTuple_Pack(2, o1, o2);
+ Py_XDECREF(o1);
+ Py_XDECREF(o2);
+ return tuple;
}
static PyObject *
raise_exception(PyObject *self, PyObject *args)
{
- PyObject *exc;
- PyObject *exc_args, *v;
- int num_args, i;
-
- if (!PyArg_ParseTuple(args, "Oi:raise_exception",
- &exc, &num_args))
- return NULL;
-
- exc_args = PyTuple_New(num_args);
- if (exc_args == NULL)
- return NULL;
- for (i = 0; i < num_args; ++i) {
- v = PyLong_FromLong(i);
- if (v == NULL) {
- Py_DECREF(exc_args);
- return NULL;
- }
- PyTuple_SET_ITEM(exc_args, i, v);
- }
- PyErr_SetObject(exc, exc_args);
- Py_DECREF(exc_args);
- return NULL;
+ PyObject *exc;
+ PyObject *exc_args, *v;
+ int num_args, i;
+
+ if (!PyArg_ParseTuple(args, "Oi:raise_exception",
+ &exc, &num_args))
+ return NULL;
+
+ exc_args = PyTuple_New(num_args);
+ if (exc_args == NULL)
+ return NULL;
+ for (i = 0; i < num_args; ++i) {
+ v = PyLong_FromLong(i);
+ if (v == NULL) {
+ Py_DECREF(exc_args);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(exc_args, i, v);
+ }
+ PyErr_SetObject(exc, exc_args);
+ Py_DECREF(exc_args);
+ return NULL;
}
@@ -1367,23 +1367,23 @@ static int test_run_counter = 0;
static PyObject *
test_datetime_capi(PyObject *self, PyObject *args) {
- if (PyDateTimeAPI) {
- if (test_run_counter) {
- /* Probably regrtest.py -R */
- Py_RETURN_NONE;
- }
- else {
- PyErr_SetString(PyExc_AssertionError,
- "PyDateTime_CAPI somehow initialized");
- return NULL;
- }
- }
- test_run_counter++;
- PyDateTime_IMPORT;
- if (PyDateTimeAPI)
- Py_RETURN_NONE;
- else
- return NULL;
+ if (PyDateTimeAPI) {
+ if (test_run_counter) {
+ /* Probably regrtest.py -R */
+ Py_RETURN_NONE;
+ }
+ else {
+ PyErr_SetString(PyExc_AssertionError,
+ "PyDateTime_CAPI somehow initialized");
+ return NULL;
+ }
+ }
+ test_run_counter++;
+ PyDateTime_IMPORT;
+ if (PyDateTimeAPI)
+ Py_RETURN_NONE;
+ else
+ return NULL;
}
@@ -1401,14 +1401,14 @@ static PyThread_type_lock thread_done = NULL;
static int
_make_call(void *callable)
{
- PyObject *rc;
- int success;
- PyGILState_STATE s = PyGILState_Ensure();
- rc = PyObject_CallFunction((PyObject *)callable, "");
- success = (rc != NULL);
- Py_XDECREF(rc);
- PyGILState_Release(s);
- return success;
+ PyObject *rc;
+ int success;
+ PyGILState_STATE s = PyGILState_Ensure();
+ rc = PyObject_CallFunction((PyObject *)callable, "");
+ success = (rc != NULL);
+ Py_XDECREF(rc);
+ PyGILState_Release(s);
+ return success;
}
/* Same thing, but releases `thread_done` when it returns. This variant
@@ -1417,70 +1417,70 @@ _make_call(void *callable)
static void
_make_call_from_thread(void *callable)
{
- _make_call(callable);
- PyThread_release_lock(thread_done);
+ _make_call(callable);
+ PyThread_release_lock(thread_done);
}
static PyObject *
test_thread_state(PyObject *self, PyObject *args)
{
- PyObject *fn;
- int success = 1;
-
- if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
- return NULL;
-
- if (!PyCallable_Check(fn)) {
- PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
- fn->ob_type->tp_name);
- return NULL;
- }
-
- /* Ensure Python is set up for threading */
- PyEval_InitThreads();
- thread_done = PyThread_allocate_lock();
- if (thread_done == NULL)
- return PyErr_NoMemory();
- PyThread_acquire_lock(thread_done, 1);
-
- /* Start a new thread with our callback. */
- PyThread_start_new_thread(_make_call_from_thread, fn);
- /* Make the callback with the thread lock held by this thread */
- success &= _make_call(fn);
- /* Do it all again, but this time with the thread-lock released */
- Py_BEGIN_ALLOW_THREADS
- success &= _make_call(fn);
- PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
- Py_END_ALLOW_THREADS
-
- /* And once more with and without a thread
- XXX - should use a lock and work out exactly what we are trying
- to test <wink>
- */
- Py_BEGIN_ALLOW_THREADS
- PyThread_start_new_thread(_make_call_from_thread, fn);
- success &= _make_call(fn);
- PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
- Py_END_ALLOW_THREADS
-
- /* Release lock we acquired above. This is required on HP-UX. */
- PyThread_release_lock(thread_done);
-
- PyThread_free_lock(thread_done);
- if (!success)
- return NULL;
- Py_RETURN_NONE;
+ PyObject *fn;
+ int success = 1;
+
+ if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
+ return NULL;
+
+ if (!PyCallable_Check(fn)) {
+ PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
+ fn->ob_type->tp_name);
+ return NULL;
+ }
+
+ /* Ensure Python is set up for threading */
+ PyEval_InitThreads();
+ thread_done = PyThread_allocate_lock();
+ if (thread_done == NULL)
+ return PyErr_NoMemory();
+ PyThread_acquire_lock(thread_done, 1);
+
+ /* Start a new thread with our callback. */
+ PyThread_start_new_thread(_make_call_from_thread, fn);
+ /* Make the callback with the thread lock held by this thread */
+ success &= _make_call(fn);
+ /* Do it all again, but this time with the thread-lock released */
+ Py_BEGIN_ALLOW_THREADS
+ success &= _make_call(fn);
+ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
+ Py_END_ALLOW_THREADS
+
+ /* And once more with and without a thread
+ XXX - should use a lock and work out exactly what we are trying
+ to test <wink>
+ */
+ Py_BEGIN_ALLOW_THREADS
+ PyThread_start_new_thread(_make_call_from_thread, fn);
+ success &= _make_call(fn);
+ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
+ Py_END_ALLOW_THREADS
+
+ /* Release lock we acquired above. This is required on HP-UX. */
+ PyThread_release_lock(thread_done);
+
+ PyThread_free_lock(thread_done);
+ if (!success)
+ return NULL;
+ Py_RETURN_NONE;
}
/* test Py_AddPendingCalls using threads */
static int _pending_callback(void *arg)
{
- /* we assume the argument is callable object to which we own a reference */
- PyObject *callable = (PyObject *)arg;
- PyObject *r = PyObject_CallObject(callable, NULL);
- Py_DECREF(callable);
- Py_XDECREF(r);
- return r != NULL ? 0 : -1;
+ /* we assume the argument is callable object to which we own a reference */
+ PyObject *callable = (PyObject *)arg;
+ PyObject *r = PyObject_CallObject(callable, NULL);
+ Py_DECREF(callable);
+ Py_XDECREF(r);
+ return r != NULL ? 0 : -1;
}
/* The following requests n callbacks to _pending_callback. It can be
@@ -1488,25 +1488,25 @@ static int _pending_callback(void *arg)
*/
PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
{
- PyObject *callable;
- int r;
- if (PyArg_ParseTuple(arg, "O", &callable) == 0)
- return NULL;
-
- /* create the reference for the callbackwhile we hold the lock */
- Py_INCREF(callable);
-
- Py_BEGIN_ALLOW_THREADS
- r = Py_AddPendingCall(&_pending_callback, callable);
- Py_END_ALLOW_THREADS
-
- if (r<0) {
- Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
- Py_INCREF(Py_False);
- return Py_False;
- }
- Py_INCREF(Py_True);
- return Py_True;
+ PyObject *callable;
+ int r;
+ if (PyArg_ParseTuple(arg, "O", &callable) == 0)
+ return NULL;
+
+ /* create the reference for the callbackwhile we hold the lock */
+ Py_INCREF(callable);
+
+ Py_BEGIN_ALLOW_THREADS
+ r = Py_AddPendingCall(&_pending_callback, callable);
+ Py_END_ALLOW_THREADS
+
+ if (r<0) {
+ Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ Py_INCREF(Py_True);
+ return Py_True;
}
#endif
@@ -1514,40 +1514,40 @@ PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
static PyObject *
test_string_from_format(PyObject *self, PyObject *args)
{
- PyObject *result;
- char *msg;
-
-#define CHECK_1_FORMAT(FORMAT, TYPE) \
- result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \
- if (result == NULL) \
- return NULL; \
- if (strcmp(_PyUnicode_AsString(result), "1")) { \
- msg = FORMAT " failed at 1"; \
- goto Fail; \
- } \
- Py_DECREF(result)
-
- CHECK_1_FORMAT("%d", int);
- CHECK_1_FORMAT("%ld", long);
- /* The z width modifier was added in Python 2.5. */
- CHECK_1_FORMAT("%zd", Py_ssize_t);
-
- /* The u type code was added in Python 2.5. */
- CHECK_1_FORMAT("%u", unsigned int);
- CHECK_1_FORMAT("%lu", unsigned long);
- CHECK_1_FORMAT("%zu", size_t);
-
- /* "%lld" and "%llu" support added in Python 2.7. */
+ PyObject *result;
+ char *msg;
+
+#define CHECK_1_FORMAT(FORMAT, TYPE) \
+ result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \
+ if (result == NULL) \
+ return NULL; \
+ if (strcmp(_PyUnicode_AsString(result), "1")) { \
+ msg = FORMAT " failed at 1"; \
+ goto Fail; \
+ } \
+ Py_DECREF(result)
+
+ CHECK_1_FORMAT("%d", int);
+ CHECK_1_FORMAT("%ld", long);
+ /* The z width modifier was added in Python 2.5. */
+ CHECK_1_FORMAT("%zd", Py_ssize_t);
+
+ /* The u type code was added in Python 2.5. */
+ CHECK_1_FORMAT("%u", unsigned int);
+ CHECK_1_FORMAT("%lu", unsigned long);
+ CHECK_1_FORMAT("%zu", size_t);
+
+ /* "%lld" and "%llu" support added in Python 2.7. */
#ifdef HAVE_LONG_LONG
- CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG);
- CHECK_1_FORMAT("%lld", PY_LONG_LONG);
+ CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG);
+ CHECK_1_FORMAT("%lld", PY_LONG_LONG);
#endif
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
Fail:
- Py_XDECREF(result);
- return raiseTestError("test_string_from_format", msg);
+ Py_XDECREF(result);
+ return raiseTestError("test_string_from_format", msg);
#undef CHECK_1_FORMAT
}
@@ -1555,70 +1555,70 @@ test_string_from_format(PyObject *self, PyObject *args)
static PyObject *
test_unicode_compare_with_ascii(PyObject *self) {
- PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4);
- int result;
- if (py_s == NULL)
- return NULL;
- result = PyUnicode_CompareWithASCIIString(py_s, "str");
- Py_DECREF(py_s);
- if (!result) {
- PyErr_SetString(TestError, "Python string ending in NULL "
- "should not compare equal to c string.");
- return NULL;
- }
- Py_RETURN_NONE;
+ PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4);
+ int result;
+ if (py_s == NULL)
+ return NULL;
+ result = PyUnicode_CompareWithASCIIString(py_s, "str");
+ Py_DECREF(py_s);
+ if (!result) {
+ PyErr_SetString(TestError, "Python string ending in NULL "
+ "should not compare equal to c string.");
+ return NULL;
+ }
+ Py_RETURN_NONE;
};
/* This is here to provide a docstring for test_descr. */
static PyObject *
test_with_docstring(PyObject *self)
{
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/* Test PyOS_string_to_double. */
static PyObject *
test_string_to_double(PyObject *self) {
- double result;
- char *msg;
-
-#define CHECK_STRING(STR, expected) \
- result = PyOS_string_to_double(STR, NULL, NULL); \
- if (result == -1.0 && PyErr_Occurred()) \
- return NULL; \
- if (result != expected) { \
- msg = "conversion of " STR " to float failed"; \
- goto fail; \
- }
-
-#define CHECK_INVALID(STR) \
- result = PyOS_string_to_double(STR, NULL, NULL); \
- if (result == -1.0 && PyErr_Occurred()) { \
- if (PyErr_ExceptionMatches(PyExc_ValueError)) \
- PyErr_Clear(); \
- else \
- return NULL; \
- } \
- else { \
- msg = "conversion of " STR " didn't raise ValueError"; \
- goto fail; \
- }
-
- CHECK_STRING("0.1", 0.1);
- CHECK_STRING("1.234", 1.234);
- CHECK_STRING("-1.35", -1.35);
- CHECK_STRING(".1e01", 1.0);
- CHECK_STRING("2.e-2", 0.02);
-
- CHECK_INVALID(" 0.1");
- CHECK_INVALID("\t\n-3");
- CHECK_INVALID(".123 ");
- CHECK_INVALID("3\n");
- CHECK_INVALID("123abc");
-
- Py_RETURN_NONE;
+ double result;
+ char *msg;
+
+#define CHECK_STRING(STR, expected) \
+ result = PyOS_string_to_double(STR, NULL, NULL); \
+ if (result == -1.0 && PyErr_Occurred()) \
+ return NULL; \
+ if (result != expected) { \
+ msg = "conversion of " STR " to float failed"; \
+ goto fail; \
+ }
+
+#define CHECK_INVALID(STR) \
+ result = PyOS_string_to_double(STR, NULL, NULL); \
+ if (result == -1.0 && PyErr_Occurred()) { \
+ if (PyErr_ExceptionMatches(PyExc_ValueError)) \
+ PyErr_Clear(); \
+ else \
+ return NULL; \
+ } \
+ else { \
+ msg = "conversion of " STR " didn't raise ValueError"; \
+ goto fail; \
+ }
+
+ CHECK_STRING("0.1", 0.1);
+ CHECK_STRING("1.234", 1.234);
+ CHECK_STRING("-1.35", -1.35);
+ CHECK_STRING(".1e01", 1.0);
+ CHECK_STRING("2.e-2", 0.02);
+
+ CHECK_INVALID(" 0.1");
+ CHECK_INVALID("\t\n-3");
+ CHECK_INVALID(".123 ");
+ CHECK_INVALID("3\n");
+ CHECK_INVALID("123abc");
+
+ Py_RETURN_NONE;
fail:
- return raiseTestError("test_string_to_double", msg);
+ return raiseTestError("test_string_to_double", msg);
#undef CHECK_STRING
#undef CHECK_INVALID
}
@@ -1635,143 +1635,143 @@ capsule_destructor_call_count = 0;
static void
capsule_destructor(PyObject *o) {
- capsule_destructor_call_count++;
- if (PyCapsule_GetContext(o) != capsule_context) {
- capsule_error = "context did not match in destructor!";
- } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
- capsule_error = "destructor did not match in destructor! (woah!)";
- } else if (PyCapsule_GetName(o) != capsule_name) {
- capsule_error = "name did not match in destructor!";
- } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
- capsule_error = "pointer did not match in destructor!";
- }
+ capsule_destructor_call_count++;
+ if (PyCapsule_GetContext(o) != capsule_context) {
+ capsule_error = "context did not match in destructor!";
+ } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
+ capsule_error = "destructor did not match in destructor! (woah!)";
+ } else if (PyCapsule_GetName(o) != capsule_name) {
+ capsule_error = "name did not match in destructor!";
+ } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
+ capsule_error = "pointer did not match in destructor!";
+ }
}
typedef struct {
- char *name;
- char *module;
- char *attribute;
+ char *name;
+ char *module;
+ char *attribute;
} known_capsule;
static PyObject *
test_capsule(PyObject *self, PyObject *args)
{
- PyObject *object;
- const char *error = NULL;
- void *pointer;
- void *pointer2;
- known_capsule known_capsules[] = {
- #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
- KNOWN_CAPSULE("_socket", "CAPI"),
- KNOWN_CAPSULE("_curses", "_C_API"),
- KNOWN_CAPSULE("datetime", "datetime_CAPI"),
- { NULL, NULL },
- };
- known_capsule *known = &known_capsules[0];
+ PyObject *object;
+ const char *error = NULL;
+ void *pointer;
+ void *pointer2;
+ known_capsule known_capsules[] = {
+ #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
+ KNOWN_CAPSULE("_socket", "CAPI"),
+ KNOWN_CAPSULE("_curses", "_C_API"),
+ KNOWN_CAPSULE("datetime", "datetime_CAPI"),
+ { NULL, NULL },
+ };
+ known_capsule *known = &known_capsules[0];
#define FAIL(x) { error = (x); goto exit; }
#define CHECK_DESTRUCTOR \
- if (capsule_error) { \
- FAIL(capsule_error); \
- } \
- else if (!capsule_destructor_call_count) { \
- FAIL("destructor not called!"); \
- } \
- capsule_destructor_call_count = 0; \
-
- object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
- PyCapsule_SetContext(object, capsule_context);
- capsule_destructor(object);
- CHECK_DESTRUCTOR;
- Py_DECREF(object);
- CHECK_DESTRUCTOR;
-
- object = PyCapsule_New(known, "ignored", NULL);
- PyCapsule_SetPointer(object, capsule_pointer);
- PyCapsule_SetName(object, capsule_name);
- PyCapsule_SetDestructor(object, capsule_destructor);
- PyCapsule_SetContext(object, capsule_context);
- capsule_destructor(object);
- CHECK_DESTRUCTOR;
- /* intentionally access using the wrong name */
- pointer2 = PyCapsule_GetPointer(object, "the wrong name");
- if (!PyErr_Occurred()) {
- FAIL("PyCapsule_GetPointer should have failed but did not!");
- }
- PyErr_Clear();
- if (pointer2) {
- if (pointer2 == capsule_pointer) {
- FAIL("PyCapsule_GetPointer should not have"
- " returned the internal pointer!");
- } else {
- FAIL("PyCapsule_GetPointer should have "
- "returned NULL pointer but did not!");
- }
- }
- PyCapsule_SetDestructor(object, NULL);
- Py_DECREF(object);
- if (capsule_destructor_call_count) {
- FAIL("destructor called when it should not have been!");
- }
-
- for (known = &known_capsules[0]; known->module != NULL; known++) {
- /* yeah, ordinarily I wouldn't do this either,
- but it's fine for this test harness.
- */
- static char buffer[256];
+ if (capsule_error) { \
+ FAIL(capsule_error); \
+ } \
+ else if (!capsule_destructor_call_count) { \
+ FAIL("destructor not called!"); \
+ } \
+ capsule_destructor_call_count = 0; \
+
+ object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
+ PyCapsule_SetContext(object, capsule_context);
+ capsule_destructor(object);
+ CHECK_DESTRUCTOR;
+ Py_DECREF(object);
+ CHECK_DESTRUCTOR;
+
+ object = PyCapsule_New(known, "ignored", NULL);
+ PyCapsule_SetPointer(object, capsule_pointer);
+ PyCapsule_SetName(object, capsule_name);
+ PyCapsule_SetDestructor(object, capsule_destructor);
+ PyCapsule_SetContext(object, capsule_context);
+ capsule_destructor(object);
+ CHECK_DESTRUCTOR;
+ /* intentionally access using the wrong name */
+ pointer2 = PyCapsule_GetPointer(object, "the wrong name");
+ if (!PyErr_Occurred()) {
+ FAIL("PyCapsule_GetPointer should have failed but did not!");
+ }
+ PyErr_Clear();
+ if (pointer2) {
+ if (pointer2 == capsule_pointer) {
+ FAIL("PyCapsule_GetPointer should not have"
+ " returned the internal pointer!");
+ } else {
+ FAIL("PyCapsule_GetPointer should have "
+ "returned NULL pointer but did not!");
+ }
+ }
+ PyCapsule_SetDestructor(object, NULL);
+ Py_DECREF(object);
+ if (capsule_destructor_call_count) {
+ FAIL("destructor called when it should not have been!");
+ }
+
+ for (known = &known_capsules[0]; known->module != NULL; known++) {
+ /* yeah, ordinarily I wouldn't do this either,
+ but it's fine for this test harness.
+ */
+ static char buffer[256];
#undef FAIL
#define FAIL(x) \
- { \
- sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
- x, known->module, known->attribute); \
- error = buffer; \
- goto exit; \
- } \
-
- PyObject *module = PyImport_ImportModule(known->module);
- if (module) {
- pointer = PyCapsule_Import(known->name, 0);
- if (!pointer) {
- Py_DECREF(module);
- FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
- }
- object = PyObject_GetAttrString(module, known->attribute);
- if (!object) {
- Py_DECREF(module);
- return NULL;
- }
- pointer2 = PyCapsule_GetPointer(object,
- "weebles wobble but they don't fall down");
- if (!PyErr_Occurred()) {
- Py_DECREF(object);
- Py_DECREF(module);
- FAIL("PyCapsule_GetPointer should have failed but did not!");
- }
- PyErr_Clear();
- if (pointer2) {
- Py_DECREF(module);
- Py_DECREF(object);
- if (pointer2 == pointer) {
- FAIL("PyCapsule_GetPointer should not have"
- " returned its internal pointer!");
- } else {
- FAIL("PyCapsule_GetPointer should have"
- " returned NULL pointer but did not!");
- }
- }
- Py_DECREF(object);
- Py_DECREF(module);
- }
- else
- PyErr_Clear();
- }
+ { \
+ sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
+ x, known->module, known->attribute); \
+ error = buffer; \
+ goto exit; \
+ } \
+
+ PyObject *module = PyImport_ImportModule(known->module);
+ if (module) {
+ pointer = PyCapsule_Import(known->name, 0);
+ if (!pointer) {
+ Py_DECREF(module);
+ FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
+ }
+ object = PyObject_GetAttrString(module, known->attribute);
+ if (!object) {
+ Py_DECREF(module);
+ return NULL;
+ }
+ pointer2 = PyCapsule_GetPointer(object,
+ "weebles wobble but they don't fall down");
+ if (!PyErr_Occurred()) {
+ Py_DECREF(object);
+ Py_DECREF(module);
+ FAIL("PyCapsule_GetPointer should have failed but did not!");
+ }
+ PyErr_Clear();
+ if (pointer2) {
+ Py_DECREF(module);
+ Py_DECREF(object);
+ if (pointer2 == pointer) {
+ FAIL("PyCapsule_GetPointer should not have"
+ " returned its internal pointer!");
+ } else {
+ FAIL("PyCapsule_GetPointer should have"
+ " returned NULL pointer but did not!");
+ }
+ }
+ Py_DECREF(object);
+ Py_DECREF(module);
+ }
+ else
+ PyErr_Clear();
+ }
exit:
- if (error) {
- return raiseTestError("test_capsule", error);
- }
- Py_RETURN_NONE;
+ if (error) {
+ return raiseTestError("test_capsule", error);
+ }
+ Py_RETURN_NONE;
#undef FAIL
}
@@ -1779,112 +1779,112 @@ test_capsule(PyObject *self, PyObject *args)
/* Profiling of integer performance */
static void print_delta(int test, struct timeval *s, struct timeval *e)
{
- e->tv_sec -= s->tv_sec;
- e->tv_usec -= s->tv_usec;
- if (e->tv_usec < 0) {
- e->tv_sec -=1;
- e->tv_usec += 1000000;
- }
- printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
+ e->tv_sec -= s->tv_sec;
+ e->tv_usec -= s->tv_usec;
+ if (e->tv_usec < 0) {
+ e->tv_sec -=1;
+ e->tv_usec += 1000000;
+ }
+ printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
}
static PyObject *
profile_int(PyObject *self, PyObject* args)
{
- int i, k;
- struct timeval start, stop;
- PyObject *single, **multiple, *op1, *result;
-
- /* Test 1: Allocate and immediately deallocate
- many small integers */
- gettimeofday(&start, NULL);
- for(k=0; k < 20000; k++)
- for(i=0; i < 1000; i++) {
- single = PyLong_FromLong(i);
- Py_DECREF(single);
- }
- gettimeofday(&stop, NULL);
- print_delta(1, &start, &stop);
-
- /* Test 2: Allocate and immediately deallocate
- many large integers */
- gettimeofday(&start, NULL);
- for(k=0; k < 20000; k++)
- for(i=0; i < 1000; i++) {
- single = PyLong_FromLong(i+1000000);
- Py_DECREF(single);
- }
- gettimeofday(&stop, NULL);
- print_delta(2, &start, &stop);
-
- /* Test 3: Allocate a few integers, then release
- them all simultaneously. */
- multiple = malloc(sizeof(PyObject*) * 1000);
- gettimeofday(&start, NULL);
- for(k=0; k < 20000; k++) {
- for(i=0; i < 1000; i++) {
- multiple[i] = PyLong_FromLong(i+1000000);
- }
- for(i=0; i < 1000; i++) {
- Py_DECREF(multiple[i]);
- }
- }
- gettimeofday(&stop, NULL);
- print_delta(3, &start, &stop);
-
- /* Test 4: Allocate many integers, then release
- them all simultaneously. */
- multiple = malloc(sizeof(PyObject*) * 1000000);
- gettimeofday(&start, NULL);
- for(k=0; k < 20; k++) {
- for(i=0; i < 1000000; i++) {
- multiple[i] = PyLong_FromLong(i+1000000);
- }
- for(i=0; i < 1000000; i++) {
- Py_DECREF(multiple[i]);
- }
- }
- gettimeofday(&stop, NULL);
- print_delta(4, &start, &stop);
-
- /* Test 5: Allocate many integers < 32000 */
- multiple = malloc(sizeof(PyObject*) * 1000000);
- gettimeofday(&start, NULL);
- for(k=0; k < 10; k++) {
- for(i=0; i < 1000000; i++) {
- multiple[i] = PyLong_FromLong(i+1000);
- }
- for(i=0; i < 1000000; i++) {
- Py_DECREF(multiple[i]);
- }
- }
- gettimeofday(&stop, NULL);
- print_delta(5, &start, &stop);
-
- /* Test 6: Perform small int addition */
- op1 = PyLong_FromLong(1);
- gettimeofday(&start, NULL);
- for(i=0; i < 10000000; i++) {
- result = PyNumber_Add(op1, op1);
- Py_DECREF(result);
- }
- gettimeofday(&stop, NULL);
- Py_DECREF(op1);
- print_delta(6, &start, &stop);
-
- /* Test 7: Perform medium int addition */
- op1 = PyLong_FromLong(1000);
- gettimeofday(&start, NULL);
- for(i=0; i < 10000000; i++) {
- result = PyNumber_Add(op1, op1);
- Py_DECREF(result);
- }
- gettimeofday(&stop, NULL);
- Py_DECREF(op1);
- print_delta(7, &start, &stop);
-
- Py_INCREF(Py_None);
- return Py_None;
+ int i, k;
+ struct timeval start, stop;
+ PyObject *single, **multiple, *op1, *result;
+
+ /* Test 1: Allocate and immediately deallocate
+ many small integers */
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20000; k++)
+ for(i=0; i < 1000; i++) {
+ single = PyLong_FromLong(i);
+ Py_DECREF(single);
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(1, &start, &stop);
+
+ /* Test 2: Allocate and immediately deallocate
+ many large integers */
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20000; k++)
+ for(i=0; i < 1000; i++) {
+ single = PyLong_FromLong(i+1000000);
+ Py_DECREF(single);
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(2, &start, &stop);
+
+ /* Test 3: Allocate a few integers, then release
+ them all simultaneously. */
+ multiple = malloc(sizeof(PyObject*) * 1000);
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20000; k++) {
+ for(i=0; i < 1000; i++) {
+ multiple[i] = PyLong_FromLong(i+1000000);
+ }
+ for(i=0; i < 1000; i++) {
+ Py_DECREF(multiple[i]);
+ }
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(3, &start, &stop);
+
+ /* Test 4: Allocate many integers, then release
+ them all simultaneously. */
+ multiple = malloc(sizeof(PyObject*) * 1000000);
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20; k++) {
+ for(i=0; i < 1000000; i++) {
+ multiple[i] = PyLong_FromLong(i+1000000);
+ }
+ for(i=0; i < 1000000; i++) {
+ Py_DECREF(multiple[i]);
+ }
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(4, &start, &stop);
+
+ /* Test 5: Allocate many integers < 32000 */
+ multiple = malloc(sizeof(PyObject*) * 1000000);
+ gettimeofday(&start, NULL);
+ for(k=0; k < 10; k++) {
+ for(i=0; i < 1000000; i++) {
+ multiple[i] = PyLong_FromLong(i+1000);
+ }
+ for(i=0; i < 1000000; i++) {
+ Py_DECREF(multiple[i]);
+ }
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(5, &start, &stop);
+
+ /* Test 6: Perform small int addition */
+ op1 = PyLong_FromLong(1);
+ gettimeofday(&start, NULL);
+ for(i=0; i < 10000000; i++) {
+ result = PyNumber_Add(op1, op1);
+ Py_DECREF(result);
+ }
+ gettimeofday(&stop, NULL);
+ Py_DECREF(op1);
+ print_delta(6, &start, &stop);
+
+ /* Test 7: Perform medium int addition */
+ op1 = PyLong_FromLong(1000);
+ gettimeofday(&start, NULL);
+ for(i=0; i < 10000000; i++) {
+ result = PyNumber_Add(op1, op1);
+ Py_DECREF(result);
+ }
+ gettimeofday(&stop, NULL);
+ Py_DECREF(op1);
+ print_delta(7, &start, &stop);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -1892,40 +1892,40 @@ profile_int(PyObject *self, PyObject* args)
static PyObject *
traceback_print(PyObject *self, PyObject *args)
{
- PyObject *file;
- PyObject *traceback;
- int result;
-
- if (!PyArg_ParseTuple(args, "OO:traceback_print",
- &traceback, &file))
- return NULL;
-
- result = PyTraceBack_Print(traceback, file);
- if (result < 0)
- return NULL;
- Py_RETURN_NONE;
+ PyObject *file;
+ PyObject *traceback;
+ int result;
+
+ if (!PyArg_ParseTuple(args, "OO:traceback_print",
+ &traceback, &file))
+ return NULL;
+
+ result = PyTraceBack_Print(traceback, file);
+ if (result < 0)
+ return NULL;
+ Py_RETURN_NONE;
}
/* To test the format of exceptions as printed out. */
static PyObject *
exception_print(PyObject *self, PyObject *args)
{
- PyObject *value;
- PyObject *tb;
+ PyObject *value;
+ PyObject *tb;
- if (!PyArg_ParseTuple(args, "O:exception_print",
- &value))
- return NULL;
- if (!PyExceptionInstance_Check(value)) {
- PyErr_Format(PyExc_TypeError, "an exception instance is required");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O:exception_print",
+ &value))
+ return NULL;
+ if (!PyExceptionInstance_Check(value)) {
+ PyErr_Format(PyExc_TypeError, "an exception instance is required");
+ return NULL;
+ }
- tb = PyException_GetTraceback(value);
- PyErr_Display((PyObject *) Py_TYPE(value), value, tb);
- Py_XDECREF(tb);
+ tb = PyException_GetTraceback(value);
+ PyErr_Display((PyObject *) Py_TYPE(value), value, tb);
+ Py_XDECREF(tb);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
@@ -1935,8 +1935,8 @@ exception_print(PyObject *self, PyObject *args)
static PyObject *
raise_memoryerror(PyObject *self)
{
- PyErr_NoMemory();
- return NULL;
+ PyErr_NoMemory();
+ return NULL;
}
/* Issue 6012 */
@@ -1944,45 +1944,45 @@ static PyObject *str1, *str2;
static int
failing_converter(PyObject *obj, void *arg)
{
- /* Clone str1, then let the conversion fail. */
- assert(str1);
- str2 = str1;
- Py_INCREF(str2);
- return 0;
+ /* Clone str1, then let the conversion fail. */
+ assert(str1);
+ str2 = str1;
+ Py_INCREF(str2);
+ return 0;
}
static PyObject*
argparsing(PyObject *o, PyObject *args)
{
- PyObject *res;
- str1 = str2 = NULL;
- if (!PyArg_ParseTuple(args, "O&O&",
- PyUnicode_FSConverter, &str1,
- failing_converter, &str2)) {
- if (!str2)
- /* argument converter not called? */
- return NULL;
- /* Should be 1 */
- res = PyLong_FromLong(Py_REFCNT(str2));
- Py_DECREF(str2);
- PyErr_Clear();
- return res;
- }
- Py_RETURN_NONE;
+ PyObject *res;
+ str1 = str2 = NULL;
+ if (!PyArg_ParseTuple(args, "O&O&",
+ PyUnicode_FSConverter, &str1,
+ failing_converter, &str2)) {
+ if (!str2)
+ /* argument converter not called? */
+ return NULL;
+ /* Should be 1 */
+ res = PyLong_FromLong(Py_REFCNT(str2));
+ Py_DECREF(str2);
+ PyErr_Clear();
+ return res;
+ }
+ Py_RETURN_NONE;
}
/* To test that the result of PyCode_NewEmpty has the right members. */
static PyObject *
code_newempty(PyObject *self, PyObject *args)
{
- const char *filename;
- const char *funcname;
- int firstlineno;
+ const char *filename;
+ const char *funcname;
+ int firstlineno;
- if (!PyArg_ParseTuple(args, "ssi:code_newempty",
- &filename, &funcname, &firstlineno))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ssi:code_newempty",
+ &filename, &funcname, &firstlineno))
+ return NULL;
- return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
+ return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
}
/* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
@@ -1990,302 +1990,302 @@ code_newempty(PyObject *self, PyObject *args)
static PyObject *
make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
{
- const char *name;
- const char *doc = NULL;
- PyObject *base = NULL;
- PyObject *dict = NULL;
+ const char *name;
+ const char *doc = NULL;
+ PyObject *base = NULL;
+ PyObject *dict = NULL;
- static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
+ static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwargs,
- "s|sOO:make_exception_with_doc", kwlist,
- &name, &doc, &base, &dict))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs,
+ "s|sOO:make_exception_with_doc", kwlist,
+ &name, &doc, &base, &dict))
+ return NULL;
- return PyErr_NewExceptionWithDoc(name, doc, base, dict);
+ return PyErr_NewExceptionWithDoc(name, doc, base, dict);
}
static PyMethodDef TestMethods[] = {
- {"raise_exception", raise_exception, METH_VARARGS},
- {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS},
- {"test_config", (PyCFunction)test_config, METH_NOARGS},
- {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
- {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
- {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
- {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
- {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
- {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
- {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
- METH_NOARGS},
- {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
- {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
- {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
- {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS},
- {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
- {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
- {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
- PyDoc_STR("This is a pretty normal docstring.")},
- {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS},
- {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS},
- {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
- {"getargs_tuple", getargs_tuple, METH_VARARGS},
- {"getargs_keywords", (PyCFunction)getargs_keywords,
- METH_VARARGS|METH_KEYWORDS},
- {"getargs_b", getargs_b, METH_VARARGS},
- {"getargs_B", getargs_B, METH_VARARGS},
- {"getargs_h", getargs_h, METH_VARARGS},
- {"getargs_H", getargs_H, METH_VARARGS},
- {"getargs_I", getargs_I, METH_VARARGS},
- {"getargs_k", getargs_k, METH_VARARGS},
- {"getargs_i", getargs_i, METH_VARARGS},
- {"getargs_l", getargs_l, METH_VARARGS},
- {"getargs_n", getargs_n, METH_VARARGS},
+ {"raise_exception", raise_exception, METH_VARARGS},
+ {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS},
+ {"test_config", (PyCFunction)test_config, METH_NOARGS},
+ {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
+ {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
+ {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
+ {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
+ {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
+ {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
+ {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
+ METH_NOARGS},
+ {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
+ {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
+ {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
+ {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS},
+ {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
+ {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
+ {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
+ PyDoc_STR("This is a pretty normal docstring.")},
+ {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS},
+ {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS},
+ {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
+ {"getargs_tuple", getargs_tuple, METH_VARARGS},
+ {"getargs_keywords", (PyCFunction)getargs_keywords,
+ METH_VARARGS|METH_KEYWORDS},
+ {"getargs_b", getargs_b, METH_VARARGS},
+ {"getargs_B", getargs_B, METH_VARARGS},
+ {"getargs_h", getargs_h, METH_VARARGS},
+ {"getargs_H", getargs_H, METH_VARARGS},
+ {"getargs_I", getargs_I, METH_VARARGS},
+ {"getargs_k", getargs_k, METH_VARARGS},
+ {"getargs_i", getargs_i, METH_VARARGS},
+ {"getargs_l", getargs_l, METH_VARARGS},
+ {"getargs_n", getargs_n, METH_VARARGS},
#ifdef HAVE_LONG_LONG
- {"getargs_L", getargs_L, METH_VARARGS},
- {"getargs_K", getargs_K, METH_VARARGS},
- {"test_longlong_api", test_longlong_api, METH_NOARGS},
- {"test_long_long_and_overflow",
- (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
- {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
- {"codec_incrementalencoder",
- (PyCFunction)codec_incrementalencoder, METH_VARARGS},
- {"codec_incrementaldecoder",
- (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
+ {"getargs_L", getargs_L, METH_VARARGS},
+ {"getargs_K", getargs_K, METH_VARARGS},
+ {"test_longlong_api", test_longlong_api, METH_NOARGS},
+ {"test_long_long_and_overflow",
+ (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
+ {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
+ {"codec_incrementalencoder",
+ (PyCFunction)codec_incrementalencoder, METH_VARARGS},
+ {"codec_incrementaldecoder",
+ (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
#endif
- {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS},
- {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
- {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS},
- {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
+ {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS},
+ {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
+ {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS},
+ {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
#ifdef WITH_THREAD
- {"_test_thread_state", test_thread_state, METH_VARARGS},
- {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
+ {"_test_thread_state", test_thread_state, METH_VARARGS},
+ {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
#endif
#ifdef HAVE_GETTIMEOFDAY
- {"profile_int", profile_int, METH_NOARGS},
+ {"profile_int", profile_int, METH_NOARGS},
#endif
- {"traceback_print", traceback_print, METH_VARARGS},
- {"exception_print", exception_print, METH_VARARGS},
- {"argparsing", argparsing, METH_VARARGS},
- {"code_newempty", code_newempty, METH_VARARGS},
- {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
- METH_VARARGS | METH_KEYWORDS},
- {NULL, NULL} /* sentinel */
+ {"traceback_print", traceback_print, METH_VARARGS},
+ {"exception_print", exception_print, METH_VARARGS},
+ {"argparsing", argparsing, METH_VARARGS},
+ {"code_newempty", code_newempty, METH_VARARGS},
+ {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
+ METH_VARARGS | METH_KEYWORDS},
+ {NULL, NULL} /* sentinel */
};
#define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
typedef struct {
- char bool_member;
- char byte_member;
- unsigned char ubyte_member;
- short short_member;
- unsigned short ushort_member;
- int int_member;
- unsigned int uint_member;
- long long_member;
- unsigned long ulong_member;
- Py_ssize_t pyssizet_member;
- float float_member;
- double double_member;
- char inplace_member[6];
+ char bool_member;
+ char byte_member;
+ unsigned char ubyte_member;
+ short short_member;
+ unsigned short ushort_member;
+ int int_member;
+ unsigned int uint_member;
+ long long_member;
+ unsigned long ulong_member;
+ Py_ssize_t pyssizet_member;
+ float float_member;
+ double double_member;
+ char inplace_member[6];
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG longlong_member;
- unsigned PY_LONG_LONG ulonglong_member;
+ PY_LONG_LONG longlong_member;
+ unsigned PY_LONG_LONG ulonglong_member;
#endif
} all_structmembers;
typedef struct {
PyObject_HEAD
- all_structmembers structmembers;
+ all_structmembers structmembers;
} test_structmembers;
static struct PyMemberDef test_members[] = {
- {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
- {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
- {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
- {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
- {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
- {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
- {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
- {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
- {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
- {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL},
- {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
- {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
- {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
+ {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
+ {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
+ {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
+ {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
+ {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
+ {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
+ {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
+ {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
+ {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
+ {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL},
+ {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
+ {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
+ {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
#ifdef HAVE_LONG_LONG
- {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
- {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
+ {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
+ {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
#endif
- {NULL}
+ {NULL}
};
static PyObject *
test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
- static char *keywords[] = {
- "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
- "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET",
- "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
+ static char *keywords[] = {
+ "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
+ "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET",
+ "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
#ifdef HAVE_LONG_LONG
- "T_LONGLONG", "T_ULONGLONG",
+ "T_LONGLONG", "T_ULONGLONG",
#endif
- NULL};
- static char *fmt = "|bbBhHiIlknfds#"
+ NULL};
+ static char *fmt = "|bbBhHiIlknfds#"
#ifdef HAVE_LONG_LONG
- "LK"
+ "LK"
#endif
- ;
- test_structmembers *ob;
- const char *s = NULL;
- Py_ssize_t string_len = 0;
- ob = PyObject_New(test_structmembers, type);
- if (ob == NULL)
- return NULL;
- memset(&ob->structmembers, 0, sizeof(all_structmembers));
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
- &ob->structmembers.bool_member,
- &ob->structmembers.byte_member,
- &ob->structmembers.ubyte_member,
- &ob->structmembers.short_member,
- &ob->structmembers.ushort_member,
- &ob->structmembers.int_member,
- &ob->structmembers.uint_member,
- &ob->structmembers.long_member,
- &ob->structmembers.ulong_member,
- &ob->structmembers.pyssizet_member,
- &ob->structmembers.float_member,
- &ob->structmembers.double_member,
- &s, &string_len
+ ;
+ test_structmembers *ob;
+ const char *s = NULL;
+ Py_ssize_t string_len = 0;
+ ob = PyObject_New(test_structmembers, type);
+ if (ob == NULL)
+ return NULL;
+ memset(&ob->structmembers, 0, sizeof(all_structmembers));
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
+ &ob->structmembers.bool_member,
+ &ob->structmembers.byte_member,
+ &ob->structmembers.ubyte_member,
+ &ob->structmembers.short_member,
+ &ob->structmembers.ushort_member,
+ &ob->structmembers.int_member,
+ &ob->structmembers.uint_member,
+ &ob->structmembers.long_member,
+ &ob->structmembers.ulong_member,
+ &ob->structmembers.pyssizet_member,
+ &ob->structmembers.float_member,
+ &ob->structmembers.double_member,
+ &s, &string_len
#ifdef HAVE_LONG_LONG
- , &ob->structmembers.longlong_member,
- &ob->structmembers.ulonglong_member
+ , &ob->structmembers.longlong_member,
+ &ob->structmembers.ulonglong_member
#endif
- )) {
- Py_DECREF(ob);
- return NULL;
- }
- if (s != NULL) {
- if (string_len > 5) {
- Py_DECREF(ob);
- PyErr_SetString(PyExc_ValueError, "string too long");
- return NULL;
- }
- strcpy(ob->structmembers.inplace_member, s);
- }
- else {
- strcpy(ob->structmembers.inplace_member, "");
- }
- return (PyObject *)ob;
+ )) {
+ Py_DECREF(ob);
+ return NULL;
+ }
+ if (s != NULL) {
+ if (string_len > 5) {
+ Py_DECREF(ob);
+ PyErr_SetString(PyExc_ValueError, "string too long");
+ return NULL;
+ }
+ strcpy(ob->structmembers.inplace_member, s);
+ }
+ else {
+ strcpy(ob->structmembers.inplace_member, "");
+ }
+ return (PyObject *)ob;
}
static void
test_structmembers_free(PyObject *ob)
{
- PyObject_FREE(ob);
+ PyObject_FREE(ob);
}
static PyTypeObject test_structmembersType = {
PyVarObject_HEAD_INIT(NULL, 0)
- "test_structmembersType",
- sizeof(test_structmembers), /* tp_basicsize */
- 0, /* tp_itemsize */
- test_structmembers_free, /* destructor tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- 0, /* tp_flags */
- "Type containing all structmember types",
- 0, /* traverseproc tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- test_members, /* tp_members */
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- test_structmembers_new, /* tp_new */
+ "test_structmembersType",
+ sizeof(test_structmembers), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ test_structmembers_free, /* destructor tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ 0, /* tp_flags */
+ "Type containing all structmember types",
+ 0, /* traverseproc tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ test_members, /* tp_members */
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ test_structmembers_new, /* tp_new */
};
static struct PyModuleDef _testcapimodule = {
- PyModuleDef_HEAD_INIT,
- "_testcapi",
- NULL,
- -1,
- TestMethods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_testcapi",
+ NULL,
+ -1,
+ TestMethods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__testcapi(void)
{
- PyObject *m;
-
- m = PyModule_Create(&_testcapimodule);
- if (m == NULL)
- return NULL;
-
- Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
- Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type;
-
- Py_TYPE(&test_structmembersType)=&PyType_Type;
- Py_INCREF(&test_structmembersType);
- /* don't use a name starting with "test", since we don't want
- test_capi to automatically call this */
- PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
-
- PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
- PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
- PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
- PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
- PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
- PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
- PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
- PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
- PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
- PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
- PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
- PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
- PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
- PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
- PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
- PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
- PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
- PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
- PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
- PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
- PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
- PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head)));
- Py_INCREF(&PyInstanceMethod_Type);
- PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
-
- TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
- Py_INCREF(TestError);
- PyModule_AddObject(m, "error", TestError);
- return m;
+ PyObject *m;
+
+ m = PyModule_Create(&_testcapimodule);
+ if (m == NULL)
+ return NULL;
+
+ Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
+ Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type;
+
+ Py_TYPE(&test_structmembersType)=&PyType_Type;
+ Py_INCREF(&test_structmembersType);
+ /* don't use a name starting with "test", since we don't want
+ test_capi to automatically call this */
+ PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
+
+ PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
+ PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
+ PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
+ PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
+ PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
+ PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
+ PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
+ PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
+ PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
+ PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
+ PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
+ PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
+ PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
+ PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
+ PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
+ PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
+ PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
+ PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
+ PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
+ PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
+ PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
+ PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head)));
+ Py_INCREF(&PyInstanceMethod_Type);
+ PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
+
+ TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
+ Py_INCREF(TestError);
+ PyModule_AddObject(m, "error", TestError);
+ return m;
}
diff --git a/Modules/_threadmodule.c b/Modules/_threadmodule.c
index 5a7cf79..a94b199 100644
--- a/Modules/_threadmodule.c
+++ b/Modules/_threadmodule.c
@@ -19,68 +19,68 @@ static long nb_threads = 0;
/* Lock objects */
typedef struct {
- PyObject_HEAD
- PyThread_type_lock lock_lock;
- PyObject *in_weakreflist;
+ PyObject_HEAD
+ PyThread_type_lock lock_lock;
+ PyObject *in_weakreflist;
} lockobject;
static void
lock_dealloc(lockobject *self)
{
- if (self->in_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) self);
- if (self->lock_lock != NULL) {
- /* Unlock the lock so it's safe to free it */
- PyThread_acquire_lock(self->lock_lock, 0);
- PyThread_release_lock(self->lock_lock);
-
- PyThread_free_lock(self->lock_lock);
- }
- PyObject_Del(self);
+ if (self->in_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) self);
+ if (self->lock_lock != NULL) {
+ /* Unlock the lock so it's safe to free it */
+ PyThread_acquire_lock(self->lock_lock, 0);
+ PyThread_release_lock(self->lock_lock);
+
+ PyThread_free_lock(self->lock_lock);
+ }
+ PyObject_Del(self);
}
static PyObject *
lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds)
{
- char *kwlist[] = {"blocking", "timeout", NULL};
- int blocking = 1;
- double timeout = -1;
- PY_TIMEOUT_T microseconds;
- int r;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
- &blocking, &timeout))
- return NULL;
-
- if (!blocking && timeout != -1) {
- PyErr_SetString(PyExc_ValueError, "can't specify a timeout "
- "for a non-blocking call");
- return NULL;
- }
- if (timeout < 0 && timeout != -1) {
- PyErr_SetString(PyExc_ValueError, "timeout value must be "
- "strictly positive");
- return NULL;
- }
- if (!blocking)
- microseconds = 0;
- else if (timeout == -1)
- microseconds = -1;
- else {
- timeout *= 1e6;
- if (timeout >= (double) PY_TIMEOUT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout value is too large");
- return NULL;
- }
- microseconds = (PY_TIMEOUT_T) timeout;
- }
-
- Py_BEGIN_ALLOW_THREADS
- r = PyThread_acquire_lock_timed(self->lock_lock, microseconds);
- Py_END_ALLOW_THREADS
-
- return PyBool_FromLong(r);
+ char *kwlist[] = {"blocking", "timeout", NULL};
+ int blocking = 1;
+ double timeout = -1;
+ PY_TIMEOUT_T microseconds;
+ int r;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
+ &blocking, &timeout))
+ return NULL;
+
+ if (!blocking && timeout != -1) {
+ PyErr_SetString(PyExc_ValueError, "can't specify a timeout "
+ "for a non-blocking call");
+ return NULL;
+ }
+ if (timeout < 0 && timeout != -1) {
+ PyErr_SetString(PyExc_ValueError, "timeout value must be "
+ "strictly positive");
+ return NULL;
+ }
+ if (!blocking)
+ microseconds = 0;
+ else if (timeout == -1)
+ microseconds = -1;
+ else {
+ timeout *= 1e6;
+ if (timeout >= (double) PY_TIMEOUT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout value is too large");
+ return NULL;
+ }
+ microseconds = (PY_TIMEOUT_T) timeout;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ r = PyThread_acquire_lock_timed(self->lock_lock, microseconds);
+ Py_END_ALLOW_THREADS
+
+ return PyBool_FromLong(r);
}
PyDoc_STRVAR(acquire_doc,
@@ -97,16 +97,16 @@ The blocking operation is not interruptible.");
static PyObject *
lock_PyThread_release_lock(lockobject *self)
{
- /* Sanity check: the lock must be locked */
- if (PyThread_acquire_lock(self->lock_lock, 0)) {
- PyThread_release_lock(self->lock_lock);
- PyErr_SetString(ThreadError, "release unlocked lock");
- return NULL;
- }
-
- PyThread_release_lock(self->lock_lock);
- Py_INCREF(Py_None);
- return Py_None;
+ /* Sanity check: the lock must be locked */
+ if (PyThread_acquire_lock(self->lock_lock, 0)) {
+ PyThread_release_lock(self->lock_lock);
+ PyErr_SetString(ThreadError, "release unlocked lock");
+ return NULL;
+ }
+
+ PyThread_release_lock(self->lock_lock);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(release_doc,
@@ -120,11 +120,11 @@ but it needn't be locked by the same thread that unlocks it.");
static PyObject *
lock_locked_lock(lockobject *self)
{
- if (PyThread_acquire_lock(self->lock_lock, 0)) {
- PyThread_release_lock(self->lock_lock);
- return PyBool_FromLong(0L);
- }
- return PyBool_FromLong(1L);
+ if (PyThread_acquire_lock(self->lock_lock, 0)) {
+ PyThread_release_lock(self->lock_lock);
+ return PyBool_FromLong(0L);
+ }
+ return PyBool_FromLong(1L);
}
PyDoc_STRVAR(locked_doc,
@@ -134,147 +134,147 @@ PyDoc_STRVAR(locked_doc,
Return whether the lock is in the locked state.");
static PyMethodDef lock_methods[] = {
- {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS | METH_KEYWORDS, acquire_doc},
- {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS | METH_KEYWORDS, acquire_doc},
- {"release_lock", (PyCFunction)lock_PyThread_release_lock,
- METH_NOARGS, release_doc},
- {"release", (PyCFunction)lock_PyThread_release_lock,
- METH_NOARGS, release_doc},
- {"locked_lock", (PyCFunction)lock_locked_lock,
- METH_NOARGS, locked_doc},
- {"locked", (PyCFunction)lock_locked_lock,
- METH_NOARGS, locked_doc},
- {"__enter__", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS | METH_KEYWORDS, acquire_doc},
- {"__exit__", (PyCFunction)lock_PyThread_release_lock,
- METH_VARARGS, release_doc},
- {NULL, NULL} /* sentinel */
+ {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS | METH_KEYWORDS, acquire_doc},
+ {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS | METH_KEYWORDS, acquire_doc},
+ {"release_lock", (PyCFunction)lock_PyThread_release_lock,
+ METH_NOARGS, release_doc},
+ {"release", (PyCFunction)lock_PyThread_release_lock,
+ METH_NOARGS, release_doc},
+ {"locked_lock", (PyCFunction)lock_locked_lock,
+ METH_NOARGS, locked_doc},
+ {"locked", (PyCFunction)lock_locked_lock,
+ METH_NOARGS, locked_doc},
+ {"__enter__", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS | METH_KEYWORDS, acquire_doc},
+ {"__exit__", (PyCFunction)lock_PyThread_release_lock,
+ METH_VARARGS, release_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject Locktype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "_thread.lock", /*tp_name*/
- sizeof(lockobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)lock_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 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, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- lock_methods, /*tp_methods*/
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "_thread.lock", /*tp_name*/
+ sizeof(lockobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)lock_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 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, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ lock_methods, /*tp_methods*/
};
/* Recursive lock objects */
typedef struct {
- PyObject_HEAD
- PyThread_type_lock rlock_lock;
- long rlock_owner;
- unsigned long rlock_count;
- PyObject *in_weakreflist;
+ PyObject_HEAD
+ PyThread_type_lock rlock_lock;
+ long rlock_owner;
+ unsigned long rlock_count;
+ PyObject *in_weakreflist;
} rlockobject;
static void
rlock_dealloc(rlockobject *self)
{
- assert(self->rlock_lock);
- if (self->in_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) self);
- /* Unlock the lock so it's safe to free it */
- if (self->rlock_count > 0)
- PyThread_release_lock(self->rlock_lock);
-
- PyThread_free_lock(self->rlock_lock);
- Py_TYPE(self)->tp_free(self);
+ assert(self->rlock_lock);
+ if (self->in_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) self);
+ /* Unlock the lock so it's safe to free it */
+ if (self->rlock_count > 0)
+ PyThread_release_lock(self->rlock_lock);
+
+ PyThread_free_lock(self->rlock_lock);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject *
rlock_acquire(rlockobject *self, PyObject *args, PyObject *kwds)
{
- char *kwlist[] = {"blocking", "timeout", NULL};
- int blocking = 1;
- double timeout = -1;
- PY_TIMEOUT_T microseconds;
- long tid;
- int r = 1;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
- &blocking, &timeout))
- return NULL;
-
- if (!blocking && timeout != -1) {
- PyErr_SetString(PyExc_ValueError, "can't specify a timeout "
- "for a non-blocking call");
- return NULL;
- }
- if (timeout < 0 && timeout != -1) {
- PyErr_SetString(PyExc_ValueError, "timeout value must be "
- "strictly positive");
- return NULL;
- }
- if (!blocking)
- microseconds = 0;
- else if (timeout == -1)
- microseconds = -1;
- else {
- timeout *= 1e6;
- if (timeout >= (double) PY_TIMEOUT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout value is too large");
- return NULL;
- }
- microseconds = (PY_TIMEOUT_T) timeout;
- }
-
- tid = PyThread_get_thread_ident();
- if (self->rlock_count > 0 && tid == self->rlock_owner) {
- unsigned long count = self->rlock_count + 1;
- if (count <= self->rlock_count) {
- PyErr_SetString(PyExc_OverflowError,
- "Internal lock count overflowed");
- return NULL;
- }
- self->rlock_count = count;
- Py_RETURN_TRUE;
- }
-
- if (self->rlock_count > 0 ||
- !PyThread_acquire_lock(self->rlock_lock, 0)) {
- if (microseconds == 0) {
- Py_RETURN_FALSE;
- }
- Py_BEGIN_ALLOW_THREADS
- r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds);
- Py_END_ALLOW_THREADS
- }
- if (r) {
- assert(self->rlock_count == 0);
- self->rlock_owner = tid;
- self->rlock_count = 1;
- }
-
- return PyBool_FromLong(r);
+ char *kwlist[] = {"blocking", "timeout", NULL};
+ int blocking = 1;
+ double timeout = -1;
+ PY_TIMEOUT_T microseconds;
+ long tid;
+ int r = 1;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
+ &blocking, &timeout))
+ return NULL;
+
+ if (!blocking && timeout != -1) {
+ PyErr_SetString(PyExc_ValueError, "can't specify a timeout "
+ "for a non-blocking call");
+ return NULL;
+ }
+ if (timeout < 0 && timeout != -1) {
+ PyErr_SetString(PyExc_ValueError, "timeout value must be "
+ "strictly positive");
+ return NULL;
+ }
+ if (!blocking)
+ microseconds = 0;
+ else if (timeout == -1)
+ microseconds = -1;
+ else {
+ timeout *= 1e6;
+ if (timeout >= (double) PY_TIMEOUT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout value is too large");
+ return NULL;
+ }
+ microseconds = (PY_TIMEOUT_T) timeout;
+ }
+
+ tid = PyThread_get_thread_ident();
+ if (self->rlock_count > 0 && tid == self->rlock_owner) {
+ unsigned long count = self->rlock_count + 1;
+ if (count <= self->rlock_count) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Internal lock count overflowed");
+ return NULL;
+ }
+ self->rlock_count = count;
+ Py_RETURN_TRUE;
+ }
+
+ if (self->rlock_count > 0 ||
+ !PyThread_acquire_lock(self->rlock_lock, 0)) {
+ if (microseconds == 0) {
+ Py_RETURN_FALSE;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds);
+ Py_END_ALLOW_THREADS
+ }
+ if (r) {
+ assert(self->rlock_count == 0);
+ self->rlock_owner = tid;
+ self->rlock_count = 1;
+ }
+
+ return PyBool_FromLong(r);
}
PyDoc_STRVAR(rlock_acquire_doc,
@@ -296,18 +296,18 @@ the lock is taken and its internal counter initialized to 1.");
static PyObject *
rlock_release(rlockobject *self)
{
- long tid = PyThread_get_thread_ident();
-
- if (self->rlock_count == 0 || self->rlock_owner != tid) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot release un-acquired lock");
- return NULL;
- }
- if (--self->rlock_count == 0) {
- self->rlock_owner = 0;
- PyThread_release_lock(self->rlock_lock);
- }
- Py_RETURN_NONE;
+ long tid = PyThread_get_thread_ident();
+
+ if (self->rlock_count == 0 || self->rlock_owner != tid) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot release un-acquired lock");
+ return NULL;
+ }
+ if (--self->rlock_count == 0) {
+ self->rlock_owner = 0;
+ PyThread_release_lock(self->rlock_lock);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(rlock_release_doc,
@@ -325,26 +325,26 @@ to be available for other threads.");
static PyObject *
rlock_acquire_restore(rlockobject *self, PyObject *arg)
{
- long owner;
- unsigned long count;
- int r = 1;
-
- if (!PyArg_ParseTuple(arg, "kl:_acquire_restore", &count, &owner))
- return NULL;
-
- if (!PyThread_acquire_lock(self->rlock_lock, 0)) {
- Py_BEGIN_ALLOW_THREADS
- r = PyThread_acquire_lock(self->rlock_lock, 1);
- Py_END_ALLOW_THREADS
- }
- if (!r) {
- PyErr_SetString(ThreadError, "couldn't acquire lock");
- return NULL;
- }
- assert(self->rlock_count == 0);
- self->rlock_owner = owner;
- self->rlock_count = count;
- Py_RETURN_NONE;
+ long owner;
+ unsigned long count;
+ int r = 1;
+
+ if (!PyArg_ParseTuple(arg, "kl:_acquire_restore", &count, &owner))
+ return NULL;
+
+ if (!PyThread_acquire_lock(self->rlock_lock, 0)) {
+ Py_BEGIN_ALLOW_THREADS
+ r = PyThread_acquire_lock(self->rlock_lock, 1);
+ Py_END_ALLOW_THREADS
+ }
+ if (!r) {
+ PyErr_SetString(ThreadError, "couldn't acquire lock");
+ return NULL;
+ }
+ assert(self->rlock_count == 0);
+ self->rlock_owner = owner;
+ self->rlock_count = count;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(rlock_acquire_restore_doc,
@@ -355,15 +355,15 @@ For internal use by `threading.Condition`.");
static PyObject *
rlock_release_save(rlockobject *self)
{
- long owner;
- unsigned long count;
-
- owner = self->rlock_owner;
- count = self->rlock_count;
- self->rlock_count = 0;
- self->rlock_owner = 0;
- PyThread_release_lock(self->rlock_lock);
- return Py_BuildValue("kl", count, owner);
+ long owner;
+ unsigned long count;
+
+ owner = self->rlock_owner;
+ count = self->rlock_count;
+ self->rlock_count = 0;
+ self->rlock_owner = 0;
+ PyThread_release_lock(self->rlock_lock);
+ return Py_BuildValue("kl", count, owner);
}
PyDoc_STRVAR(rlock_release_save_doc,
@@ -375,12 +375,12 @@ For internal use by `threading.Condition`.");
static PyObject *
rlock_is_owned(rlockobject *self)
{
- long tid = PyThread_get_thread_ident();
-
- if (self->rlock_count > 0 && self->rlock_owner == tid) {
- Py_RETURN_TRUE;
- }
- Py_RETURN_FALSE;
+ long tid = PyThread_get_thread_ident();
+
+ if (self->rlock_count > 0 && self->rlock_owner == tid) {
+ Py_RETURN_TRUE;
+ }
+ Py_RETURN_FALSE;
}
PyDoc_STRVAR(rlock_is_owned_doc,
@@ -391,108 +391,108 @@ For internal use by `threading.Condition`.");
static PyObject *
rlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- rlockobject *self;
-
- self = (rlockobject *) type->tp_alloc(type, 0);
- if (self != NULL) {
- self->rlock_lock = PyThread_allocate_lock();
- if (self->rlock_lock == NULL) {
- type->tp_free(self);
- PyErr_SetString(ThreadError, "can't allocate lock");
- return NULL;
- }
- self->in_weakreflist = NULL;
- self->rlock_owner = 0;
- self->rlock_count = 0;
- }
-
- return (PyObject *) self;
+ rlockobject *self;
+
+ self = (rlockobject *) type->tp_alloc(type, 0);
+ if (self != NULL) {
+ self->rlock_lock = PyThread_allocate_lock();
+ if (self->rlock_lock == NULL) {
+ type->tp_free(self);
+ PyErr_SetString(ThreadError, "can't allocate lock");
+ return NULL;
+ }
+ self->in_weakreflist = NULL;
+ self->rlock_owner = 0;
+ self->rlock_count = 0;
+ }
+
+ return (PyObject *) self;
}
static PyObject *
rlock_repr(rlockobject *self)
{
- return PyUnicode_FromFormat("<%s owner=%ld count=%lu>",
- Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count);
+ return PyUnicode_FromFormat("<%s owner=%ld count=%lu>",
+ Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count);
}
static PyMethodDef rlock_methods[] = {
- {"acquire", (PyCFunction)rlock_acquire,
- METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
- {"release", (PyCFunction)rlock_release,
- METH_NOARGS, rlock_release_doc},
- {"_is_owned", (PyCFunction)rlock_is_owned,
- METH_NOARGS, rlock_is_owned_doc},
- {"_acquire_restore", (PyCFunction)rlock_acquire_restore,
- METH_O, rlock_acquire_restore_doc},
- {"_release_save", (PyCFunction)rlock_release_save,
- METH_NOARGS, rlock_release_save_doc},
- {"__enter__", (PyCFunction)rlock_acquire,
- METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
- {"__exit__", (PyCFunction)rlock_release,
- METH_VARARGS, rlock_release_doc},
- {NULL, NULL} /* sentinel */
+ {"acquire", (PyCFunction)rlock_acquire,
+ METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
+ {"release", (PyCFunction)rlock_release,
+ METH_NOARGS, rlock_release_doc},
+ {"_is_owned", (PyCFunction)rlock_is_owned,
+ METH_NOARGS, rlock_is_owned_doc},
+ {"_acquire_restore", (PyCFunction)rlock_acquire_restore,
+ METH_O, rlock_acquire_restore_doc},
+ {"_release_save", (PyCFunction)rlock_release_save,
+ METH_NOARGS, rlock_release_save_doc},
+ {"__enter__", (PyCFunction)rlock_acquire,
+ METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
+ {"__exit__", (PyCFunction)rlock_release,
+ METH_VARARGS, rlock_release_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject RLocktype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "_thread.RLock", /*tp_name*/
- sizeof(rlockobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)rlock_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- (reprfunc)rlock_repr, /*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 */
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- rlock_methods, /*tp_methods*/
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- rlock_new /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "_thread.RLock", /*tp_name*/
+ sizeof(rlockobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)rlock_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ (reprfunc)rlock_repr, /*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 */
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ rlock_methods, /*tp_methods*/
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ rlock_new /* tp_new */
};
static lockobject *
newlockobject(void)
{
- lockobject *self;
- self = PyObject_New(lockobject, &Locktype);
- if (self == NULL)
- return NULL;
- self->lock_lock = PyThread_allocate_lock();
- self->in_weakreflist = NULL;
- if (self->lock_lock == NULL) {
- Py_DECREF(self);
- PyErr_SetString(ThreadError, "can't allocate lock");
- return NULL;
- }
- return self;
+ lockobject *self;
+ self = PyObject_New(lockobject, &Locktype);
+ if (self == NULL)
+ return NULL;
+ self->lock_lock = PyThread_allocate_lock();
+ self->in_weakreflist = NULL;
+ if (self->lock_lock == NULL) {
+ Py_DECREF(self);
+ PyErr_SetString(ThreadError, "can't allocate lock");
+ return NULL;
+ }
+ return self;
}
/* Thread-local objects */
@@ -500,353 +500,353 @@ newlockobject(void)
#include "structmember.h"
typedef struct {
- PyObject_HEAD
- PyObject *key;
- PyObject *args;
- PyObject *kw;
- PyObject *dict;
+ PyObject_HEAD
+ PyObject *key;
+ PyObject *args;
+ PyObject *kw;
+ PyObject *dict;
} localobject;
static PyObject *
local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- localobject *self;
- PyObject *tdict;
-
- if (type->tp_init == PyBaseObject_Type.tp_init
- && ((args && PyObject_IsTrue(args))
- || (kw && PyObject_IsTrue(kw)))) {
- PyErr_SetString(PyExc_TypeError,
- "Initialization arguments are not supported");
- return NULL;
- }
-
- self = (localobject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- Py_XINCREF(args);
- self->args = args;
- Py_XINCREF(kw);
- self->kw = kw;
- self->dict = NULL; /* making sure */
- self->key = PyUnicode_FromFormat("thread.local.%p", self);
- if (self->key == NULL)
- goto err;
-
- self->dict = PyDict_New();
- if (self->dict == NULL)
- goto err;
-
- tdict = PyThreadState_GetDict();
- if (tdict == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "Couldn't get thread-state dictionary");
- goto err;
- }
-
- if (PyDict_SetItem(tdict, self->key, self->dict) < 0)
- goto err;
-
- return (PyObject *)self;
+ localobject *self;
+ PyObject *tdict;
+
+ if (type->tp_init == PyBaseObject_Type.tp_init
+ && ((args && PyObject_IsTrue(args))
+ || (kw && PyObject_IsTrue(kw)))) {
+ PyErr_SetString(PyExc_TypeError,
+ "Initialization arguments are not supported");
+ return NULL;
+ }
+
+ self = (localobject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ Py_XINCREF(args);
+ self->args = args;
+ Py_XINCREF(kw);
+ self->kw = kw;
+ self->dict = NULL; /* making sure */
+ self->key = PyUnicode_FromFormat("thread.local.%p", self);
+ if (self->key == NULL)
+ goto err;
+
+ self->dict = PyDict_New();
+ if (self->dict == NULL)
+ goto err;
+
+ tdict = PyThreadState_GetDict();
+ if (tdict == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "Couldn't get thread-state dictionary");
+ goto err;
+ }
+
+ if (PyDict_SetItem(tdict, self->key, self->dict) < 0)
+ goto err;
+
+ return (PyObject *)self;
err:
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->args);
- Py_VISIT(self->kw);
- Py_VISIT(self->dict);
- return 0;
+ Py_VISIT(self->args);
+ Py_VISIT(self->kw);
+ Py_VISIT(self->dict);
+ return 0;
}
static int
local_clear(localobject *self)
{
- Py_CLEAR(self->args);
- Py_CLEAR(self->kw);
- Py_CLEAR(self->dict);
- return 0;
+ Py_CLEAR(self->args);
+ Py_CLEAR(self->kw);
+ Py_CLEAR(self->dict);
+ return 0;
}
static void
local_dealloc(localobject *self)
{
- PyThreadState *tstate;
- if (self->key
- && (tstate = PyThreadState_Get())
- && tstate->interp) {
- for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
- tstate;
- tstate = PyThreadState_Next(tstate))
- if (tstate->dict &&
- PyDict_GetItem(tstate->dict, self->key))
- PyDict_DelItem(tstate->dict, self->key);
- }
-
- Py_XDECREF(self->key);
- local_clear(self);
- Py_TYPE(self)->tp_free((PyObject*)self);
+ PyThreadState *tstate;
+ if (self->key
+ && (tstate = PyThreadState_Get())
+ && tstate->interp) {
+ for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
+ tstate;
+ tstate = PyThreadState_Next(tstate))
+ if (tstate->dict &&
+ PyDict_GetItem(tstate->dict, self->key))
+ PyDict_DelItem(tstate->dict, self->key);
+ }
+
+ Py_XDECREF(self->key);
+ local_clear(self);
+ Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
_ldict(localobject *self)
{
- PyObject *tdict, *ldict;
-
- tdict = PyThreadState_GetDict();
- if (tdict == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "Couldn't get thread-state dictionary");
- return NULL;
- }
-
- ldict = PyDict_GetItem(tdict, self->key);
- if (ldict == NULL) {
- ldict = PyDict_New(); /* we own ldict */
-
- if (ldict == NULL)
- return NULL;
- else {
- int i = PyDict_SetItem(tdict, self->key, ldict);
- Py_DECREF(ldict); /* now ldict is borrowed */
- if (i < 0)
- return NULL;
- }
-
- Py_CLEAR(self->dict);
- Py_INCREF(ldict);
- self->dict = ldict; /* still borrowed */
-
- if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
- Py_TYPE(self)->tp_init((PyObject*)self,
- self->args, self->kw) < 0) {
- /* we need to get rid of ldict from thread so
- we create a new one the next time we do an attr
- acces */
- PyDict_DelItem(tdict, self->key);
- return NULL;
- }
-
- }
-
- /* The call to tp_init above may have caused another thread to run.
- Install our ldict again. */
- if (self->dict != ldict) {
- Py_CLEAR(self->dict);
- Py_INCREF(ldict);
- self->dict = ldict;
- }
-
- return ldict;
+ PyObject *tdict, *ldict;
+
+ tdict = PyThreadState_GetDict();
+ if (tdict == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "Couldn't get thread-state dictionary");
+ return NULL;
+ }
+
+ ldict = PyDict_GetItem(tdict, self->key);
+ if (ldict == NULL) {
+ ldict = PyDict_New(); /* we own ldict */
+
+ if (ldict == NULL)
+ return NULL;
+ else {
+ int i = PyDict_SetItem(tdict, self->key, ldict);
+ Py_DECREF(ldict); /* now ldict is borrowed */
+ if (i < 0)
+ return NULL;
+ }
+
+ Py_CLEAR(self->dict);
+ Py_INCREF(ldict);
+ self->dict = ldict; /* still borrowed */
+
+ if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
+ Py_TYPE(self)->tp_init((PyObject*)self,
+ self->args, self->kw) < 0) {
+ /* we need to get rid of ldict from thread so
+ we create a new one the next time we do an attr
+ acces */
+ PyDict_DelItem(tdict, self->key);
+ return NULL;
+ }
+
+ }
+
+ /* The call to tp_init above may have caused another thread to run.
+ Install our ldict again. */
+ if (self->dict != ldict) {
+ Py_CLEAR(self->dict);
+ Py_INCREF(ldict);
+ self->dict = ldict;
+ }
+
+ return ldict;
}
static int
local_setattro(localobject *self, PyObject *name, PyObject *v)
{
- PyObject *ldict;
-
- ldict = _ldict(self);
- if (ldict == NULL)
- return -1;
+ PyObject *ldict;
+
+ ldict = _ldict(self);
+ if (ldict == NULL)
+ return -1;
- return PyObject_GenericSetAttr((PyObject *)self, name, v);
+ return PyObject_GenericSetAttr((PyObject *)self, name, v);
}
static PyObject *
local_getdict(localobject *self, void *closure)
{
- if (self->dict == NULL) {
- PyErr_SetString(PyExc_AttributeError, "__dict__");
- return NULL;
- }
+ if (self->dict == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "__dict__");
+ return NULL;
+ }
- Py_INCREF(self->dict);
- return self->dict;
+ Py_INCREF(self->dict);
+ return self->dict;
}
static PyGetSetDef local_getset[] = {
- {"__dict__", (getter)local_getdict, (setter)NULL,
- "Local-data dictionary", NULL},
- {NULL} /* Sentinel */
+ {"__dict__", (getter)local_getdict, (setter)NULL,
+ "Local-data dictionary", NULL},
+ {NULL} /* Sentinel */
};
static PyObject *local_getattro(localobject *, PyObject *);
static PyTypeObject localtype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* tp_name */ "_thread._local",
- /* tp_basicsize */ sizeof(localobject),
- /* tp_itemsize */ 0,
- /* tp_dealloc */ (destructor)local_dealloc,
- /* tp_print */ 0,
- /* tp_getattr */ 0,
- /* tp_setattr */ 0,
- /* tp_reserved */ 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 */ (getattrofunc)local_getattro,
- /* tp_setattro */ (setattrofunc)local_setattro,
- /* tp_as_buffer */ 0,
- /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- /* tp_doc */ "Thread-local data",
- /* tp_traverse */ (traverseproc)local_traverse,
- /* tp_clear */ (inquiry)local_clear,
- /* tp_richcompare */ 0,
- /* tp_weaklistoffset */ 0,
- /* tp_iter */ 0,
- /* tp_iternext */ 0,
- /* tp_methods */ 0,
- /* tp_members */ 0,
- /* tp_getset */ local_getset,
- /* tp_base */ 0,
- /* tp_dict */ 0, /* internal use */
- /* tp_descr_get */ 0,
- /* tp_descr_set */ 0,
- /* tp_dictoffset */ offsetof(localobject, dict),
- /* tp_init */ 0,
- /* tp_alloc */ 0,
- /* tp_new */ local_new,
- /* tp_free */ 0, /* Low-level free-mem routine */
- /* tp_is_gc */ 0, /* For PyObject_IS_GC */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* tp_name */ "_thread._local",
+ /* tp_basicsize */ sizeof(localobject),
+ /* tp_itemsize */ 0,
+ /* tp_dealloc */ (destructor)local_dealloc,
+ /* tp_print */ 0,
+ /* tp_getattr */ 0,
+ /* tp_setattr */ 0,
+ /* tp_reserved */ 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 */ (getattrofunc)local_getattro,
+ /* tp_setattro */ (setattrofunc)local_setattro,
+ /* tp_as_buffer */ 0,
+ /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+ /* tp_doc */ "Thread-local data",
+ /* tp_traverse */ (traverseproc)local_traverse,
+ /* tp_clear */ (inquiry)local_clear,
+ /* tp_richcompare */ 0,
+ /* tp_weaklistoffset */ 0,
+ /* tp_iter */ 0,
+ /* tp_iternext */ 0,
+ /* tp_methods */ 0,
+ /* tp_members */ 0,
+ /* tp_getset */ local_getset,
+ /* tp_base */ 0,
+ /* tp_dict */ 0, /* internal use */
+ /* tp_descr_get */ 0,
+ /* tp_descr_set */ 0,
+ /* tp_dictoffset */ offsetof(localobject, dict),
+ /* tp_init */ 0,
+ /* tp_alloc */ 0,
+ /* tp_new */ local_new,
+ /* tp_free */ 0, /* Low-level free-mem routine */
+ /* tp_is_gc */ 0, /* For PyObject_IS_GC */
};
static PyObject *
local_getattro(localobject *self, PyObject *name)
{
- PyObject *ldict, *value;
+ PyObject *ldict, *value;
- ldict = _ldict(self);
- if (ldict == NULL)
- return NULL;
+ ldict = _ldict(self);
+ if (ldict == NULL)
+ return NULL;
- if (Py_TYPE(self) != &localtype)
- /* use generic lookup for subtypes */
- return PyObject_GenericGetAttr((PyObject *)self, name);
+ if (Py_TYPE(self) != &localtype)
+ /* use generic lookup for subtypes */
+ return PyObject_GenericGetAttr((PyObject *)self, name);
- /* Optimization: just look in dict ourselves */
- value = PyDict_GetItem(ldict, name);
- if (value == NULL)
- /* Fall back on generic to get __class__ and __dict__ */
- return PyObject_GenericGetAttr((PyObject *)self, name);
+ /* Optimization: just look in dict ourselves */
+ value = PyDict_GetItem(ldict, name);
+ if (value == NULL)
+ /* Fall back on generic to get __class__ and __dict__ */
+ return PyObject_GenericGetAttr((PyObject *)self, name);
- Py_INCREF(value);
- return value;
+ Py_INCREF(value);
+ return value;
}
/* Module functions */
struct bootstate {
- PyInterpreterState *interp;
- PyObject *func;
- PyObject *args;
- PyObject *keyw;
- PyThreadState *tstate;
+ PyInterpreterState *interp;
+ PyObject *func;
+ PyObject *args;
+ PyObject *keyw;
+ PyThreadState *tstate;
};
static void
t_bootstrap(void *boot_raw)
{
- struct bootstate *boot = (struct bootstate *) boot_raw;
- PyThreadState *tstate;
- PyObject *res;
-
- tstate = boot->tstate;
- tstate->thread_id = PyThread_get_thread_ident();
- _PyThreadState_Init(tstate);
- PyEval_AcquireThread(tstate);
- nb_threads++;
- res = PyEval_CallObjectWithKeywords(
- boot->func, boot->args, boot->keyw);
- if (res == NULL) {
- if (PyErr_ExceptionMatches(PyExc_SystemExit))
- PyErr_Clear();
- else {
- PyObject *file;
- PySys_WriteStderr(
- "Unhandled exception in thread started by ");
- file = PySys_GetObject("stderr");
- if (file != NULL && file != Py_None)
- PyFile_WriteObject(boot->func, file, 0);
- else
- PyObject_Print(boot->func, stderr, 0);
- PySys_WriteStderr("\n");
- PyErr_PrintEx(0);
- }
- }
- else
- Py_DECREF(res);
- Py_DECREF(boot->func);
- Py_DECREF(boot->args);
- Py_XDECREF(boot->keyw);
- PyMem_DEL(boot_raw);
- nb_threads--;
- PyThreadState_Clear(tstate);
- PyThreadState_DeleteCurrent();
- PyThread_exit_thread();
+ struct bootstate *boot = (struct bootstate *) boot_raw;
+ PyThreadState *tstate;
+ PyObject *res;
+
+ tstate = boot->tstate;
+ tstate->thread_id = PyThread_get_thread_ident();
+ _PyThreadState_Init(tstate);
+ PyEval_AcquireThread(tstate);
+ nb_threads++;
+ res = PyEval_CallObjectWithKeywords(
+ boot->func, boot->args, boot->keyw);
+ if (res == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_SystemExit))
+ PyErr_Clear();
+ else {
+ PyObject *file;
+ PySys_WriteStderr(
+ "Unhandled exception in thread started by ");
+ file = PySys_GetObject("stderr");
+ if (file != NULL && file != Py_None)
+ PyFile_WriteObject(boot->func, file, 0);
+ else
+ PyObject_Print(boot->func, stderr, 0);
+ PySys_WriteStderr("\n");
+ PyErr_PrintEx(0);
+ }
+ }
+ else
+ Py_DECREF(res);
+ Py_DECREF(boot->func);
+ Py_DECREF(boot->args);
+ Py_XDECREF(boot->keyw);
+ PyMem_DEL(boot_raw);
+ nb_threads--;
+ PyThreadState_Clear(tstate);
+ PyThreadState_DeleteCurrent();
+ PyThread_exit_thread();
}
static PyObject *
thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
{
- PyObject *func, *args, *keyw = NULL;
- struct bootstate *boot;
- long ident;
-
- if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
- &func, &args, &keyw))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError,
- "first arg must be callable");
- return NULL;
- }
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_TypeError,
- "2nd arg must be a tuple");
- return NULL;
- }
- if (keyw != NULL && !PyDict_Check(keyw)) {
- PyErr_SetString(PyExc_TypeError,
- "optional 3rd arg must be a dictionary");
- return NULL;
- }
- boot = PyMem_NEW(struct bootstate, 1);
- if (boot == NULL)
- return PyErr_NoMemory();
- boot->interp = PyThreadState_GET()->interp;
- boot->func = func;
- boot->args = args;
- boot->keyw = keyw;
- boot->tstate = _PyThreadState_Prealloc(boot->interp);
- if (boot->tstate == NULL) {
- PyMem_DEL(boot);
- return PyErr_NoMemory();
- }
- Py_INCREF(func);
- Py_INCREF(args);
- Py_XINCREF(keyw);
- PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
- ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
- if (ident == -1) {
- PyErr_SetString(ThreadError, "can't start new thread");
- Py_DECREF(func);
- Py_DECREF(args);
- Py_XDECREF(keyw);
- PyThreadState_Clear(boot->tstate);
- PyMem_DEL(boot);
- return NULL;
- }
- return PyLong_FromLong(ident);
+ PyObject *func, *args, *keyw = NULL;
+ struct bootstate *boot;
+ long ident;
+
+ if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
+ &func, &args, &keyw))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first arg must be callable");
+ return NULL;
+ }
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "2nd arg must be a tuple");
+ return NULL;
+ }
+ if (keyw != NULL && !PyDict_Check(keyw)) {
+ PyErr_SetString(PyExc_TypeError,
+ "optional 3rd arg must be a dictionary");
+ return NULL;
+ }
+ boot = PyMem_NEW(struct bootstate, 1);
+ if (boot == NULL)
+ return PyErr_NoMemory();
+ boot->interp = PyThreadState_GET()->interp;
+ boot->func = func;
+ boot->args = args;
+ boot->keyw = keyw;
+ boot->tstate = _PyThreadState_Prealloc(boot->interp);
+ if (boot->tstate == NULL) {
+ PyMem_DEL(boot);
+ return PyErr_NoMemory();
+ }
+ Py_INCREF(func);
+ Py_INCREF(args);
+ Py_XINCREF(keyw);
+ PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
+ ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
+ if (ident == -1) {
+ PyErr_SetString(ThreadError, "can't start new thread");
+ Py_DECREF(func);
+ Py_DECREF(args);
+ Py_XDECREF(keyw);
+ PyThreadState_Clear(boot->tstate);
+ PyMem_DEL(boot);
+ return NULL;
+ }
+ return PyLong_FromLong(ident);
}
PyDoc_STRVAR(start_new_doc,
@@ -863,8 +863,8 @@ printed unless the exception is SystemExit.\n");
static PyObject *
thread_PyThread_exit_thread(PyObject *self)
{
- PyErr_SetNone(PyExc_SystemExit);
- return NULL;
+ PyErr_SetNone(PyExc_SystemExit);
+ return NULL;
}
PyDoc_STRVAR(exit_doc,
@@ -877,9 +877,9 @@ thread to exit silently unless the exception is caught.");
static PyObject *
thread_PyThread_interrupt_main(PyObject * self)
{
- PyErr_SetInterrupt();
- Py_INCREF(Py_None);
- return Py_None;
+ PyErr_SetInterrupt();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(interrupt_doc,
@@ -894,7 +894,7 @@ static lockobject *newlockobject(void);
static PyObject *
thread_PyThread_allocate_lock(PyObject *self)
{
- return (PyObject *) newlockobject();
+ return (PyObject *) newlockobject();
}
PyDoc_STRVAR(allocate_doc,
@@ -906,13 +906,13 @@ Create a new lock object. See LockType.__doc__ for information about locks.");
static PyObject *
thread_get_ident(PyObject *self)
{
- long ident;
- ident = PyThread_get_thread_ident();
- if (ident == -1) {
- PyErr_SetString(ThreadError, "no current thread ident");
- return NULL;
- }
- return PyLong_FromLong(ident);
+ long ident;
+ ident = PyThread_get_thread_ident();
+ if (ident == -1) {
+ PyErr_SetString(ThreadError, "no current thread ident");
+ return NULL;
+ }
+ return PyLong_FromLong(ident);
}
PyDoc_STRVAR(get_ident_doc,
@@ -929,7 +929,7 @@ A thread's identity may be reused for another thread after it exits.");
static PyObject *
thread__count(PyObject *self)
{
- return PyLong_FromLong(nb_threads);
+ return PyLong_FromLong(nb_threads);
}
PyDoc_STRVAR(_count_doc,
@@ -947,35 +947,35 @@ In most applications `threading.enumerate()` should be used instead.");
static PyObject *
thread_stack_size(PyObject *self, PyObject *args)
{
- size_t old_size;
- Py_ssize_t new_size = 0;
- int rc;
-
- if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size))
- return NULL;
-
- if (new_size < 0) {
- PyErr_SetString(PyExc_ValueError,
- "size must be 0 or a positive value");
- return NULL;
- }
-
- old_size = PyThread_get_stacksize();
-
- rc = PyThread_set_stacksize((size_t) new_size);
- if (rc == -1) {
- PyErr_Format(PyExc_ValueError,
- "size not valid: %zd bytes",
- new_size);
- return NULL;
- }
- if (rc == -2) {
- PyErr_SetString(ThreadError,
- "setting stack size not supported");
- return NULL;
- }
-
- return PyLong_FromSsize_t((Py_ssize_t) old_size);
+ size_t old_size;
+ Py_ssize_t new_size = 0;
+ int rc;
+
+ if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size))
+ return NULL;
+
+ if (new_size < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "size must be 0 or a positive value");
+ return NULL;
+ }
+
+ old_size = PyThread_get_stacksize();
+
+ rc = PyThread_set_stacksize((size_t) new_size);
+ if (rc == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "size not valid: %zd bytes",
+ new_size);
+ return NULL;
+ }
+ if (rc == -2) {
+ PyErr_SetString(ThreadError,
+ "setting stack size not supported");
+ return NULL;
+ }
+
+ return PyLong_FromSsize_t((Py_ssize_t) old_size);
}
PyDoc_STRVAR(stack_size_doc,
@@ -999,30 +999,30 @@ requiring allocation in multiples of the system memory page size\n\
the suggested approach in the absence of more specific information).");
static PyMethodDef thread_methods[] = {
- {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread,
- METH_VARARGS,
- start_new_doc},
- {"start_new", (PyCFunction)thread_PyThread_start_new_thread,
- METH_VARARGS,
- start_new_doc},
- {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock,
- METH_NOARGS, allocate_doc},
- {"allocate", (PyCFunction)thread_PyThread_allocate_lock,
- METH_NOARGS, allocate_doc},
- {"exit_thread", (PyCFunction)thread_PyThread_exit_thread,
- METH_NOARGS, exit_doc},
- {"exit", (PyCFunction)thread_PyThread_exit_thread,
- METH_NOARGS, exit_doc},
- {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main,
- METH_NOARGS, interrupt_doc},
- {"get_ident", (PyCFunction)thread_get_ident,
- METH_NOARGS, get_ident_doc},
- {"_count", (PyCFunction)thread__count,
- METH_NOARGS, _count_doc},
- {"stack_size", (PyCFunction)thread_stack_size,
- METH_VARARGS,
- stack_size_doc},
- {NULL, NULL} /* sentinel */
+ {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread,
+ METH_VARARGS,
+ start_new_doc},
+ {"start_new", (PyCFunction)thread_PyThread_start_new_thread,
+ METH_VARARGS,
+ start_new_doc},
+ {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock,
+ METH_NOARGS, allocate_doc},
+ {"allocate", (PyCFunction)thread_PyThread_allocate_lock,
+ METH_NOARGS, allocate_doc},
+ {"exit_thread", (PyCFunction)thread_PyThread_exit_thread,
+ METH_NOARGS, exit_doc},
+ {"exit", (PyCFunction)thread_PyThread_exit_thread,
+ METH_NOARGS, exit_doc},
+ {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main,
+ METH_NOARGS, interrupt_doc},
+ {"get_ident", (PyCFunction)thread_get_ident,
+ METH_NOARGS, get_ident_doc},
+ {"_count", (PyCFunction)thread__count,
+ METH_NOARGS, _count_doc},
+ {"stack_size", (PyCFunction)thread_stack_size,
+ METH_VARARGS,
+ stack_size_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1045,61 +1045,61 @@ unlock it. A thread attempting to lock a lock that it has already locked\n\
will block until another thread unlocks it. Deadlocks may ensue.");
static struct PyModuleDef threadmodule = {
- PyModuleDef_HEAD_INIT,
- "_thread",
- thread_doc,
- -1,
- thread_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_thread",
+ thread_doc,
+ -1,
+ thread_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__thread(void)
{
- PyObject *m, *d, *timeout_max;
-
- /* Initialize types: */
- if (PyType_Ready(&localtype) < 0)
- return NULL;
- if (PyType_Ready(&Locktype) < 0)
- return NULL;
- if (PyType_Ready(&RLocktype) < 0)
- return NULL;
-
- /* Create the module and add the functions */
- m = PyModule_Create(&threadmodule);
- if (m == NULL)
- return NULL;
-
- timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000);
- if (!timeout_max)
- return NULL;
- if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0)
- return NULL;
-
- /* Add a symbolic constant */
- d = PyModule_GetDict(m);
- ThreadError = PyErr_NewException("_thread.error", NULL, NULL);
- PyDict_SetItemString(d, "error", ThreadError);
- Locktype.tp_doc = lock_doc;
- Py_INCREF(&Locktype);
- PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
-
- Py_INCREF(&RLocktype);
- if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0)
- return NULL;
-
- Py_INCREF(&localtype);
- if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
- return NULL;
-
- nb_threads = 0;
-
- /* Initialize the C thread library */
- PyThread_init_thread();
- return m;
+ PyObject *m, *d, *timeout_max;
+
+ /* Initialize types: */
+ if (PyType_Ready(&localtype) < 0)
+ return NULL;
+ if (PyType_Ready(&Locktype) < 0)
+ return NULL;
+ if (PyType_Ready(&RLocktype) < 0)
+ return NULL;
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&threadmodule);
+ if (m == NULL)
+ return NULL;
+
+ timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000);
+ if (!timeout_max)
+ return NULL;
+ if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0)
+ return NULL;
+
+ /* Add a symbolic constant */
+ d = PyModule_GetDict(m);
+ ThreadError = PyErr_NewException("_thread.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", ThreadError);
+ Locktype.tp_doc = lock_doc;
+ Py_INCREF(&Locktype);
+ PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
+
+ Py_INCREF(&RLocktype);
+ if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0)
+ return NULL;
+
+ Py_INCREF(&localtype);
+ if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
+ return NULL;
+
+ nb_threads = 0;
+
+ /* Initialize the C thread library */
+ PyThread_init_thread();
+ return m;
}
diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c
index ef38ea3..8552575 100644
--- a/Modules/_tkinter.c
+++ b/Modules/_tkinter.c
@@ -9,9 +9,9 @@ Copyright (C) 1994 Steen Lumholt.
/* TCL/TK VERSION INFO:
- Only Tcl/Tk 8.3.1 and later are supported. Older versions are not
- supported. Use Python 2.6 or older if you cannot upgrade your
- Tcl/Tk libraries.
+ Only Tcl/Tk 8.3.1 and later are supported. Older versions are not
+ supported. Use Python 2.6 or older if you cannot upgrade your
+ Tcl/Tk libraries.
*/
/* XXX Further speed-up ideas, involving Tcl 8.0 features:
@@ -197,32 +197,32 @@ static PyThreadState *tcl_tstate = NULL;
#endif
#define ENTER_TCL \
- { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
+ { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
#define LEAVE_TCL \
tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS}
#define ENTER_OVERLAP \
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
#define LEAVE_OVERLAP_TCL \
- tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); }
+ tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); }
#define ENTER_PYTHON \
- { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
- if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
+ { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
+ if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
#define LEAVE_PYTHON \
- { PyThreadState *tstate = PyEval_SaveThread(); \
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
+ { PyThreadState *tstate = PyEval_SaveThread(); \
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
#define CHECK_TCL_APPARTMENT \
- if (((TkappObject *)self)->threaded && \
- ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \
- PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \
- return 0; \
- }
+ if (((TkappObject *)self)->threaded && \
+ ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \
+ PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \
+ return 0; \
+ }
#else
@@ -245,21 +245,21 @@ static PyThreadState *tcl_tstate = NULL;
static PyTypeObject Tkapp_Type;
typedef struct {
- PyObject_HEAD
- Tcl_Interp *interp;
- int wantobjects;
- int threaded; /* True if tcl_platform[threaded] */
- Tcl_ThreadId thread_id;
- int dispatching;
- /* We cannot include tclInt.h, as this is internal.
- So we cache interesting types here. */
- Tcl_ObjType *BooleanType;
- Tcl_ObjType *ByteArrayType;
- Tcl_ObjType *DoubleType;
- Tcl_ObjType *IntType;
- Tcl_ObjType *ListType;
- Tcl_ObjType *ProcBodyType;
- Tcl_ObjType *StringType;
+ PyObject_HEAD
+ Tcl_Interp *interp;
+ int wantobjects;
+ int threaded; /* True if tcl_platform[threaded] */
+ Tcl_ThreadId thread_id;
+ int dispatching;
+ /* We cannot include tclInt.h, as this is internal.
+ So we cache interesting types here. */
+ Tcl_ObjType *BooleanType;
+ Tcl_ObjType *ByteArrayType;
+ Tcl_ObjType *DoubleType;
+ Tcl_ObjType *IntType;
+ Tcl_ObjType *ListType;
+ Tcl_ObjType *ProcBodyType;
+ Tcl_ObjType *StringType;
} TkappObject;
#define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type)
@@ -270,7 +270,7 @@ typedef struct {
(void *) v, Py_REFCNT(v)))
-
+
/**** Error Handling ****/
static PyObject *Tkinter_TclError;
@@ -284,16 +284,16 @@ static PyObject *trbInCmd;
static int tk_load_failed = 0;
#endif
-
+
static PyObject *
Tkinter_Error(PyObject *v)
{
- PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
- return NULL;
+ PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
+ return NULL;
}
-
+
/**** Utils ****/
static int Tkinter_busywaitinterval = 20;
@@ -306,11 +306,11 @@ static int Tkinter_busywaitinterval = 20;
static void
Sleep(int milli)
{
- /* XXX Too bad if you don't have select(). */
- struct timeval t;
- t.tv_sec = milli/1000;
- t.tv_usec = (milli%1000) * 1000;
- select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
+ /* XXX Too bad if you don't have select(). */
+ struct timeval t;
+ t.tv_sec = milli/1000;
+ t.tv_usec = (milli%1000) * 1000;
+ select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
}
#endif /* MS_WINDOWS */
@@ -319,172 +319,172 @@ Sleep(int milli)
static int
WaitForMainloop(TkappObject* self)
{
- int i;
- for (i = 0; i < 10; i++) {
- if (self->dispatching)
- return 1;
- Py_BEGIN_ALLOW_THREADS
- Sleep(100);
- Py_END_ALLOW_THREADS
- }
- if (self->dispatching)
- return 1;
- PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop");
- return 0;
+ int i;
+ for (i = 0; i < 10; i++) {
+ if (self->dispatching)
+ return 1;
+ Py_BEGIN_ALLOW_THREADS
+ Sleep(100);
+ Py_END_ALLOW_THREADS
+ }
+ if (self->dispatching)
+ return 1;
+ PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop");
+ return 0;
}
#endif /* WITH_THREAD */
-
+
static char *
AsString(PyObject *value, PyObject *tmp)
{
- if (PyBytes_Check(value))
- return PyBytes_AsString(value);
- else if (PyUnicode_Check(value)) {
- PyObject *v = PyUnicode_AsUTF8String(value);
- if (v == NULL)
- return NULL;
- if (PyList_Append(tmp, v) != 0) {
- Py_DECREF(v);
- return NULL;
- }
- Py_DECREF(v);
- return PyBytes_AsString(v);
- }
- else {
- PyObject *v = PyObject_Str(value);
- if (v == NULL)
- return NULL;
- if (PyList_Append(tmp, v) != 0) {
- Py_DECREF(v);
- return NULL;
- }
- Py_DECREF(v);
- return PyBytes_AsString(v);
- }
-}
-
-
-
+ if (PyBytes_Check(value))
+ return PyBytes_AsString(value);
+ else if (PyUnicode_Check(value)) {
+ PyObject *v = PyUnicode_AsUTF8String(value);
+ if (v == NULL)
+ return NULL;
+ if (PyList_Append(tmp, v) != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ Py_DECREF(v);
+ return PyBytes_AsString(v);
+ }
+ else {
+ PyObject *v = PyObject_Str(value);
+ if (v == NULL)
+ return NULL;
+ if (PyList_Append(tmp, v) != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ Py_DECREF(v);
+ return PyBytes_AsString(v);
+ }
+}
+
+
+
#define ARGSZ 64
static char *
Merge(PyObject *args)
{
- PyObject *tmp = NULL;
- char *argvStore[ARGSZ];
- char **argv = NULL;
- int fvStore[ARGSZ];
- int *fv = NULL;
- int argc = 0, fvc = 0, i;
- char *res = NULL;
-
- if (!(tmp = PyList_New(0)))
- return NULL;
-
- argv = argvStore;
- fv = fvStore;
-
- if (args == NULL)
- argc = 0;
-
- else if (!PyTuple_Check(args)) {
- argc = 1;
- fv[0] = 0;
- if (!(argv[0] = AsString(args, tmp)))
- goto finally;
- }
- else {
- argc = PyTuple_Size(args);
-
- if (argc > ARGSZ) {
- argv = (char **)ckalloc(argc * sizeof(char *));
- fv = (int *)ckalloc(argc * sizeof(int));
- if (argv == NULL || fv == NULL) {
- PyErr_NoMemory();
- goto finally;
- }
- }
-
- for (i = 0; i < argc; i++) {
- PyObject *v = PyTuple_GetItem(args, i);
- if (PyTuple_Check(v)) {
- fv[i] = 1;
- if (!(argv[i] = Merge(v)))
- goto finally;
- fvc++;
- }
- else if (v == Py_None) {
- argc = i;
- break;
- }
- else {
- fv[i] = 0;
- if (!(argv[i] = AsString(v, tmp)))
- goto finally;
- fvc++;
- }
- }
- }
- res = Tcl_Merge(argc, argv);
- if (res == NULL)
- PyErr_SetString(Tkinter_TclError, "merge failed");
+ PyObject *tmp = NULL;
+ char *argvStore[ARGSZ];
+ char **argv = NULL;
+ int fvStore[ARGSZ];
+ int *fv = NULL;
+ int argc = 0, fvc = 0, i;
+ char *res = NULL;
+
+ if (!(tmp = PyList_New(0)))
+ return NULL;
+
+ argv = argvStore;
+ fv = fvStore;
+
+ if (args == NULL)
+ argc = 0;
+
+ else if (!PyTuple_Check(args)) {
+ argc = 1;
+ fv[0] = 0;
+ if (!(argv[0] = AsString(args, tmp)))
+ goto finally;
+ }
+ else {
+ argc = PyTuple_Size(args);
+
+ if (argc > ARGSZ) {
+ argv = (char **)ckalloc(argc * sizeof(char *));
+ fv = (int *)ckalloc(argc * sizeof(int));
+ if (argv == NULL || fv == NULL) {
+ PyErr_NoMemory();
+ goto finally;
+ }
+ }
+
+ for (i = 0; i < argc; i++) {
+ PyObject *v = PyTuple_GetItem(args, i);
+ if (PyTuple_Check(v)) {
+ fv[i] = 1;
+ if (!(argv[i] = Merge(v)))
+ goto finally;
+ fvc++;
+ }
+ else if (v == Py_None) {
+ argc = i;
+ break;
+ }
+ else {
+ fv[i] = 0;
+ if (!(argv[i] = AsString(v, tmp)))
+ goto finally;
+ fvc++;
+ }
+ }
+ }
+ res = Tcl_Merge(argc, argv);
+ if (res == NULL)
+ PyErr_SetString(Tkinter_TclError, "merge failed");
finally:
- for (i = 0; i < fvc; i++)
- if (fv[i]) {
- ckfree(argv[i]);
- }
- if (argv != argvStore)
- ckfree(FREECAST argv);
- if (fv != fvStore)
- ckfree(FREECAST fv);
+ for (i = 0; i < fvc; i++)
+ if (fv[i]) {
+ ckfree(argv[i]);
+ }
+ if (argv != argvStore)
+ ckfree(FREECAST argv);
+ if (fv != fvStore)
+ ckfree(FREECAST fv);
- Py_DECREF(tmp);
- return res;
+ Py_DECREF(tmp);
+ return res;
}
-
+
static PyObject *
Split(char *list)
{
- int argc;
- char **argv;
- PyObject *v;
-
- if (list == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
- /* Not a list.
- * Could be a quoted string containing funnies, e.g. {"}.
- * Return the string itself.
- */
- return PyUnicode_FromString(list);
- }
-
- if (argc == 0)
- v = PyUnicode_FromString("");
- else if (argc == 1)
- v = PyUnicode_FromString(argv[0]);
- else if ((v = PyTuple_New(argc)) != NULL) {
- int i;
- PyObject *w;
-
- for (i = 0; i < argc; i++) {
- if ((w = Split(argv[i])) == NULL) {
- Py_DECREF(v);
- v = NULL;
- break;
- }
- PyTuple_SetItem(v, i, w);
- }
- }
- Tcl_Free(FREECAST argv);
- return v;
+ int argc;
+ char **argv;
+ PyObject *v;
+
+ if (list == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
+ /* Not a list.
+ * Could be a quoted string containing funnies, e.g. {"}.
+ * Return the string itself.
+ */
+ return PyUnicode_FromString(list);
+ }
+
+ if (argc == 0)
+ v = PyUnicode_FromString("");
+ else if (argc == 1)
+ v = PyUnicode_FromString(argv[0]);
+ else if ((v = PyTuple_New(argc)) != NULL) {
+ int i;
+ PyObject *w;
+
+ for (i = 0; i < argc; i++) {
+ if ((w = Split(argv[i])) == NULL) {
+ Py_DECREF(v);
+ v = NULL;
+ break;
+ }
+ PyTuple_SetItem(v, i, w);
+ }
+ }
+ Tcl_Free(FREECAST argv);
+ return v;
}
/* In some cases, Tcl will still return strings that are supposed to be
@@ -494,103 +494,103 @@ Split(char *list)
static PyObject *
SplitObj(PyObject *arg)
{
- if (PyTuple_Check(arg)) {
- int i, size;
- PyObject *elem, *newelem, *result;
-
- size = PyTuple_Size(arg);
- result = NULL;
- /* Recursively invoke SplitObj for all tuple items.
- If this does not return a new object, no action is
- needed. */
- for(i = 0; i < size; i++) {
- elem = PyTuple_GetItem(arg, i);
- newelem = SplitObj(elem);
- if (!newelem) {
- Py_XDECREF(result);
- return NULL;
- }
- if (!result) {
- int k;
- if (newelem == elem) {
- Py_DECREF(newelem);
- continue;
- }
- result = PyTuple_New(size);
- if (!result)
- return NULL;
- for(k = 0; k < i; k++) {
- elem = PyTuple_GetItem(arg, k);
- Py_INCREF(elem);
- PyTuple_SetItem(result, k, elem);
- }
- }
- PyTuple_SetItem(result, i, newelem);
- }
- if (result)
- return result;
- /* Fall through, returning arg. */
- }
- else if (PyBytes_Check(arg)) {
- int argc;
- char **argv;
- char *list = PyBytes_AsString(arg);
-
- if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
- Py_INCREF(arg);
- return arg;
- }
- Tcl_Free(FREECAST argv);
- if (argc > 1)
- return Split(PyBytes_AsString(arg));
- /* Fall through, returning arg. */
- }
- Py_INCREF(arg);
- return arg;
-}
-
-
+ if (PyTuple_Check(arg)) {
+ int i, size;
+ PyObject *elem, *newelem, *result;
+
+ size = PyTuple_Size(arg);
+ result = NULL;
+ /* Recursively invoke SplitObj for all tuple items.
+ If this does not return a new object, no action is
+ needed. */
+ for(i = 0; i < size; i++) {
+ elem = PyTuple_GetItem(arg, i);
+ newelem = SplitObj(elem);
+ if (!newelem) {
+ Py_XDECREF(result);
+ return NULL;
+ }
+ if (!result) {
+ int k;
+ if (newelem == elem) {
+ Py_DECREF(newelem);
+ continue;
+ }
+ result = PyTuple_New(size);
+ if (!result)
+ return NULL;
+ for(k = 0; k < i; k++) {
+ elem = PyTuple_GetItem(arg, k);
+ Py_INCREF(elem);
+ PyTuple_SetItem(result, k, elem);
+ }
+ }
+ PyTuple_SetItem(result, i, newelem);
+ }
+ if (result)
+ return result;
+ /* Fall through, returning arg. */
+ }
+ else if (PyBytes_Check(arg)) {
+ int argc;
+ char **argv;
+ char *list = PyBytes_AsString(arg);
+
+ if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
+ Py_INCREF(arg);
+ return arg;
+ }
+ Tcl_Free(FREECAST argv);
+ if (argc > 1)
+ return Split(PyBytes_AsString(arg));
+ /* Fall through, returning arg. */
+ }
+ Py_INCREF(arg);
+ return arg;
+}
+
+
/**** Tkapp Object ****/
#ifndef WITH_APPINIT
int
Tcl_AppInit(Tcl_Interp *interp)
{
- const char * _tkinter_skip_tk_init;
+ const char * _tkinter_skip_tk_init;
- if (Tcl_Init(interp) == TCL_ERROR) {
- PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp));
- return TCL_ERROR;
- }
+ if (Tcl_Init(interp) == TCL_ERROR) {
+ PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp));
+ return TCL_ERROR;
+ }
- _tkinter_skip_tk_init = Tcl_GetVar(interp,
- "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
- if (_tkinter_skip_tk_init != NULL &&
- strcmp(_tkinter_skip_tk_init, "1") == 0) {
- return TCL_OK;
- }
+ _tkinter_skip_tk_init = Tcl_GetVar(interp,
+ "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
+ if (_tkinter_skip_tk_init != NULL &&
+ strcmp(_tkinter_skip_tk_init, "1") == 0) {
+ return TCL_OK;
+ }
#ifdef TKINTER_PROTECT_LOADTK
- if (tk_load_failed) {
- PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG);
- return TCL_ERROR;
- }
+ if (tk_load_failed) {
+ PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG);
+ return TCL_ERROR;
+ }
#endif
- if (Tk_Init(interp) == TCL_ERROR) {
+ if (Tk_Init(interp) == TCL_ERROR) {
#ifdef TKINTER_PROTECT_LOADTK
- tk_load_failed = 1;
+ tk_load_failed = 1;
#endif
- PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
- return TCL_ERROR;
- }
+ PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
+ return TCL_ERROR;
+ }
- return TCL_OK;
+ return TCL_OK;
}
#endif /* !WITH_APPINIT */
-
+
/* Initialize the Tk application; see the `main' function in
* `tkMain.c'.
@@ -601,189 +601,189 @@ static void DisableEventHook(void); /* Forward */
static TkappObject *
Tkapp_New(char *screenName, char *className,
- int interactive, int wantobjects, int wantTk, int sync, char *use)
+ int interactive, int wantobjects, int wantTk, int sync, char *use)
{
- TkappObject *v;
- char *argv0;
+ TkappObject *v;
+ char *argv0;
- v = PyObject_New(TkappObject, &Tkapp_Type);
- if (v == NULL)
- return NULL;
+ v = PyObject_New(TkappObject, &Tkapp_Type);
+ if (v == NULL)
+ return NULL;
- v->interp = Tcl_CreateInterp();
- v->wantobjects = wantobjects;
- v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded",
- TCL_GLOBAL_ONLY) != NULL;
- v->thread_id = Tcl_GetCurrentThread();
- v->dispatching = 0;
+ v->interp = Tcl_CreateInterp();
+ v->wantobjects = wantobjects;
+ v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded",
+ TCL_GLOBAL_ONLY) != NULL;
+ v->thread_id = Tcl_GetCurrentThread();
+ v->dispatching = 0;
#ifndef TCL_THREADS
- if (v->threaded) {
- PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not");
- Py_DECREF(v);
- return 0;
- }
+ if (v->threaded) {
+ PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not");
+ Py_DECREF(v);
+ return 0;
+ }
#endif
#ifdef WITH_THREAD
- if (v->threaded && tcl_lock) {
- /* If Tcl is threaded, we don't need the lock. */
- PyThread_free_lock(tcl_lock);
- tcl_lock = NULL;
- }
+ if (v->threaded && tcl_lock) {
+ /* If Tcl is threaded, we don't need the lock. */
+ PyThread_free_lock(tcl_lock);
+ tcl_lock = NULL;
+ }
#endif
- v->BooleanType = Tcl_GetObjType("boolean");
- v->ByteArrayType = Tcl_GetObjType("bytearray");
- v->DoubleType = Tcl_GetObjType("double");
- v->IntType = Tcl_GetObjType("int");
- v->ListType = Tcl_GetObjType("list");
- v->ProcBodyType = Tcl_GetObjType("procbody");
- v->StringType = Tcl_GetObjType("string");
-
- /* Delete the 'exit' command, which can screw things up */
- Tcl_DeleteCommand(v->interp, "exit");
-
- if (screenName != NULL)
- Tcl_SetVar2(v->interp, "env", "DISPLAY",
- screenName, TCL_GLOBAL_ONLY);
-
- if (interactive)
- Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
- else
- Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
-
- /* This is used to get the application class for Tk 4.1 and up */
- argv0 = (char*)ckalloc(strlen(className) + 1);
- if (!argv0) {
- PyErr_NoMemory();
- Py_DECREF(v);
- return NULL;
- }
-
- strcpy(argv0, className);
- if (isupper(Py_CHARMASK(argv0[0])))
- argv0[0] = tolower(Py_CHARMASK(argv0[0]));
- Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
- ckfree(argv0);
-
- if (! wantTk) {
- Tcl_SetVar(v->interp,
- "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY);
- }
+ v->BooleanType = Tcl_GetObjType("boolean");
+ v->ByteArrayType = Tcl_GetObjType("bytearray");
+ v->DoubleType = Tcl_GetObjType("double");
+ v->IntType = Tcl_GetObjType("int");
+ v->ListType = Tcl_GetObjType("list");
+ v->ProcBodyType = Tcl_GetObjType("procbody");
+ v->StringType = Tcl_GetObjType("string");
+
+ /* Delete the 'exit' command, which can screw things up */
+ Tcl_DeleteCommand(v->interp, "exit");
+
+ if (screenName != NULL)
+ Tcl_SetVar2(v->interp, "env", "DISPLAY",
+ screenName, TCL_GLOBAL_ONLY);
+
+ if (interactive)
+ Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
+ else
+ Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
+
+ /* This is used to get the application class for Tk 4.1 and up */
+ argv0 = (char*)ckalloc(strlen(className) + 1);
+ if (!argv0) {
+ PyErr_NoMemory();
+ Py_DECREF(v);
+ return NULL;
+ }
+
+ strcpy(argv0, className);
+ if (isupper(Py_CHARMASK(argv0[0])))
+ argv0[0] = tolower(Py_CHARMASK(argv0[0]));
+ Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
+ ckfree(argv0);
+
+ if (! wantTk) {
+ Tcl_SetVar(v->interp,
+ "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY);
+ }
#ifdef TKINTER_PROTECT_LOADTK
- else if (tk_load_failed) {
- Tcl_SetVar(v->interp,
- "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
- }
+ else if (tk_load_failed) {
+ Tcl_SetVar(v->interp,
+ "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
+ }
#endif
- /* some initial arguments need to be in argv */
- if (sync || use) {
- char *args;
- int len = 0;
-
- if (sync)
- len += sizeof "-sync";
- if (use)
- len += strlen(use) + sizeof "-use ";
-
- args = (char*)ckalloc(len);
- if (!args) {
- PyErr_NoMemory();
- Py_DECREF(v);
- return NULL;
- }
-
- args[0] = '\0';
- if (sync)
- strcat(args, "-sync");
- if (use) {
- if (sync)
- strcat(args, " ");
- strcat(args, "-use ");
- strcat(args, use);
- }
-
- Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY);
- ckfree(args);
- }
-
- if (Tcl_AppInit(v->interp) != TCL_OK) {
- PyObject *result = Tkinter_Error((PyObject *)v);
+ /* some initial arguments need to be in argv */
+ if (sync || use) {
+ char *args;
+ int len = 0;
+
+ if (sync)
+ len += sizeof "-sync";
+ if (use)
+ len += strlen(use) + sizeof "-use ";
+
+ args = (char*)ckalloc(len);
+ if (!args) {
+ PyErr_NoMemory();
+ Py_DECREF(v);
+ return NULL;
+ }
+
+ args[0] = '\0';
+ if (sync)
+ strcat(args, "-sync");
+ if (use) {
+ if (sync)
+ strcat(args, " ");
+ strcat(args, "-use ");
+ strcat(args, use);
+ }
+
+ Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY);
+ ckfree(args);
+ }
+
+ if (Tcl_AppInit(v->interp) != TCL_OK) {
+ PyObject *result = Tkinter_Error((PyObject *)v);
#ifdef TKINTER_PROTECT_LOADTK
- if (wantTk) {
- const char *_tkinter_tk_failed;
- _tkinter_tk_failed = Tcl_GetVar(v->interp,
- "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
-
- if ( _tkinter_tk_failed != NULL &&
- strcmp(_tkinter_tk_failed, "1") == 0) {
- tk_load_failed = 1;
- }
- }
+ if (wantTk) {
+ const char *_tkinter_tk_failed;
+ _tkinter_tk_failed = Tcl_GetVar(v->interp,
+ "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
+
+ if ( _tkinter_tk_failed != NULL &&
+ strcmp(_tkinter_tk_failed, "1") == 0) {
+ tk_load_failed = 1;
+ }
+ }
#endif
- Py_DECREF((PyObject *)v);
- return (TkappObject *)result;
- }
+ Py_DECREF((PyObject *)v);
+ return (TkappObject *)result;
+ }
- EnableEventHook();
+ EnableEventHook();
- return v;
+ return v;
}
#ifdef WITH_THREAD
static void
Tkapp_ThreadSend(TkappObject *self, Tcl_Event *ev,
- Tcl_Condition *cond, Tcl_Mutex *mutex)
+ Tcl_Condition *cond, Tcl_Mutex *mutex)
{
- Py_BEGIN_ALLOW_THREADS;
- Tcl_MutexLock(mutex);
- Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
- Tcl_ThreadAlert(self->thread_id);
- Tcl_ConditionWait(cond, mutex, NULL);
- Tcl_MutexUnlock(mutex);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS;
+ Tcl_MutexLock(mutex);
+ Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
+ Tcl_ThreadAlert(self->thread_id);
+ Tcl_ConditionWait(cond, mutex, NULL);
+ Tcl_MutexUnlock(mutex);
+ Py_END_ALLOW_THREADS
}
#endif
-
+
/** Tcl Eval **/
typedef struct {
- PyObject_HEAD
- Tcl_Obj *value;
- PyObject *string; /* This cannot cause cycles. */
+ PyObject_HEAD
+ Tcl_Obj *value;
+ PyObject *string; /* This cannot cause cycles. */
} PyTclObject;
static PyTypeObject PyTclObject_Type;
-#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type)
+#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type)
static PyObject *
newPyTclObject(Tcl_Obj *arg)
{
- PyTclObject *self;
- self = PyObject_New(PyTclObject, &PyTclObject_Type);
- if (self == NULL)
- return NULL;
- Tcl_IncrRefCount(arg);
- self->value = arg;
- self->string = NULL;
- return (PyObject*)self;
+ PyTclObject *self;
+ self = PyObject_New(PyTclObject, &PyTclObject_Type);
+ if (self == NULL)
+ return NULL;
+ Tcl_IncrRefCount(arg);
+ self->value = arg;
+ self->string = NULL;
+ return (PyObject*)self;
}
static void
PyTclObject_dealloc(PyTclObject *self)
{
- Tcl_DecrRefCount(self->value);
- Py_XDECREF(self->string);
- PyObject_Del(self);
+ Tcl_DecrRefCount(self->value);
+ Py_XDECREF(self->string);
+ PyObject_Del(self);
}
static char*
PyTclObject_TclString(PyObject *self)
{
- return Tcl_GetString(((PyTclObject*)self)->value);
+ return Tcl_GetString(((PyTclObject*)self)->value);
}
/* Like _str, but create Unicode if necessary. */
@@ -793,37 +793,37 @@ PyDoc_STRVAR(PyTclObject_string__doc__,
static PyObject *
PyTclObject_string(PyTclObject *self, void *ignored)
{
- char *s;
- int len;
- if (!self->string) {
- s = Tcl_GetStringFromObj(self->value, &len);
- self->string = PyUnicode_FromStringAndSize(s, len);
- if (!self->string)
- return NULL;
- }
- Py_INCREF(self->string);
- return self->string;
+ char *s;
+ int len;
+ if (!self->string) {
+ s = Tcl_GetStringFromObj(self->value, &len);
+ self->string = PyUnicode_FromStringAndSize(s, len);
+ if (!self->string)
+ return NULL;
+ }
+ Py_INCREF(self->string);
+ return self->string;
}
static PyObject *
PyTclObject_str(PyTclObject *self, void *ignored)
{
- char *s;
- int len;
- if (self->string && PyUnicode_Check(self->string)) {
- Py_INCREF(self->string);
- return self->string;
- }
- /* XXX Could chache result if it is non-ASCII. */
- s = Tcl_GetStringFromObj(self->value, &len);
- return PyUnicode_DecodeUTF8(s, len, "strict");
+ char *s;
+ int len;
+ if (self->string && PyUnicode_Check(self->string)) {
+ Py_INCREF(self->string);
+ return self->string;
+ }
+ /* XXX Could chache result if it is non-ASCII. */
+ s = Tcl_GetStringFromObj(self->value, &len);
+ return PyUnicode_DecodeUTF8(s, len, "strict");
}
static PyObject *
PyTclObject_repr(PyTclObject *self)
{
- return PyUnicode_FromFormat("<%s object at %p>",
- self->value->typePtr->name, self->value);
+ return PyUnicode_FromFormat("<%s object at %p>",
+ self->value->typePtr->name, self->value);
}
#define TEST_COND(cond) ((cond) ? Py_True : Py_False)
@@ -831,54 +831,54 @@ PyTclObject_repr(PyTclObject *self)
static PyObject *
PyTclObject_richcompare(PyObject *self, PyObject *other, int op)
{
- int result;
- PyObject *v;
-
- /* neither argument should be NULL, unless something's gone wrong */
- if (self == NULL || other == NULL) {
- PyErr_BadInternalCall();
- return NULL;
- }
-
- /* both arguments should be instances of PyTclObject */
- if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) {
- v = Py_NotImplemented;
- goto finished;
- }
-
- if (self == other)
- /* fast path when self and other are identical */
- result = 0;
- else
- result = strcmp(Tcl_GetString(((PyTclObject *)self)->value),
- Tcl_GetString(((PyTclObject *)other)->value));
- /* Convert return value to a Boolean */
- switch (op) {
- case Py_EQ:
- v = TEST_COND(result == 0);
- break;
- case Py_NE:
- v = TEST_COND(result != 0);
- break;
- case Py_LE:
- v = TEST_COND(result <= 0);
- break;
- case Py_GE:
- v = TEST_COND(result >= 0);
- break;
- case Py_LT:
- v = TEST_COND(result < 0);
- break;
- case Py_GT:
- v = TEST_COND(result > 0);
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
+ int result;
+ PyObject *v;
+
+ /* neither argument should be NULL, unless something's gone wrong */
+ if (self == NULL || other == NULL) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ /* both arguments should be instances of PyTclObject */
+ if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) {
+ v = Py_NotImplemented;
+ goto finished;
+ }
+
+ if (self == other)
+ /* fast path when self and other are identical */
+ result = 0;
+ else
+ result = strcmp(Tcl_GetString(((PyTclObject *)self)->value),
+ Tcl_GetString(((PyTclObject *)other)->value));
+ /* Convert return value to a Boolean */
+ switch (op) {
+ case Py_EQ:
+ v = TEST_COND(result == 0);
+ break;
+ case Py_NE:
+ v = TEST_COND(result != 0);
+ break;
+ case Py_LE:
+ v = TEST_COND(result <= 0);
+ break;
+ case Py_GE:
+ v = TEST_COND(result >= 0);
+ break;
+ case Py_LT:
+ v = TEST_COND(result < 0);
+ break;
+ case Py_GT:
+ v = TEST_COND(result > 0);
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
finished:
- Py_INCREF(v);
- return v;
+ Py_INCREF(v);
+ return v;
}
PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
@@ -886,230 +886,230 @@ PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
static PyObject*
get_typename(PyTclObject* obj, void* ignored)
{
- return PyUnicode_FromString(obj->value->typePtr->name);
+ return PyUnicode_FromString(obj->value->typePtr->name);
}
static PyGetSetDef PyTclObject_getsetlist[] = {
- {"typename", (getter)get_typename, NULL, get_typename__doc__},
- {"string", (getter)PyTclObject_string, NULL,
- PyTclObject_string__doc__},
- {0},
+ {"typename", (getter)get_typename, NULL, get_typename__doc__},
+ {"string", (getter)PyTclObject_string, NULL,
+ PyTclObject_string__doc__},
+ {0},
};
static PyTypeObject PyTclObject_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_tkinter.Tcl_Obj", /*tp_name*/
- sizeof(PyTclObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)PyTclObject_dealloc,/*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- (reprfunc)PyTclObject_repr, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- (reprfunc)PyTclObject_str, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- PyTclObject_richcompare, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- 0, /*tp_methods*/
- 0, /*tp_members*/
- PyTclObject_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_tkinter.Tcl_Obj", /*tp_name*/
+ sizeof(PyTclObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)PyTclObject_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ (reprfunc)PyTclObject_repr, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ (reprfunc)PyTclObject_str, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ PyTclObject_richcompare, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ 0, /*tp_methods*/
+ 0, /*tp_members*/
+ PyTclObject_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
static Tcl_Obj*
AsObj(PyObject *value)
{
- Tcl_Obj *result;
- long longVal;
- int overflow;
-
- if (PyBytes_Check(value))
- return Tcl_NewStringObj(PyBytes_AS_STRING(value),
- PyBytes_GET_SIZE(value));
- else if (PyBool_Check(value))
- return Tcl_NewBooleanObj(PyObject_IsTrue(value));
- else if (PyLong_CheckExact(value) &&
- ((longVal = PyLong_AsLongAndOverflow(value, &overflow)),
- !overflow)) {
- /* If there is an overflow in the long conversion,
- fall through to default object handling. */
- return Tcl_NewLongObj(longVal);
- }
- else if (PyFloat_Check(value))
- return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
- else if (PyTuple_Check(value)) {
- Tcl_Obj **argv = (Tcl_Obj**)
- ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*));
- int i;
- if(!argv)
- return 0;
- for(i=0;i<PyTuple_Size(value);i++)
- argv[i] = AsObj(PyTuple_GetItem(value,i));
- result = Tcl_NewListObj(PyTuple_Size(value), argv);
- ckfree(FREECAST argv);
- return result;
- }
- else if (PyUnicode_Check(value)) {
- Py_UNICODE *inbuf = PyUnicode_AS_UNICODE(value);
- Py_ssize_t size = PyUnicode_GET_SIZE(value);
- /* This #ifdef assumes that Tcl uses UCS-2.
- See TCL_UTF_MAX test above. */
+ Tcl_Obj *result;
+ long longVal;
+ int overflow;
+
+ if (PyBytes_Check(value))
+ return Tcl_NewStringObj(PyBytes_AS_STRING(value),
+ PyBytes_GET_SIZE(value));
+ else if (PyBool_Check(value))
+ return Tcl_NewBooleanObj(PyObject_IsTrue(value));
+ else if (PyLong_CheckExact(value) &&
+ ((longVal = PyLong_AsLongAndOverflow(value, &overflow)),
+ !overflow)) {
+ /* If there is an overflow in the long conversion,
+ fall through to default object handling. */
+ return Tcl_NewLongObj(longVal);
+ }
+ else if (PyFloat_Check(value))
+ return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
+ else if (PyTuple_Check(value)) {
+ Tcl_Obj **argv = (Tcl_Obj**)
+ ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*));
+ int i;
+ if(!argv)
+ return 0;
+ for(i=0;i<PyTuple_Size(value);i++)
+ argv[i] = AsObj(PyTuple_GetItem(value,i));
+ result = Tcl_NewListObj(PyTuple_Size(value), argv);
+ ckfree(FREECAST argv);
+ return result;
+ }
+ else if (PyUnicode_Check(value)) {
+ Py_UNICODE *inbuf = PyUnicode_AS_UNICODE(value);
+ Py_ssize_t size = PyUnicode_GET_SIZE(value);
+ /* This #ifdef assumes that Tcl uses UCS-2.
+ See TCL_UTF_MAX test above. */
#if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX == 3
- Tcl_UniChar *outbuf = NULL;
- Py_ssize_t i;
- size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar);
- if (allocsize >= size)
- outbuf = (Tcl_UniChar*)ckalloc(allocsize);
- /* Else overflow occurred, and we take the next exit */
- if (!outbuf) {
- PyErr_NoMemory();
- return NULL;
- }
- for (i = 0; i < size; i++) {
- if (inbuf[i] >= 0x10000) {
- /* Tcl doesn't do UTF-16, yet. */
- PyErr_SetString(PyExc_ValueError,
- "unsupported character");
- ckfree(FREECAST outbuf);
- return NULL;
- }
- outbuf[i] = inbuf[i];
- }
- result = Tcl_NewUnicodeObj(outbuf, size);
- ckfree(FREECAST outbuf);
- return result;
+ Tcl_UniChar *outbuf = NULL;
+ Py_ssize_t i;
+ size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar);
+ if (allocsize >= size)
+ outbuf = (Tcl_UniChar*)ckalloc(allocsize);
+ /* Else overflow occurred, and we take the next exit */
+ if (!outbuf) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ for (i = 0; i < size; i++) {
+ if (inbuf[i] >= 0x10000) {
+ /* Tcl doesn't do UTF-16, yet. */
+ PyErr_SetString(PyExc_ValueError,
+ "unsupported character");
+ ckfree(FREECAST outbuf);
+ return NULL;
+ }
+ outbuf[i] = inbuf[i];
+ }
+ result = Tcl_NewUnicodeObj(outbuf, size);
+ ckfree(FREECAST outbuf);
+ return result;
#else
- return Tcl_NewUnicodeObj(inbuf, size);
+ return Tcl_NewUnicodeObj(inbuf, size);
#endif
- }
- else if(PyTclObject_Check(value)) {
- Tcl_Obj *v = ((PyTclObject*)value)->value;
- Tcl_IncrRefCount(v);
- return v;
- }
- else {
- PyObject *v = PyObject_Str(value);
- if (!v)
- return 0;
- result = AsObj(v);
- Py_DECREF(v);
- return result;
- }
+ }
+ else if(PyTclObject_Check(value)) {
+ Tcl_Obj *v = ((PyTclObject*)value)->value;
+ Tcl_IncrRefCount(v);
+ return v;
+ }
+ else {
+ PyObject *v = PyObject_Str(value);
+ if (!v)
+ return 0;
+ result = AsObj(v);
+ Py_DECREF(v);
+ return result;
+ }
}
static PyObject*
FromObj(PyObject* tkapp, Tcl_Obj *value)
{
- PyObject *result = NULL;
- TkappObject *app = (TkappObject*)tkapp;
-
- if (value->typePtr == NULL) {
- return PyUnicode_FromStringAndSize(value->bytes,
- value->length);
- }
-
- if (value->typePtr == app->BooleanType) {
- result = value->internalRep.longValue ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
- }
-
- if (value->typePtr == app->ByteArrayType) {
- int size;
- char *data = (char*)Tcl_GetByteArrayFromObj(value, &size);
- return PyBytes_FromStringAndSize(data, size);
- }
-
- if (value->typePtr == app->DoubleType) {
- return PyFloat_FromDouble(value->internalRep.doubleValue);
- }
-
- if (value->typePtr == app->IntType) {
- return PyLong_FromLong(value->internalRep.longValue);
- }
-
- if (value->typePtr == app->ListType) {
- int size;
- int i, status;
- PyObject *elem;
- Tcl_Obj *tcl_elem;
-
- status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size);
- if (status == TCL_ERROR)
- return Tkinter_Error(tkapp);
- result = PyTuple_New(size);
- if (!result)
- return NULL;
- for (i = 0; i < size; i++) {
- status = Tcl_ListObjIndex(Tkapp_Interp(tkapp),
- value, i, &tcl_elem);
- if (status == TCL_ERROR) {
- Py_DECREF(result);
- return Tkinter_Error(tkapp);
- }
- elem = FromObj(tkapp, tcl_elem);
- if (!elem) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SetItem(result, i, elem);
- }
- return result;
- }
-
- if (value->typePtr == app->ProcBodyType) {
- /* fall through: return tcl object. */
- }
-
- if (value->typePtr == app->StringType) {
+ PyObject *result = NULL;
+ TkappObject *app = (TkappObject*)tkapp;
+
+ if (value->typePtr == NULL) {
+ return PyUnicode_FromStringAndSize(value->bytes,
+ value->length);
+ }
+
+ if (value->typePtr == app->BooleanType) {
+ result = value->internalRep.longValue ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
+ }
+
+ if (value->typePtr == app->ByteArrayType) {
+ int size;
+ char *data = (char*)Tcl_GetByteArrayFromObj(value, &size);
+ return PyBytes_FromStringAndSize(data, size);
+ }
+
+ if (value->typePtr == app->DoubleType) {
+ return PyFloat_FromDouble(value->internalRep.doubleValue);
+ }
+
+ if (value->typePtr == app->IntType) {
+ return PyLong_FromLong(value->internalRep.longValue);
+ }
+
+ if (value->typePtr == app->ListType) {
+ int size;
+ int i, status;
+ PyObject *elem;
+ Tcl_Obj *tcl_elem;
+
+ status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size);
+ if (status == TCL_ERROR)
+ return Tkinter_Error(tkapp);
+ result = PyTuple_New(size);
+ if (!result)
+ return NULL;
+ for (i = 0; i < size; i++) {
+ status = Tcl_ListObjIndex(Tkapp_Interp(tkapp),
+ value, i, &tcl_elem);
+ if (status == TCL_ERROR) {
+ Py_DECREF(result);
+ return Tkinter_Error(tkapp);
+ }
+ elem = FromObj(tkapp, tcl_elem);
+ if (!elem) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SetItem(result, i, elem);
+ }
+ return result;
+ }
+
+ if (value->typePtr == app->ProcBodyType) {
+ /* fall through: return tcl object. */
+ }
+
+ if (value->typePtr == app->StringType) {
#if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==3
- PyObject *result;
- int size;
- Tcl_UniChar *input;
- Py_UNICODE *output;
-
- size = Tcl_GetCharLength(value);
- result = PyUnicode_FromUnicode(NULL, size);
- if (!result)
- return NULL;
- input = Tcl_GetUnicode(value);
- output = PyUnicode_AS_UNICODE(result);
- while (size--)
- *output++ = *input++;
- return result;
+ PyObject *result;
+ int size;
+ Tcl_UniChar *input;
+ Py_UNICODE *output;
+
+ size = Tcl_GetCharLength(value);
+ result = PyUnicode_FromUnicode(NULL, size);
+ if (!result)
+ return NULL;
+ input = Tcl_GetUnicode(value);
+ output = PyUnicode_AS_UNICODE(result);
+ while (size--)
+ *output++ = *input++;
+ return result;
#else
- return PyUnicode_FromUnicode(Tcl_GetUnicode(value),
- Tcl_GetCharLength(value));
+ return PyUnicode_FromUnicode(Tcl_GetUnicode(value),
+ Tcl_GetCharLength(value));
#endif
- }
+ }
- return newPyTclObject(value);
+ return newPyTclObject(value);
}
#ifdef WITH_THREAD
@@ -1117,24 +1117,24 @@ FromObj(PyObject* tkapp, Tcl_Obj *value)
TCL_DECLARE_MUTEX(call_mutex)
typedef struct Tkapp_CallEvent {
- Tcl_Event ev; /* Must be first */
- TkappObject *self;
- PyObject *args;
- int flags;
- PyObject **res;
- PyObject **exc_type, **exc_value, **exc_tb;
- Tcl_Condition *done;
+ Tcl_Event ev; /* Must be first */
+ TkappObject *self;
+ PyObject *args;
+ int flags;
+ PyObject **res;
+ PyObject **exc_type, **exc_value, **exc_tb;
+ Tcl_Condition *done;
} Tkapp_CallEvent;
#endif
void
Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc)
{
- int i;
- for (i = 0; i < objc; i++)
- Tcl_DecrRefCount(objv[i]);
- if (objv != objStore)
- ckfree(FREECAST objv);
+ int i;
+ for (i = 0; i < objc; i++)
+ Tcl_DecrRefCount(objv[i]);
+ if (objv != objStore)
+ ckfree(FREECAST objv);
}
/* Convert Python objects to Tcl objects. This must happen in the
@@ -1143,51 +1143,51 @@ Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc)
static Tcl_Obj**
Tkapp_CallArgs(PyObject *args, Tcl_Obj** objStore, int *pobjc)
{
- Tcl_Obj **objv = objStore;
- int objc = 0, i;
- if (args == NULL)
- /* do nothing */;
-
- else if (!PyTuple_Check(args)) {
- objv[0] = AsObj(args);
- if (objv[0] == 0)
- goto finally;
- objc = 1;
- Tcl_IncrRefCount(objv[0]);
- }
- else {
- objc = PyTuple_Size(args);
-
- if (objc > ARGSZ) {
- objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
- if (objv == NULL) {
- PyErr_NoMemory();
- objc = 0;
- goto finally;
- }
- }
-
- for (i = 0; i < objc; i++) {
- PyObject *v = PyTuple_GetItem(args, i);
- if (v == Py_None) {
- objc = i;
- break;
- }
- objv[i] = AsObj(v);
- if (!objv[i]) {
- /* Reset objc, so it attempts to clear
- objects only up to i. */
- objc = i;
- goto finally;
- }
- Tcl_IncrRefCount(objv[i]);
- }
- }
- *pobjc = objc;
- return objv;
+ Tcl_Obj **objv = objStore;
+ int objc = 0, i;
+ if (args == NULL)
+ /* do nothing */;
+
+ else if (!PyTuple_Check(args)) {
+ objv[0] = AsObj(args);
+ if (objv[0] == 0)
+ goto finally;
+ objc = 1;
+ Tcl_IncrRefCount(objv[0]);
+ }
+ else {
+ objc = PyTuple_Size(args);
+
+ if (objc > ARGSZ) {
+ objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
+ if (objv == NULL) {
+ PyErr_NoMemory();
+ objc = 0;
+ goto finally;
+ }
+ }
+
+ for (i = 0; i < objc; i++) {
+ PyObject *v = PyTuple_GetItem(args, i);
+ if (v == Py_None) {
+ objc = i;
+ break;
+ }
+ objv[i] = AsObj(v);
+ if (!objv[i]) {
+ /* Reset objc, so it attempts to clear
+ objects only up to i. */
+ objc = i;
+ goto finally;
+ }
+ Tcl_IncrRefCount(objv[i]);
+ }
+ }
+ *pobjc = objc;
+ return objv;
finally:
- Tkapp_CallDeallocArgs(objv, objStore, objc);
- return NULL;
+ Tkapp_CallDeallocArgs(objv, objStore, objc);
+ return NULL;
}
/* Convert the results of a command call into a Python objects. */
@@ -1195,22 +1195,22 @@ finally:
static PyObject*
Tkapp_CallResult(TkappObject *self)
{
- PyObject *res = NULL;
- if(self->wantobjects) {
- Tcl_Obj *value = Tcl_GetObjResult(self->interp);
- /* Not sure whether the IncrRef is necessary, but something
- may overwrite the interpreter result while we are
- converting it. */
- Tcl_IncrRefCount(value);
- res = FromObj((PyObject*)self, value);
- Tcl_DecrRefCount(value);
- } else {
- const char *s = Tcl_GetStringResult(self->interp);
- const char *p = s;
+ PyObject *res = NULL;
+ if(self->wantobjects) {
+ Tcl_Obj *value = Tcl_GetObjResult(self->interp);
+ /* Not sure whether the IncrRef is necessary, but something
+ may overwrite the interpreter result while we are
+ converting it. */
+ Tcl_IncrRefCount(value);
+ res = FromObj((PyObject*)self, value);
+ Tcl_DecrRefCount(value);
+ } else {
+ const char *s = Tcl_GetStringResult(self->interp);
+ const char *p = s;
- res = PyUnicode_FromStringAndSize(s, (int)(p-s));
- }
- return res;
+ res = PyUnicode_FromStringAndSize(s, (int)(p-s));
+ }
+ return res;
}
#ifdef WITH_THREAD
@@ -1222,41 +1222,41 @@ Tkapp_CallResult(TkappObject *self)
static int
Tkapp_CallProc(Tkapp_CallEvent *e, int flags)
{
- Tcl_Obj *objStore[ARGSZ];
- Tcl_Obj **objv;
- int objc;
- int i;
- ENTER_PYTHON
- objv = Tkapp_CallArgs(e->args, objStore, &objc);
- if (!objv) {
- PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb);
- *(e->res) = NULL;
- }
- LEAVE_PYTHON
- if (!objv)
- goto done;
- i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags);
- ENTER_PYTHON
- if (i == TCL_ERROR) {
- *(e->res) = NULL;
- *(e->exc_type) = NULL;
- *(e->exc_tb) = NULL;
- *(e->exc_value) = PyObject_CallFunction(
- Tkinter_TclError, "s",
- Tcl_GetStringResult(e->self->interp));
- }
- else {
- *(e->res) = Tkapp_CallResult(e->self);
- }
- LEAVE_PYTHON
-
- Tkapp_CallDeallocArgs(objv, objStore, objc);
+ Tcl_Obj *objStore[ARGSZ];
+ Tcl_Obj **objv;
+ int objc;
+ int i;
+ ENTER_PYTHON
+ objv = Tkapp_CallArgs(e->args, objStore, &objc);
+ if (!objv) {
+ PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb);
+ *(e->res) = NULL;
+ }
+ LEAVE_PYTHON
+ if (!objv)
+ goto done;
+ i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags);
+ ENTER_PYTHON
+ if (i == TCL_ERROR) {
+ *(e->res) = NULL;
+ *(e->exc_type) = NULL;
+ *(e->exc_tb) = NULL;
+ *(e->exc_value) = PyObject_CallFunction(
+ Tkinter_TclError, "s",
+ Tcl_GetStringResult(e->self->interp));
+ }
+ else {
+ *(e->res) = Tkapp_CallResult(e->self);
+ }
+ LEAVE_PYTHON
+
+ Tkapp_CallDeallocArgs(objv, objStore, objc);
done:
- /* Wake up calling thread. */
- Tcl_MutexLock(&call_mutex);
- Tcl_ConditionNotify(e->done);
- Tcl_MutexUnlock(&call_mutex);
- return 1;
+ /* Wake up calling thread. */
+ Tcl_MutexLock(&call_mutex);
+ Tcl_ConditionNotify(e->done);
+ Tcl_MutexUnlock(&call_mutex);
+ return 1;
}
#endif
@@ -1276,218 +1276,218 @@ done:
static PyObject *
Tkapp_Call(PyObject *selfptr, PyObject *args)
{
- Tcl_Obj *objStore[ARGSZ];
- Tcl_Obj **objv = NULL;
- int objc, i;
- PyObject *res = NULL;
- TkappObject *self = (TkappObject*)selfptr;
- int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL;
-
- /* If args is a single tuple, replace with contents of tuple */
- if (1 == PyTuple_Size(args)){
- PyObject* item = PyTuple_GetItem(args, 0);
- if (PyTuple_Check(item))
- args = item;
- }
+ Tcl_Obj *objStore[ARGSZ];
+ Tcl_Obj **objv = NULL;
+ int objc, i;
+ PyObject *res = NULL;
+ TkappObject *self = (TkappObject*)selfptr;
+ int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL;
+
+ /* If args is a single tuple, replace with contents of tuple */
+ if (1 == PyTuple_Size(args)){
+ PyObject* item = PyTuple_GetItem(args, 0);
+ if (PyTuple_Check(item))
+ args = item;
+ }
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- /* We cannot call the command directly. Instead, we must
- marshal the parameters to the interpreter thread. */
- Tkapp_CallEvent *ev;
- Tcl_Condition cond = NULL;
- PyObject *exc_type, *exc_value, *exc_tb;
- if (!WaitForMainloop(self))
- return NULL;
- ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent));
- ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc;
- ev->self = self;
- ev->args = args;
- ev->res = &res;
- ev->exc_type = &exc_type;
- ev->exc_value = &exc_value;
- ev->exc_tb = &exc_tb;
- ev->done = &cond;
-
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex);
-
- if (res == NULL) {
- if (exc_type)
- PyErr_Restore(exc_type, exc_value, exc_tb);
- else
- PyErr_SetObject(Tkinter_TclError, exc_value);
- }
- Tcl_ConditionFinalize(&cond);
- }
- else
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ /* We cannot call the command directly. Instead, we must
+ marshal the parameters to the interpreter thread. */
+ Tkapp_CallEvent *ev;
+ Tcl_Condition cond = NULL;
+ PyObject *exc_type, *exc_value, *exc_tb;
+ if (!WaitForMainloop(self))
+ return NULL;
+ ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent));
+ ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc;
+ ev->self = self;
+ ev->args = args;
+ ev->res = &res;
+ ev->exc_type = &exc_type;
+ ev->exc_value = &exc_value;
+ ev->exc_tb = &exc_tb;
+ ev->done = &cond;
+
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex);
+
+ if (res == NULL) {
+ if (exc_type)
+ PyErr_Restore(exc_type, exc_value, exc_tb);
+ else
+ PyErr_SetObject(Tkinter_TclError, exc_value);
+ }
+ Tcl_ConditionFinalize(&cond);
+ }
+ else
#endif
- {
+ {
- objv = Tkapp_CallArgs(args, objStore, &objc);
- if (!objv)
- return NULL;
+ objv = Tkapp_CallArgs(args, objStore, &objc);
+ if (!objv)
+ return NULL;
- ENTER_TCL
+ ENTER_TCL
- i = Tcl_EvalObjv(self->interp, objc, objv, flags);
+ i = Tcl_EvalObjv(self->interp, objc, objv, flags);
- ENTER_OVERLAP
+ ENTER_OVERLAP
- if (i == TCL_ERROR)
- Tkinter_Error(selfptr);
- else
- res = Tkapp_CallResult(self);
+ if (i == TCL_ERROR)
+ Tkinter_Error(selfptr);
+ else
+ res = Tkapp_CallResult(self);
- LEAVE_OVERLAP_TCL
+ LEAVE_OVERLAP_TCL
- Tkapp_CallDeallocArgs(objv, objStore, objc);
- }
- return res;
+ Tkapp_CallDeallocArgs(objv, objStore, objc);
+ }
+ return res;
}
static PyObject *
Tkapp_GlobalCall(PyObject *self, PyObject *args)
{
- /* Could do the same here as for Tkapp_Call(), but this is not used
- much, so I can't be bothered. Unfortunately Tcl doesn't export a
- way for the user to do what all its Global* variants do (save and
- reset the scope pointer, call the local version, restore the saved
- scope pointer). */
+ /* Could do the same here as for Tkapp_Call(), but this is not used
+ much, so I can't be bothered. Unfortunately Tcl doesn't export a
+ way for the user to do what all its Global* variants do (save and
+ reset the scope pointer, call the local version, restore the saved
+ scope pointer). */
- char *cmd;
- PyObject *res = NULL;
+ char *cmd;
+ PyObject *res = NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- cmd = Merge(args);
- if (cmd) {
- int err;
- ENTER_TCL
- err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyUnicode_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- ckfree(cmd);
- }
+ cmd = Merge(args);
+ if (cmd) {
+ int err;
+ ENTER_TCL
+ err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyUnicode_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ ckfree(cmd);
+ }
- return res;
+ return res;
}
static PyObject *
Tkapp_Eval(PyObject *self, PyObject *args)
{
- char *script;
- PyObject *res = NULL;
- int err;
+ char *script;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s:eval", &script))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:eval", &script))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_Eval(Tkapp_Interp(self), script);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyUnicode_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ err = Tcl_Eval(Tkapp_Interp(self), script);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyUnicode_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_GlobalEval(PyObject *self, PyObject *args)
{
- char *script;
- PyObject *res = NULL;
- int err;
+ char *script;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s:globaleval", &script))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:globaleval", &script))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_GlobalEval(Tkapp_Interp(self), script);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyUnicode_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ err = Tcl_GlobalEval(Tkapp_Interp(self), script);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyUnicode_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_EvalFile(PyObject *self, PyObject *args)
{
- char *fileName;
- PyObject *res = NULL;
- int err;
+ char *fileName;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s:evalfile", &fileName))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:evalfile", &fileName))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
+ ENTER_TCL
+ err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
- else
- res = PyUnicode_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ else
+ res = PyUnicode_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_Record(PyObject *self, PyObject *args)
{
- char *script;
- PyObject *res = NULL;
- int err;
+ char *script;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s", &script))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s", &script))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyUnicode_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyUnicode_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_AddErrorInfo(PyObject *self, PyObject *args)
{
- char *msg;
+ char *msg;
- if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg))
- return NULL;
- CHECK_TCL_APPARTMENT;
+ if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg))
+ return NULL;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
- LEAVE_TCL
+ ENTER_TCL
+ Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
+ LEAVE_TCL
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
/** Tcl Variable **/
typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags);
@@ -1496,36 +1496,36 @@ typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags);
TCL_DECLARE_MUTEX(var_mutex)
typedef struct VarEvent {
- Tcl_Event ev; /* must be first */
- PyObject *self;
- PyObject *args;
- int flags;
- EventFunc func;
- PyObject **res;
- PyObject **exc_type;
- PyObject **exc_val;
- Tcl_Condition *cond;
+ Tcl_Event ev; /* must be first */
+ PyObject *self;
+ PyObject *args;
+ int flags;
+ EventFunc func;
+ PyObject **res;
+ PyObject **exc_type;
+ PyObject **exc_val;
+ Tcl_Condition *cond;
} VarEvent;
#endif
static int
varname_converter(PyObject *in, void *_out)
{
- char **out = (char**)_out;
- if (PyBytes_Check(in)) {
- *out = PyBytes_AsString(in);
- return 1;
- }
- if (PyUnicode_Check(in)) {
- *out = _PyUnicode_AsString(in);
- return 1;
- }
- if (PyTclObject_Check(in)) {
- *out = PyTclObject_TclString(in);
- return 1;
- }
- /* XXX: Should give diagnostics. */
- return 0;
+ char **out = (char**)_out;
+ if (PyBytes_Check(in)) {
+ *out = PyBytes_AsString(in);
+ return 1;
+ }
+ if (PyUnicode_Check(in)) {
+ *out = _PyUnicode_AsString(in);
+ return 1;
+ }
+ if (PyTclObject_Check(in)) {
+ *out = PyTclObject_TclString(in);
+ return 1;
+ }
+ /* XXX: Should give diagnostics. */
+ return 0;
}
#ifdef WITH_THREAD
@@ -1533,28 +1533,28 @@ varname_converter(PyObject *in, void *_out)
static void
var_perform(VarEvent *ev)
{
- *(ev->res) = ev->func(ev->self, ev->args, ev->flags);
- if (!*(ev->res)) {
- PyObject *exc, *val, *tb;
- PyErr_Fetch(&exc, &val, &tb);
- PyErr_NormalizeException(&exc, &val, &tb);
- *(ev->exc_type) = exc;
- *(ev->exc_val) = val;
- Py_DECREF(tb);
- }
+ *(ev->res) = ev->func(ev->self, ev->args, ev->flags);
+ if (!*(ev->res)) {
+ PyObject *exc, *val, *tb;
+ PyErr_Fetch(&exc, &val, &tb);
+ PyErr_NormalizeException(&exc, &val, &tb);
+ *(ev->exc_type) = exc;
+ *(ev->exc_val) = val;
+ Py_DECREF(tb);
+ }
}
static int
var_proc(VarEvent* ev, int flags)
{
- ENTER_PYTHON
- var_perform(ev);
- Tcl_MutexLock(&var_mutex);
- Tcl_ConditionNotify(ev->cond);
- Tcl_MutexUnlock(&var_mutex);
- LEAVE_PYTHON
- return 1;
+ ENTER_PYTHON
+ var_perform(ev);
+ Tcl_MutexLock(&var_mutex);
+ Tcl_ConditionNotify(ev->cond);
+ Tcl_MutexUnlock(&var_mutex);
+ LEAVE_PYTHON
+ return 1;
}
#endif
@@ -1563,439 +1563,439 @@ static PyObject*
var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags)
{
#ifdef WITH_THREAD
- TkappObject *self = (TkappObject*)selfptr;
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- TkappObject *self = (TkappObject*)selfptr;
- VarEvent *ev;
- PyObject *res, *exc_type, *exc_val;
- Tcl_Condition cond = NULL;
-
- /* The current thread is not the interpreter thread. Marshal
- the call to the interpreter thread, then wait for
- completion. */
- if (!WaitForMainloop(self))
- return NULL;
-
- ev = (VarEvent*)ckalloc(sizeof(VarEvent));
-
- ev->self = selfptr;
- ev->args = args;
- ev->flags = flags;
- ev->func = func;
- ev->res = &res;
- ev->exc_type = &exc_type;
- ev->exc_val = &exc_val;
- ev->cond = &cond;
- ev->ev.proc = (Tcl_EventProc*)var_proc;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex);
- Tcl_ConditionFinalize(&cond);
- if (!res) {
- PyErr_SetObject(exc_type, exc_val);
- Py_DECREF(exc_type);
- Py_DECREF(exc_val);
- return NULL;
- }
- return res;
- }
+ TkappObject *self = (TkappObject*)selfptr;
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ TkappObject *self = (TkappObject*)selfptr;
+ VarEvent *ev;
+ PyObject *res, *exc_type, *exc_val;
+ Tcl_Condition cond = NULL;
+
+ /* The current thread is not the interpreter thread. Marshal
+ the call to the interpreter thread, then wait for
+ completion. */
+ if (!WaitForMainloop(self))
+ return NULL;
+
+ ev = (VarEvent*)ckalloc(sizeof(VarEvent));
+
+ ev->self = selfptr;
+ ev->args = args;
+ ev->flags = flags;
+ ev->func = func;
+ ev->res = &res;
+ ev->exc_type = &exc_type;
+ ev->exc_val = &exc_val;
+ ev->cond = &cond;
+ ev->ev.proc = (Tcl_EventProc*)var_proc;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex);
+ Tcl_ConditionFinalize(&cond);
+ if (!res) {
+ PyErr_SetObject(exc_type, exc_val);
+ Py_DECREF(exc_type);
+ Py_DECREF(exc_val);
+ return NULL;
+ }
+ return res;
+ }
#endif
- /* Tcl is not threaded, or this is the interpreter thread. */
- return func(selfptr, args, flags);
+ /* Tcl is not threaded, or this is the interpreter thread. */
+ return func(selfptr, args, flags);
}
static PyObject *
SetVar(PyObject *self, PyObject *args, int flags)
{
- char *name1, *name2;
- PyObject *newValue;
- PyObject *res = NULL;
- Tcl_Obj *newval, *ok;
-
- if (PyArg_ParseTuple(args, "O&O:setvar",
- varname_converter, &name1, &newValue)) {
- /* XXX Acquire tcl lock??? */
- newval = AsObj(newValue);
- if (newval == NULL)
- return NULL;
- ENTER_TCL
- ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL,
- newval, flags);
- ENTER_OVERLAP
- if (!ok)
- Tkinter_Error(self);
- else {
- res = Py_None;
- Py_INCREF(res);
- }
- LEAVE_OVERLAP_TCL
- }
- else {
- PyErr_Clear();
- if (PyArg_ParseTuple(args, "ssO:setvar",
- &name1, &name2, &newValue)) {
- /* XXX must hold tcl lock already??? */
- newval = AsObj(newValue);
- ENTER_TCL
- ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags);
- ENTER_OVERLAP
- if (!ok)
- Tkinter_Error(self);
- else {
- res = Py_None;
- Py_INCREF(res);
- }
- LEAVE_OVERLAP_TCL
- }
- else {
- return NULL;
- }
- }
- return res;
+ char *name1, *name2;
+ PyObject *newValue;
+ PyObject *res = NULL;
+ Tcl_Obj *newval, *ok;
+
+ if (PyArg_ParseTuple(args, "O&O:setvar",
+ varname_converter, &name1, &newValue)) {
+ /* XXX Acquire tcl lock??? */
+ newval = AsObj(newValue);
+ if (newval == NULL)
+ return NULL;
+ ENTER_TCL
+ ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL,
+ newval, flags);
+ ENTER_OVERLAP
+ if (!ok)
+ Tkinter_Error(self);
+ else {
+ res = Py_None;
+ Py_INCREF(res);
+ }
+ LEAVE_OVERLAP_TCL
+ }
+ else {
+ PyErr_Clear();
+ if (PyArg_ParseTuple(args, "ssO:setvar",
+ &name1, &name2, &newValue)) {
+ /* XXX must hold tcl lock already??? */
+ newval = AsObj(newValue);
+ ENTER_TCL
+ ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags);
+ ENTER_OVERLAP
+ if (!ok)
+ Tkinter_Error(self);
+ else {
+ res = Py_None;
+ Py_INCREF(res);
+ }
+ LEAVE_OVERLAP_TCL
+ }
+ else {
+ return NULL;
+ }
+ }
+ return res;
}
static PyObject *
Tkapp_SetVar(PyObject *self, PyObject *args)
{
- return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG);
+ return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG);
}
static PyObject *
Tkapp_GlobalSetVar(PyObject *self, PyObject *args)
{
- return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
+ return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
}
-
+
static PyObject *
GetVar(PyObject *self, PyObject *args, int flags)
{
- char *name1, *name2=NULL;
- PyObject *res = NULL;
- Tcl_Obj *tres;
-
- if (!PyArg_ParseTuple(args, "O&|s:getvar",
- varname_converter, &name1, &name2))
- return NULL;
-
- ENTER_TCL
- tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags);
- ENTER_OVERLAP
- if (tres == NULL) {
- PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
- } else {
- if (((TkappObject*)self)->wantobjects) {
- res = FromObj(self, tres);
- }
- else {
- res = PyUnicode_FromString(Tcl_GetString(tres));
- }
- }
- LEAVE_OVERLAP_TCL
- return res;
+ char *name1, *name2=NULL;
+ PyObject *res = NULL;
+ Tcl_Obj *tres;
+
+ if (!PyArg_ParseTuple(args, "O&|s:getvar",
+ varname_converter, &name1, &name2))
+ return NULL;
+
+ ENTER_TCL
+ tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags);
+ ENTER_OVERLAP
+ if (tres == NULL) {
+ PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
+ } else {
+ if (((TkappObject*)self)->wantobjects) {
+ res = FromObj(self, tres);
+ }
+ else {
+ res = PyUnicode_FromString(Tcl_GetString(tres));
+ }
+ }
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_GetVar(PyObject *self, PyObject *args)
{
- return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG);
+ return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG);
}
static PyObject *
Tkapp_GlobalGetVar(PyObject *self, PyObject *args)
{
- return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
+ return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
}
-
+
static PyObject *
UnsetVar(PyObject *self, PyObject *args, int flags)
{
- char *name1, *name2=NULL;
- int code;
- PyObject *res = NULL;
+ char *name1, *name2=NULL;
+ int code;
+ PyObject *res = NULL;
- if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2))
+ return NULL;
- ENTER_TCL
- code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
- ENTER_OVERLAP
- if (code == TCL_ERROR)
- res = Tkinter_Error(self);
- else {
- Py_INCREF(Py_None);
- res = Py_None;
- }
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
+ ENTER_OVERLAP
+ if (code == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else {
+ Py_INCREF(Py_None);
+ res = Py_None;
+ }
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_UnsetVar(PyObject *self, PyObject *args)
{
- return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG);
+ return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG);
}
static PyObject *
Tkapp_GlobalUnsetVar(PyObject *self, PyObject *args)
{
- return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
+ return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
}
-
+
/** Tcl to Python **/
static PyObject *
Tkapp_GetInt(PyObject *self, PyObject *args)
{
- char *s;
- int v;
+ char *s;
+ int v;
- if (PyTuple_Size(args) == 1) {
- PyObject* o = PyTuple_GetItem(args, 0);
- if (PyLong_Check(o)) {
- Py_INCREF(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "s:getint", &s))
- return NULL;
- if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
- return Tkinter_Error(self);
- return Py_BuildValue("i", v);
+ if (PyTuple_Size(args) == 1) {
+ PyObject* o = PyTuple_GetItem(args, 0);
+ if (PyLong_Check(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "s:getint", &s))
+ return NULL;
+ if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+ return Tkinter_Error(self);
+ return Py_BuildValue("i", v);
}
static PyObject *
Tkapp_GetDouble(PyObject *self, PyObject *args)
{
- char *s;
- double v;
+ char *s;
+ double v;
- if (PyTuple_Size(args) == 1) {
- PyObject *o = PyTuple_GetItem(args, 0);
- if (PyFloat_Check(o)) {
- Py_INCREF(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "s:getdouble", &s))
- return NULL;
- if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
- return Tkinter_Error(self);
- return Py_BuildValue("d", v);
+ if (PyTuple_Size(args) == 1) {
+ PyObject *o = PyTuple_GetItem(args, 0);
+ if (PyFloat_Check(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "s:getdouble", &s))
+ return NULL;
+ if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+ return Tkinter_Error(self);
+ return Py_BuildValue("d", v);
}
static PyObject *
Tkapp_GetBoolean(PyObject *self, PyObject *args)
{
- char *s;
- int v;
+ char *s;
+ int v;
- if (PyTuple_Size(args) == 1) {
- PyObject *o = PyTuple_GetItem(args, 0);
- if (PyLong_Check(o)) {
- Py_INCREF(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "s:getboolean", &s))
- return NULL;
- if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
- return Tkinter_Error(self);
- return PyBool_FromLong(v);
+ if (PyTuple_Size(args) == 1) {
+ PyObject *o = PyTuple_GetItem(args, 0);
+ if (PyLong_Check(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "s:getboolean", &s))
+ return NULL;
+ if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+ return Tkinter_Error(self);
+ return PyBool_FromLong(v);
}
static PyObject *
Tkapp_ExprString(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- int retval;
+ char *s;
+ PyObject *res = NULL;
+ int retval;
- if (!PyArg_ParseTuple(args, "s:exprstring", &s))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:exprstring", &s))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- retval = Tcl_ExprString(Tkapp_Interp(self), s);
- ENTER_OVERLAP
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("s", Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ retval = Tcl_ExprString(Tkapp_Interp(self), s);
+ ENTER_OVERLAP
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("s", Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_ExprLong(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- int retval;
- long v;
+ char *s;
+ PyObject *res = NULL;
+ int retval;
+ long v;
- if (!PyArg_ParseTuple(args, "s:exprlong", &s))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:exprlong", &s))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
- ENTER_OVERLAP
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("l", v);
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
+ ENTER_OVERLAP
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("l", v);
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_ExprDouble(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- double v;
- int retval;
-
- if (!PyArg_ParseTuple(args, "s:exprdouble", &s))
- return NULL;
- CHECK_TCL_APPARTMENT;
- PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
- ENTER_TCL
- retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
- ENTER_OVERLAP
- PyFPE_END_PROTECT(retval)
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("d", v);
- LEAVE_OVERLAP_TCL
- return res;
+ char *s;
+ PyObject *res = NULL;
+ double v;
+ int retval;
+
+ if (!PyArg_ParseTuple(args, "s:exprdouble", &s))
+ return NULL;
+ CHECK_TCL_APPARTMENT;
+ PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
+ ENTER_TCL
+ retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
+ ENTER_OVERLAP
+ PyFPE_END_PROTECT(retval)
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("d", v);
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_ExprBoolean(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- int retval;
- int v;
+ char *s;
+ PyObject *res = NULL;
+ int retval;
+ int v;
- if (!PyArg_ParseTuple(args, "s:exprboolean", &s))
- return NULL;
- CHECK_TCL_APPARTMENT;
- ENTER_TCL
- retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
- ENTER_OVERLAP
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("i", v);
- LEAVE_OVERLAP_TCL
- return res;
+ if (!PyArg_ParseTuple(args, "s:exprboolean", &s))
+ return NULL;
+ CHECK_TCL_APPARTMENT;
+ ENTER_TCL
+ retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
+ ENTER_OVERLAP
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("i", v);
+ LEAVE_OVERLAP_TCL
+ return res;
}
-
+
static PyObject *
Tkapp_SplitList(PyObject *self, PyObject *args)
{
- char *list;
- int argc;
- char **argv;
- PyObject *v;
- int i;
-
- if (PyTuple_Size(args) == 1) {
- v = PyTuple_GetItem(args, 0);
- if (PyTuple_Check(v)) {
- Py_INCREF(v);
- return v;
- }
- }
- if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list))
- return NULL;
-
- if (Tcl_SplitList(Tkapp_Interp(self), list,
- &argc, &argv) == TCL_ERROR) {
- PyMem_Free(list);
- return Tkinter_Error(self);
- }
-
- if (!(v = PyTuple_New(argc)))
- goto finally;
-
- for (i = 0; i < argc; i++) {
- PyObject *s = PyUnicode_FromString(argv[i]);
- if (!s || PyTuple_SetItem(v, i, s)) {
- Py_DECREF(v);
- v = NULL;
- goto finally;
- }
- }
+ char *list;
+ int argc;
+ char **argv;
+ PyObject *v;
+ int i;
+
+ if (PyTuple_Size(args) == 1) {
+ v = PyTuple_GetItem(args, 0);
+ if (PyTuple_Check(v)) {
+ Py_INCREF(v);
+ return v;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list))
+ return NULL;
+
+ if (Tcl_SplitList(Tkapp_Interp(self), list,
+ &argc, &argv) == TCL_ERROR) {
+ PyMem_Free(list);
+ return Tkinter_Error(self);
+ }
+
+ if (!(v = PyTuple_New(argc)))
+ goto finally;
+
+ for (i = 0; i < argc; i++) {
+ PyObject *s = PyUnicode_FromString(argv[i]);
+ if (!s || PyTuple_SetItem(v, i, s)) {
+ Py_DECREF(v);
+ v = NULL;
+ goto finally;
+ }
+ }
finally:
- ckfree(FREECAST argv);
- PyMem_Free(list);
- return v;
+ ckfree(FREECAST argv);
+ PyMem_Free(list);
+ return v;
}
static PyObject *
Tkapp_Split(PyObject *self, PyObject *args)
{
- PyObject *v;
- char *list;
+ PyObject *v;
+ char *list;
- if (PyTuple_Size(args) == 1) {
- PyObject* o = PyTuple_GetItem(args, 0);
- if (PyTuple_Check(o)) {
- o = SplitObj(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list))
- return NULL;
- v = Split(list);
- PyMem_Free(list);
- return v;
+ if (PyTuple_Size(args) == 1) {
+ PyObject* o = PyTuple_GetItem(args, 0);
+ if (PyTuple_Check(o)) {
+ o = SplitObj(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list))
+ return NULL;
+ v = Split(list);
+ PyMem_Free(list);
+ return v;
}
static PyObject *
Tkapp_Merge(PyObject *self, PyObject *args)
{
- char *s = Merge(args);
- PyObject *res = NULL;
+ char *s = Merge(args);
+ PyObject *res = NULL;
- if (s) {
- res = PyUnicode_FromString(s);
- ckfree(s);
- }
+ if (s) {
+ res = PyUnicode_FromString(s);
+ ckfree(s);
+ }
- return res;
+ return res;
}
-
+
/** Tcl Command **/
/* Client data struct */
typedef struct {
- PyObject *self;
- PyObject *func;
+ PyObject *self;
+ PyObject *func;
} PythonCmd_ClientData;
static int
PythonCmd_Error(Tcl_Interp *interp)
{
- errorInCmd = 1;
- PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
- LEAVE_PYTHON
- return TCL_ERROR;
+ errorInCmd = 1;
+ PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
+ LEAVE_PYTHON
+ return TCL_ERROR;
}
/* This is the Tcl command that acts as a wrapper for Python
@@ -2004,211 +2004,211 @@ PythonCmd_Error(Tcl_Interp *interp)
static int
PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])
{
- PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
- PyObject *self, *func, *arg, *res;
- int i, rv;
- Tcl_Obj *obj_res;
+ PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
+ PyObject *self, *func, *arg, *res;
+ int i, rv;
+ Tcl_Obj *obj_res;
- ENTER_PYTHON
+ ENTER_PYTHON
- /* TBD: no error checking here since we know, via the
- * Tkapp_CreateCommand() that the client data is a two-tuple
- */
- self = data->self;
- func = data->func;
+ /* TBD: no error checking here since we know, via the
+ * Tkapp_CreateCommand() that the client data is a two-tuple
+ */
+ self = data->self;
+ func = data->func;
- /* Create argument list (argv1, ..., argvN) */
- if (!(arg = PyTuple_New(argc - 1)))
- return PythonCmd_Error(interp);
+ /* Create argument list (argv1, ..., argvN) */
+ if (!(arg = PyTuple_New(argc - 1)))
+ return PythonCmd_Error(interp);
- for (i = 0; i < (argc - 1); i++) {
- PyObject *s = PyUnicode_FromString(argv[i + 1]);
- if (!s || PyTuple_SetItem(arg, i, s)) {
- Py_DECREF(arg);
- return PythonCmd_Error(interp);
- }
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
+ for (i = 0; i < (argc - 1); i++) {
+ PyObject *s = PyUnicode_FromString(argv[i + 1]);
+ if (!s || PyTuple_SetItem(arg, i, s)) {
+ Py_DECREF(arg);
+ return PythonCmd_Error(interp);
+ }
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
- if (res == NULL)
- return PythonCmd_Error(interp);
+ if (res == NULL)
+ return PythonCmd_Error(interp);
- obj_res = AsObj(res);
- if (obj_res == NULL) {
- Py_DECREF(res);
- return PythonCmd_Error(interp);
- }
- else {
- Tcl_SetObjResult(interp, obj_res);
- rv = TCL_OK;
- }
+ obj_res = AsObj(res);
+ if (obj_res == NULL) {
+ Py_DECREF(res);
+ return PythonCmd_Error(interp);
+ }
+ else {
+ Tcl_SetObjResult(interp, obj_res);
+ rv = TCL_OK;
+ }
- Py_DECREF(res);
+ Py_DECREF(res);
- LEAVE_PYTHON
+ LEAVE_PYTHON
- return rv;
+ return rv;
}
static void
PythonCmdDelete(ClientData clientData)
{
- PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
+ PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
- ENTER_PYTHON
- Py_XDECREF(data->self);
- Py_XDECREF(data->func);
- PyMem_DEL(data);
- LEAVE_PYTHON
+ ENTER_PYTHON
+ Py_XDECREF(data->self);
+ Py_XDECREF(data->func);
+ PyMem_DEL(data);
+ LEAVE_PYTHON
}
-
+
#ifdef WITH_THREAD
TCL_DECLARE_MUTEX(command_mutex)
typedef struct CommandEvent{
- Tcl_Event ev;
- Tcl_Interp* interp;
- char *name;
- int create;
- int *status;
- ClientData *data;
- Tcl_Condition *done;
+ Tcl_Event ev;
+ Tcl_Interp* interp;
+ char *name;
+ int create;
+ int *status;
+ ClientData *data;
+ Tcl_Condition *done;
} CommandEvent;
static int
Tkapp_CommandProc(CommandEvent *ev, int flags)
{
- if (ev->create)
- *ev->status = Tcl_CreateCommand(
- ev->interp, ev->name, PythonCmd,
- ev->data, PythonCmdDelete) == NULL;
- else
- *ev->status = Tcl_DeleteCommand(ev->interp, ev->name);
- Tcl_MutexLock(&command_mutex);
- Tcl_ConditionNotify(ev->done);
- Tcl_MutexUnlock(&command_mutex);
- return 1;
+ if (ev->create)
+ *ev->status = Tcl_CreateCommand(
+ ev->interp, ev->name, PythonCmd,
+ ev->data, PythonCmdDelete) == NULL;
+ else
+ *ev->status = Tcl_DeleteCommand(ev->interp, ev->name);
+ Tcl_MutexLock(&command_mutex);
+ Tcl_ConditionNotify(ev->done);
+ Tcl_MutexUnlock(&command_mutex);
+ return 1;
}
#endif
static PyObject *
Tkapp_CreateCommand(PyObject *selfptr, PyObject *args)
{
- TkappObject *self = (TkappObject*)selfptr;
- PythonCmd_ClientData *data;
- char *cmdName;
- PyObject *func;
- int err;
+ TkappObject *self = (TkappObject*)selfptr;
+ PythonCmd_ClientData *data;
+ char *cmdName;
+ PyObject *func;
+ int err;
- if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError, "command not callable");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError, "command not callable");
+ return NULL;
+ }
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread() &&
- !WaitForMainloop(self))
- return NULL;
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread() &&
+ !WaitForMainloop(self))
+ return NULL;
#endif
- data = PyMem_NEW(PythonCmd_ClientData, 1);
- if (!data)
- return PyErr_NoMemory();
- Py_INCREF(self);
- Py_INCREF(func);
- data->self = selfptr;
- data->func = func;
+ data = PyMem_NEW(PythonCmd_ClientData, 1);
+ if (!data)
+ return PyErr_NoMemory();
+ Py_INCREF(self);
+ Py_INCREF(func);
+ data->self = selfptr;
+ data->func = func;
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- Tcl_Condition cond = NULL;
- CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
- ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
- ev->interp = self->interp;
- ev->create = 1;
- ev->name = cmdName;
- ev->data = (ClientData)data;
- ev->status = &err;
- ev->done = &cond;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex);
- Tcl_ConditionFinalize(&cond);
- }
- else
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ Tcl_Condition cond = NULL;
+ CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
+ ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
+ ev->interp = self->interp;
+ ev->create = 1;
+ ev->name = cmdName;
+ ev->data = (ClientData)data;
+ ev->status = &err;
+ ev->done = &cond;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex);
+ Tcl_ConditionFinalize(&cond);
+ }
+ else
#endif
- {
- ENTER_TCL
- err = Tcl_CreateCommand(
- Tkapp_Interp(self), cmdName, PythonCmd,
- (ClientData)data, PythonCmdDelete) == NULL;
- LEAVE_TCL
- }
- if (err) {
- PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
- PyMem_DEL(data);
- return NULL;
- }
+ {
+ ENTER_TCL
+ err = Tcl_CreateCommand(
+ Tkapp_Interp(self), cmdName, PythonCmd,
+ (ClientData)data, PythonCmdDelete) == NULL;
+ LEAVE_TCL
+ }
+ if (err) {
+ PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
+ PyMem_DEL(data);
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args)
{
- TkappObject *self = (TkappObject*)selfptr;
- char *cmdName;
- int err;
+ TkappObject *self = (TkappObject*)selfptr;
+ char *cmdName;
+ int err;
- if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
+ return NULL;
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- Tcl_Condition cond = NULL;
- CommandEvent *ev;
- ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
- ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
- ev->interp = self->interp;
- ev->create = 0;
- ev->name = cmdName;
- ev->status = &err;
- ev->done = &cond;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond,
- &command_mutex);
- Tcl_ConditionFinalize(&cond);
- }
- else
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ Tcl_Condition cond = NULL;
+ CommandEvent *ev;
+ ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
+ ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
+ ev->interp = self->interp;
+ ev->create = 0;
+ ev->name = cmdName;
+ ev->status = &err;
+ ev->done = &cond;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond,
+ &command_mutex);
+ Tcl_ConditionFinalize(&cond);
+ }
+ else
#endif
- {
- ENTER_TCL
- err = Tcl_DeleteCommand(self->interp, cmdName);
- LEAVE_TCL
- }
- if (err == -1) {
- PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ {
+ ENTER_TCL
+ err = Tcl_DeleteCommand(self->interp, cmdName);
+ LEAVE_TCL
+ }
+ if (err == -1) {
+ PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
#ifdef HAVE_CREATEFILEHANDLER
/** File Handler **/
typedef struct _fhcdata {
- PyObject *func;
- PyObject *file;
- int id;
- struct _fhcdata *next;
+ PyObject *func;
+ PyObject *file;
+ int id;
+ struct _fhcdata *next;
} FileHandler_ClientData;
static FileHandler_ClientData *HeadFHCD;
@@ -2216,712 +2216,712 @@ static FileHandler_ClientData *HeadFHCD;
static FileHandler_ClientData *
NewFHCD(PyObject *func, PyObject *file, int id)
{
- FileHandler_ClientData *p;
- p = PyMem_NEW(FileHandler_ClientData, 1);
- if (p != NULL) {
- Py_XINCREF(func);
- Py_XINCREF(file);
- p->func = func;
- p->file = file;
- p->id = id;
- p->next = HeadFHCD;
- HeadFHCD = p;
- }
- return p;
+ FileHandler_ClientData *p;
+ p = PyMem_NEW(FileHandler_ClientData, 1);
+ if (p != NULL) {
+ Py_XINCREF(func);
+ Py_XINCREF(file);
+ p->func = func;
+ p->file = file;
+ p->id = id;
+ p->next = HeadFHCD;
+ HeadFHCD = p;
+ }
+ return p;
}
static void
DeleteFHCD(int id)
{
- FileHandler_ClientData *p, **pp;
+ FileHandler_ClientData *p, **pp;
- pp = &HeadFHCD;
- while ((p = *pp) != NULL) {
- if (p->id == id) {
- *pp = p->next;
- Py_XDECREF(p->func);
- Py_XDECREF(p->file);
- PyMem_DEL(p);
- }
- else
- pp = &p->next;
- }
+ pp = &HeadFHCD;
+ while ((p = *pp) != NULL) {
+ if (p->id == id) {
+ *pp = p->next;
+ Py_XDECREF(p->func);
+ Py_XDECREF(p->file);
+ PyMem_DEL(p);
+ }
+ else
+ pp = &p->next;
+ }
}
static void
FileHandler(ClientData clientData, int mask)
{
- FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
- PyObject *func, *file, *arg, *res;
+ FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
+ PyObject *func, *file, *arg, *res;
- ENTER_PYTHON
- func = data->func;
- file = data->file;
+ ENTER_PYTHON
+ func = data->func;
+ file = data->file;
- arg = Py_BuildValue("(Oi)", file, (long) mask);
- res = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
+ arg = Py_BuildValue("(Oi)", file, (long) mask);
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
- if (res == NULL) {
- errorInCmd = 1;
- PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
- }
- Py_XDECREF(res);
- LEAVE_PYTHON
+ if (res == NULL) {
+ errorInCmd = 1;
+ PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
+ }
+ Py_XDECREF(res);
+ LEAVE_PYTHON
}
static PyObject *
Tkapp_CreateFileHandler(PyObject *self, PyObject *args)
/* args is (file, mask, func) */
{
- FileHandler_ClientData *data;
- PyObject *file, *func;
- int mask, tfile;
+ FileHandler_ClientData *data;
+ PyObject *file, *func;
+ int mask, tfile;
- if (!PyArg_ParseTuple(args, "OiO:createfilehandler",
- &file, &mask, &func))
- return NULL;
+ if (!PyArg_ParseTuple(args, "OiO:createfilehandler",
+ &file, &mask, &func))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- tfile = PyObject_AsFileDescriptor(file);
- if (tfile < 0)
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError, "bad argument list");
- return NULL;
- }
+ tfile = PyObject_AsFileDescriptor(file);
+ if (tfile < 0)
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError, "bad argument list");
+ return NULL;
+ }
- data = NewFHCD(func, file, tfile);
- if (data == NULL)
- return NULL;
+ data = NewFHCD(func, file, tfile);
+ if (data == NULL)
+ return NULL;
- /* Ought to check for null Tcl_File object... */
- ENTER_TCL
- Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
- LEAVE_TCL
- Py_INCREF(Py_None);
- return Py_None;
+ /* Ought to check for null Tcl_File object... */
+ ENTER_TCL
+ Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
+ LEAVE_TCL
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_DeleteFileHandler(PyObject *self, PyObject *args)
{
- PyObject *file;
- int tfile;
+ PyObject *file;
+ int tfile;
- if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- tfile = PyObject_AsFileDescriptor(file);
- if (tfile < 0)
- return NULL;
+ tfile = PyObject_AsFileDescriptor(file);
+ if (tfile < 0)
+ return NULL;
- DeleteFHCD(tfile);
+ DeleteFHCD(tfile);
- /* Ought to check for null Tcl_File object... */
- ENTER_TCL
- Tcl_DeleteFileHandler(tfile);
- LEAVE_TCL
- Py_INCREF(Py_None);
- return Py_None;
+ /* Ought to check for null Tcl_File object... */
+ ENTER_TCL
+ Tcl_DeleteFileHandler(tfile);
+ LEAVE_TCL
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* HAVE_CREATEFILEHANDLER */
-
+
/**** Tktt Object (timer token) ****/
static PyTypeObject Tktt_Type;
typedef struct {
- PyObject_HEAD
- Tcl_TimerToken token;
- PyObject *func;
+ PyObject_HEAD
+ Tcl_TimerToken token;
+ PyObject *func;
} TkttObject;
static PyObject *
Tktt_DeleteTimerHandler(PyObject *self, PyObject *args)
{
- TkttObject *v = (TkttObject *)self;
- PyObject *func = v->func;
+ TkttObject *v = (TkttObject *)self;
+ PyObject *func = v->func;
- if (!PyArg_ParseTuple(args, ":deletetimerhandler"))
- return NULL;
- if (v->token != NULL) {
- Tcl_DeleteTimerHandler(v->token);
- v->token = NULL;
- }
- if (func != NULL) {
- v->func = NULL;
- Py_DECREF(func);
- Py_DECREF(v); /* See Tktt_New() */
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":deletetimerhandler"))
+ return NULL;
+ if (v->token != NULL) {
+ Tcl_DeleteTimerHandler(v->token);
+ v->token = NULL;
+ }
+ if (func != NULL) {
+ v->func = NULL;
+ Py_DECREF(func);
+ Py_DECREF(v); /* See Tktt_New() */
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef Tktt_methods[] =
{
- {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS},
- {NULL, NULL}
+ {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS},
+ {NULL, NULL}
};
static TkttObject *
Tktt_New(PyObject *func)
{
- TkttObject *v;
+ TkttObject *v;
- v = PyObject_New(TkttObject, &Tktt_Type);
- if (v == NULL)
- return NULL;
+ v = PyObject_New(TkttObject, &Tktt_Type);
+ if (v == NULL)
+ return NULL;
- Py_INCREF(func);
- v->token = NULL;
- v->func = func;
+ Py_INCREF(func);
+ v->token = NULL;
+ v->func = func;
- /* Extra reference, deleted when called or when handler is deleted */
- Py_INCREF(v);
- return v;
+ /* Extra reference, deleted when called or when handler is deleted */
+ Py_INCREF(v);
+ return v;
}
static void
Tktt_Dealloc(PyObject *self)
{
- TkttObject *v = (TkttObject *)self;
- PyObject *func = v->func;
+ TkttObject *v = (TkttObject *)self;
+ PyObject *func = v->func;
- Py_XDECREF(func);
+ Py_XDECREF(func);
- PyObject_Del(self);
+ PyObject_Del(self);
}
static PyObject *
Tktt_Repr(PyObject *self)
{
- TkttObject *v = (TkttObject *)self;
- char buf[100];
+ TkttObject *v = (TkttObject *)self;
+ char buf[100];
- PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
- v->func == NULL ? ", handler deleted" : "");
- return PyUnicode_FromString(buf);
+ PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
+ v->func == NULL ? ", handler deleted" : "");
+ return PyUnicode_FromString(buf);
}
static PyTypeObject Tktt_Type =
{
- PyVarObject_HEAD_INIT(NULL, 0)
- "tktimertoken", /*tp_name */
- sizeof(TkttObject), /*tp_basicsize */
- 0, /*tp_itemsize */
- Tktt_Dealloc, /*tp_dealloc */
- 0, /*tp_print */
- 0, /*tp_getattr */
- 0, /*tp_setattr */
- 0, /*tp_reserved */
- Tktt_Repr, /*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, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- Tktt_methods, /*tp_methods*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "tktimertoken", /*tp_name */
+ sizeof(TkttObject), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ Tktt_Dealloc, /*tp_dealloc */
+ 0, /*tp_print */
+ 0, /*tp_getattr */
+ 0, /*tp_setattr */
+ 0, /*tp_reserved */
+ Tktt_Repr, /*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, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ Tktt_methods, /*tp_methods*/
};
-
+
/** Timer Handler **/
static void
TimerHandler(ClientData clientData)
{
- TkttObject *v = (TkttObject *)clientData;
- PyObject *func = v->func;
- PyObject *res;
+ TkttObject *v = (TkttObject *)clientData;
+ PyObject *func = v->func;
+ PyObject *res;
- if (func == NULL)
- return;
+ if (func == NULL)
+ return;
- v->func = NULL;
+ v->func = NULL;
- ENTER_PYTHON
+ ENTER_PYTHON
- res = PyEval_CallObject(func, NULL);
- Py_DECREF(func);
- Py_DECREF(v); /* See Tktt_New() */
+ res = PyEval_CallObject(func, NULL);
+ Py_DECREF(func);
+ Py_DECREF(v); /* See Tktt_New() */
- if (res == NULL) {
- errorInCmd = 1;
- PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
- }
- else
- Py_DECREF(res);
+ if (res == NULL) {
+ errorInCmd = 1;
+ PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
+ }
+ else
+ Py_DECREF(res);
- LEAVE_PYTHON
+ LEAVE_PYTHON
}
static PyObject *
Tkapp_CreateTimerHandler(PyObject *self, PyObject *args)
{
- int milliseconds;
- PyObject *func;
- TkttObject *v;
+ int milliseconds;
+ PyObject *func;
+ TkttObject *v;
- if (!PyArg_ParseTuple(args, "iO:createtimerhandler",
- &milliseconds, &func))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError, "bad argument list");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "iO:createtimerhandler",
+ &milliseconds, &func))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError, "bad argument list");
+ return NULL;
+ }
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- v = Tktt_New(func);
- if (v) {
- v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
- (ClientData)v);
- }
+ v = Tktt_New(func);
+ if (v) {
+ v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
+ (ClientData)v);
+ }
- return (PyObject *) v;
+ return (PyObject *) v;
}
-
+
/** Event Loop **/
static PyObject *
Tkapp_MainLoop(PyObject *selfptr, PyObject *args)
{
- int threshold = 0;
- TkappObject *self = (TkappObject*)selfptr;
+ int threshold = 0;
+ TkappObject *self = (TkappObject*)selfptr;
#ifdef WITH_THREAD
- PyThreadState *tstate = PyThreadState_Get();
+ PyThreadState *tstate = PyThreadState_Get();
#endif
- if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
+ return NULL;
- CHECK_TCL_APPARTMENT;
- self->dispatching = 1;
+ CHECK_TCL_APPARTMENT;
+ self->dispatching = 1;
- quitMainLoop = 0;
- while (Tk_GetNumMainWindows() > threshold &&
- !quitMainLoop &&
- !errorInCmd)
- {
- int result;
+ quitMainLoop = 0;
+ while (Tk_GetNumMainWindows() > threshold &&
+ !quitMainLoop &&
+ !errorInCmd)
+ {
+ int result;
#ifdef WITH_THREAD
- if (self->threaded) {
- /* Allow other Python threads to run. */
- ENTER_TCL
- result = Tcl_DoOneEvent(0);
- LEAVE_TCL
- }
- else {
- Py_BEGIN_ALLOW_THREADS
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
- tcl_tstate = tstate;
- result = Tcl_DoOneEvent(TCL_DONT_WAIT);
- tcl_tstate = NULL;
- if(tcl_lock)PyThread_release_lock(tcl_lock);
- if (result == 0)
- Sleep(Tkinter_busywaitinterval);
- Py_END_ALLOW_THREADS
- }
+ if (self->threaded) {
+ /* Allow other Python threads to run. */
+ ENTER_TCL
+ result = Tcl_DoOneEvent(0);
+ LEAVE_TCL
+ }
+ else {
+ Py_BEGIN_ALLOW_THREADS
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
+ tcl_tstate = tstate;
+ result = Tcl_DoOneEvent(TCL_DONT_WAIT);
+ tcl_tstate = NULL;
+ if(tcl_lock)PyThread_release_lock(tcl_lock);
+ if (result == 0)
+ Sleep(Tkinter_busywaitinterval);
+ Py_END_ALLOW_THREADS
+ }
#else
- result = Tcl_DoOneEvent(0);
+ result = Tcl_DoOneEvent(0);
#endif
- if (PyErr_CheckSignals() != 0) {
- self->dispatching = 0;
- return NULL;
- }
- if (result < 0)
- break;
- }
- self->dispatching = 0;
- quitMainLoop = 0;
-
- if (errorInCmd) {
- errorInCmd = 0;
- PyErr_Restore(excInCmd, valInCmd, trbInCmd);
- excInCmd = valInCmd = trbInCmd = NULL;
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (PyErr_CheckSignals() != 0) {
+ self->dispatching = 0;
+ return NULL;
+ }
+ if (result < 0)
+ break;
+ }
+ self->dispatching = 0;
+ quitMainLoop = 0;
+
+ if (errorInCmd) {
+ errorInCmd = 0;
+ PyErr_Restore(excInCmd, valInCmd, trbInCmd);
+ excInCmd = valInCmd = trbInCmd = NULL;
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_DoOneEvent(PyObject *self, PyObject *args)
{
- int flags = 0;
- int rv;
+ int flags = 0;
+ int rv;
- if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
+ return NULL;
- ENTER_TCL
- rv = Tcl_DoOneEvent(flags);
- LEAVE_TCL
- return Py_BuildValue("i", rv);
+ ENTER_TCL
+ rv = Tcl_DoOneEvent(flags);
+ LEAVE_TCL
+ return Py_BuildValue("i", rv);
}
static PyObject *
Tkapp_Quit(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":quit"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":quit"))
+ return NULL;
- quitMainLoop = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ quitMainLoop = 1;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_InterpAddr(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":interpaddr"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":interpaddr"))
+ return NULL;
- return PyLong_FromLong((long)Tkapp_Interp(self));
+ return PyLong_FromLong((long)Tkapp_Interp(self));
}
-static PyObject *
+static PyObject *
Tkapp_TkInit(PyObject *self, PyObject *args)
{
- Tcl_Interp *interp = Tkapp_Interp(self);
- const char * _tk_exists = NULL;
- int err;
+ Tcl_Interp *interp = Tkapp_Interp(self);
+ const char * _tk_exists = NULL;
+ int err;
#ifdef TKINTER_PROTECT_LOADTK
- /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the
- * first call failed.
- * To avoid the deadlock, we just refuse the second call through
- * a static variable.
- */
- if (tk_load_failed) {
- PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG);
- return NULL;
- }
+ /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the
+ * first call failed.
+ * To avoid the deadlock, we just refuse the second call through
+ * a static variable.
+ */
+ if (tk_load_failed) {
+ PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG);
+ return NULL;
+ }
#endif
- /* We want to guard against calling Tk_Init() multiple times */
- CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version");
- ENTER_OVERLAP
- if (err == TCL_ERROR) {
- /* This sets an exception, but we cannot return right
- away because we need to exit the overlap first. */
- Tkinter_Error(self);
- } else {
- _tk_exists = Tkapp_Result(self);
- }
- LEAVE_OVERLAP_TCL
- if (err == TCL_ERROR) {
- return NULL;
- }
- if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) {
- if (Tk_Init(interp) == TCL_ERROR) {
- PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
+ /* We want to guard against calling Tk_Init() multiple times */
+ CHECK_TCL_APPARTMENT;
+ ENTER_TCL
+ err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version");
+ ENTER_OVERLAP
+ if (err == TCL_ERROR) {
+ /* This sets an exception, but we cannot return right
+ away because we need to exit the overlap first. */
+ Tkinter_Error(self);
+ } else {
+ _tk_exists = Tkapp_Result(self);
+ }
+ LEAVE_OVERLAP_TCL
+ if (err == TCL_ERROR) {
+ return NULL;
+ }
+ if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) {
+ if (Tk_Init(interp) == TCL_ERROR) {
+ PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
#ifdef TKINTER_PROTECT_LOADTK
- tk_load_failed = 1;
+ tk_load_failed = 1;
#endif
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_WantObjects(PyObject *self, PyObject *args)
{
- int wantobjects = -1;
- if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects))
- return NULL;
- if (wantobjects == -1)
- return PyBool_FromLong(((TkappObject*)self)->wantobjects);
- ((TkappObject*)self)->wantobjects = wantobjects;
+ int wantobjects = -1;
+ if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects))
+ return NULL;
+ if (wantobjects == -1)
+ return PyBool_FromLong(((TkappObject*)self)->wantobjects);
+ ((TkappObject*)self)->wantobjects = wantobjects;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_WillDispatch(PyObject *self, PyObject *args)
{
- ((TkappObject*)self)->dispatching = 1;
+ ((TkappObject*)self)->dispatching = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
/**** Tkapp Method List ****/
static PyMethodDef Tkapp_methods[] =
{
- {"willdispatch", Tkapp_WillDispatch, METH_NOARGS},
- {"wantobjects", Tkapp_WantObjects, METH_VARARGS},
- {"call", Tkapp_Call, METH_VARARGS},
- {"globalcall", Tkapp_GlobalCall, METH_VARARGS},
- {"eval", Tkapp_Eval, METH_VARARGS},
- {"globaleval", Tkapp_GlobalEval, METH_VARARGS},
- {"evalfile", Tkapp_EvalFile, METH_VARARGS},
- {"record", Tkapp_Record, METH_VARARGS},
- {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS},
- {"setvar", Tkapp_SetVar, METH_VARARGS},
- {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS},
- {"getvar", Tkapp_GetVar, METH_VARARGS},
- {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS},
- {"unsetvar", Tkapp_UnsetVar, METH_VARARGS},
- {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS},
- {"getint", Tkapp_GetInt, METH_VARARGS},
- {"getdouble", Tkapp_GetDouble, METH_VARARGS},
- {"getboolean", Tkapp_GetBoolean, METH_VARARGS},
- {"exprstring", Tkapp_ExprString, METH_VARARGS},
- {"exprlong", Tkapp_ExprLong, METH_VARARGS},
- {"exprdouble", Tkapp_ExprDouble, METH_VARARGS},
- {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS},
- {"splitlist", Tkapp_SplitList, METH_VARARGS},
- {"split", Tkapp_Split, METH_VARARGS},
- {"merge", Tkapp_Merge, METH_VARARGS},
- {"createcommand", Tkapp_CreateCommand, METH_VARARGS},
- {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS},
+ {"willdispatch", Tkapp_WillDispatch, METH_NOARGS},
+ {"wantobjects", Tkapp_WantObjects, METH_VARARGS},
+ {"call", Tkapp_Call, METH_VARARGS},
+ {"globalcall", Tkapp_GlobalCall, METH_VARARGS},
+ {"eval", Tkapp_Eval, METH_VARARGS},
+ {"globaleval", Tkapp_GlobalEval, METH_VARARGS},
+ {"evalfile", Tkapp_EvalFile, METH_VARARGS},
+ {"record", Tkapp_Record, METH_VARARGS},
+ {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS},
+ {"setvar", Tkapp_SetVar, METH_VARARGS},
+ {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS},
+ {"getvar", Tkapp_GetVar, METH_VARARGS},
+ {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS},
+ {"unsetvar", Tkapp_UnsetVar, METH_VARARGS},
+ {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS},
+ {"getint", Tkapp_GetInt, METH_VARARGS},
+ {"getdouble", Tkapp_GetDouble, METH_VARARGS},
+ {"getboolean", Tkapp_GetBoolean, METH_VARARGS},
+ {"exprstring", Tkapp_ExprString, METH_VARARGS},
+ {"exprlong", Tkapp_ExprLong, METH_VARARGS},
+ {"exprdouble", Tkapp_ExprDouble, METH_VARARGS},
+ {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS},
+ {"splitlist", Tkapp_SplitList, METH_VARARGS},
+ {"split", Tkapp_Split, METH_VARARGS},
+ {"merge", Tkapp_Merge, METH_VARARGS},
+ {"createcommand", Tkapp_CreateCommand, METH_VARARGS},
+ {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS},
#ifdef HAVE_CREATEFILEHANDLER
- {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
- {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
+ {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
+ {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
#endif
- {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
- {"mainloop", Tkapp_MainLoop, METH_VARARGS},
- {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
- {"quit", Tkapp_Quit, METH_VARARGS},
- {"interpaddr", Tkapp_InterpAddr, METH_VARARGS},
- {"loadtk", Tkapp_TkInit, METH_NOARGS},
- {NULL, NULL}
+ {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
+ {"mainloop", Tkapp_MainLoop, METH_VARARGS},
+ {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
+ {"quit", Tkapp_Quit, METH_VARARGS},
+ {"interpaddr", Tkapp_InterpAddr, METH_VARARGS},
+ {"loadtk", Tkapp_TkInit, METH_NOARGS},
+ {NULL, NULL}
};
-
+
/**** Tkapp Type Methods ****/
static void
Tkapp_Dealloc(PyObject *self)
{
- /*CHECK_TCL_APPARTMENT;*/
- ENTER_TCL
- Tcl_DeleteInterp(Tkapp_Interp(self));
- LEAVE_TCL
- PyObject_Del(self);
- DisableEventHook();
+ /*CHECK_TCL_APPARTMENT;*/
+ ENTER_TCL
+ Tcl_DeleteInterp(Tkapp_Interp(self));
+ LEAVE_TCL
+ PyObject_Del(self);
+ DisableEventHook();
}
static PyTypeObject Tkapp_Type =
{
- PyVarObject_HEAD_INIT(NULL, 0)
- "tkapp", /*tp_name */
- sizeof(TkappObject), /*tp_basicsize */
- 0, /*tp_itemsize */
- Tkapp_Dealloc, /*tp_dealloc */
- 0, /*tp_print */
- 0, /*tp_getattr */
- 0, /*tp_setattr */
- 0, /*tp_reserved */
- 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, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- Tkapp_methods, /*tp_methods*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "tkapp", /*tp_name */
+ sizeof(TkappObject), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ Tkapp_Dealloc, /*tp_dealloc */
+ 0, /*tp_print */
+ 0, /*tp_getattr */
+ 0, /*tp_setattr */
+ 0, /*tp_reserved */
+ 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, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ Tkapp_methods, /*tp_methods*/
};
-
+
/**** Tkinter Module ****/
typedef struct {
- PyObject* tuple;
- int size; /* current size */
- int maxsize; /* allocated size */
+ PyObject* tuple;
+ int size; /* current size */
+ int maxsize; /* allocated size */
} FlattenContext;
static int
_bump(FlattenContext* context, int size)
{
- /* expand tuple to hold (at least) size new items.
- return true if successful, false if an exception was raised */
+ /* expand tuple to hold (at least) size new items.
+ return true if successful, false if an exception was raised */
- int maxsize = context->maxsize * 2;
+ int maxsize = context->maxsize * 2;
- if (maxsize < context->size + size)
- maxsize = context->size + size;
+ if (maxsize < context->size + size)
+ maxsize = context->size + size;
- context->maxsize = maxsize;
+ context->maxsize = maxsize;
- return _PyTuple_Resize(&context->tuple, maxsize) >= 0;
+ return _PyTuple_Resize(&context->tuple, maxsize) >= 0;
}
static int
_flatten1(FlattenContext* context, PyObject* item, int depth)
{
- /* add tuple or list to argument tuple (recursively) */
-
- int i, size;
-
- if (depth > 1000) {
- PyErr_SetString(PyExc_ValueError,
- "nesting too deep in _flatten");
- return 0;
- } else if (PyList_Check(item)) {
- size = PyList_GET_SIZE(item);
- /* preallocate (assume no nesting) */
- if (context->size + size > context->maxsize &&
- !_bump(context, size))
- return 0;
- /* copy items to output tuple */
- for (i = 0; i < size; i++) {
- PyObject *o = PyList_GET_ITEM(item, i);
- if (PyList_Check(o) || PyTuple_Check(o)) {
- if (!_flatten1(context, o, depth + 1))
- return 0;
- } else if (o != Py_None) {
- if (context->size + 1 > context->maxsize &&
- !_bump(context, 1))
- return 0;
- Py_INCREF(o);
- PyTuple_SET_ITEM(context->tuple,
- context->size++, o);
- }
- }
- } else if (PyTuple_Check(item)) {
- /* same, for tuples */
- size = PyTuple_GET_SIZE(item);
- if (context->size + size > context->maxsize &&
- !_bump(context, size))
- return 0;
- for (i = 0; i < size; i++) {
- PyObject *o = PyTuple_GET_ITEM(item, i);
- if (PyList_Check(o) || PyTuple_Check(o)) {
- if (!_flatten1(context, o, depth + 1))
- return 0;
- } else if (o != Py_None) {
- if (context->size + 1 > context->maxsize &&
- !_bump(context, 1))
- return 0;
- Py_INCREF(o);
- PyTuple_SET_ITEM(context->tuple,
- context->size++, o);
- }
- }
- } else {
- PyErr_SetString(PyExc_TypeError, "argument must be sequence");
- return 0;
- }
- return 1;
+ /* add tuple or list to argument tuple (recursively) */
+
+ int i, size;
+
+ if (depth > 1000) {
+ PyErr_SetString(PyExc_ValueError,
+ "nesting too deep in _flatten");
+ return 0;
+ } else if (PyList_Check(item)) {
+ size = PyList_GET_SIZE(item);
+ /* preallocate (assume no nesting) */
+ if (context->size + size > context->maxsize &&
+ !_bump(context, size))
+ return 0;
+ /* copy items to output tuple */
+ for (i = 0; i < size; i++) {
+ PyObject *o = PyList_GET_ITEM(item, i);
+ if (PyList_Check(o) || PyTuple_Check(o)) {
+ if (!_flatten1(context, o, depth + 1))
+ return 0;
+ } else if (o != Py_None) {
+ if (context->size + 1 > context->maxsize &&
+ !_bump(context, 1))
+ return 0;
+ Py_INCREF(o);
+ PyTuple_SET_ITEM(context->tuple,
+ context->size++, o);
+ }
+ }
+ } else if (PyTuple_Check(item)) {
+ /* same, for tuples */
+ size = PyTuple_GET_SIZE(item);
+ if (context->size + size > context->maxsize &&
+ !_bump(context, size))
+ return 0;
+ for (i = 0; i < size; i++) {
+ PyObject *o = PyTuple_GET_ITEM(item, i);
+ if (PyList_Check(o) || PyTuple_Check(o)) {
+ if (!_flatten1(context, o, depth + 1))
+ return 0;
+ } else if (o != Py_None) {
+ if (context->size + 1 > context->maxsize &&
+ !_bump(context, 1))
+ return 0;
+ Py_INCREF(o);
+ PyTuple_SET_ITEM(context->tuple,
+ context->size++, o);
+ }
+ }
+ } else {
+ PyErr_SetString(PyExc_TypeError, "argument must be sequence");
+ return 0;
+ }
+ return 1;
}
static PyObject *
Tkinter_Flatten(PyObject* self, PyObject* args)
{
- FlattenContext context;
- PyObject* item;
+ FlattenContext context;
+ PyObject* item;
- if (!PyArg_ParseTuple(args, "O:_flatten", &item))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:_flatten", &item))
+ return NULL;
- context.maxsize = PySequence_Size(item);
- if (context.maxsize < 0)
- return NULL;
- if (context.maxsize == 0)
- return PyTuple_New(0);
+ context.maxsize = PySequence_Size(item);
+ if (context.maxsize < 0)
+ return NULL;
+ if (context.maxsize == 0)
+ return PyTuple_New(0);
- context.tuple = PyTuple_New(context.maxsize);
- if (!context.tuple)
- return NULL;
+ context.tuple = PyTuple_New(context.maxsize);
+ if (!context.tuple)
+ return NULL;
- context.size = 0;
+ context.size = 0;
- if (!_flatten1(&context, item,0))
- return NULL;
+ if (!_flatten1(&context, item,0))
+ return NULL;
- if (_PyTuple_Resize(&context.tuple, context.size))
- return NULL;
+ if (_PyTuple_Resize(&context.tuple, context.size))
+ return NULL;
- return context.tuple;
+ return context.tuple;
}
static PyObject *
Tkinter_Create(PyObject *self, PyObject *args)
{
- char *screenName = NULL;
- char *baseName = NULL; /* XXX this is not used anymore;
- try getting rid of it. */
- char *className = NULL;
- int interactive = 0;
- int wantobjects = 0;
- int wantTk = 1; /* If false, then Tk_Init() doesn't get called */
- int sync = 0; /* pass -sync to wish */
- char *use = NULL; /* pass -use to wish */
+ char *screenName = NULL;
+ char *baseName = NULL; /* XXX this is not used anymore;
+ try getting rid of it. */
+ char *className = NULL;
+ int interactive = 0;
+ int wantobjects = 0;
+ int wantTk = 1; /* If false, then Tk_Init() doesn't get called */
+ int sync = 0; /* pass -sync to wish */
+ char *use = NULL; /* pass -use to wish */
- className = "Tk";
+ className = "Tk";
- if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
- &screenName, &baseName, &className,
- &interactive, &wantobjects, &wantTk,
- &sync, &use))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
+ &screenName, &baseName, &className,
+ &interactive, &wantobjects, &wantTk,
+ &sync, &use))
+ return NULL;
- return (PyObject *) Tkapp_New(screenName, className,
- interactive, wantobjects, wantTk,
- sync, use);
+ return (PyObject *) Tkapp_New(screenName, className,
+ interactive, wantobjects, wantTk,
+ sync, use);
}
static PyObject *
Tkinter_setbusywaitinterval(PyObject *self, PyObject *args)
{
- int new_val;
- if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val))
- return NULL;
- if (new_val < 0) {
- PyErr_SetString(PyExc_ValueError,
- "busywaitinterval must be >= 0");
- return NULL;
- }
- Tkinter_busywaitinterval = new_val;
- Py_INCREF(Py_None);
- return Py_None;
+ int new_val;
+ if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val))
+ return NULL;
+ if (new_val < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "busywaitinterval must be >= 0");
+ return NULL;
+ }
+ Tkinter_busywaitinterval = new_val;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static char setbusywaitinterval_doc[] =
@@ -2935,7 +2935,7 @@ frames in an animation.";
static PyObject *
Tkinter_getbusywaitinterval(PyObject *self, PyObject *args)
{
- return PyLong_FromLong(Tkinter_busywaitinterval);
+ return PyLong_FromLong(Tkinter_busywaitinterval);
}
static char getbusywaitinterval_doc[] =
@@ -2946,13 +2946,13 @@ calls to Tcl_DoOneEvent in a threaded Python interpreter.";
static PyMethodDef moduleMethods[] =
{
- {"_flatten", Tkinter_Flatten, METH_VARARGS},
- {"create", Tkinter_Create, METH_VARARGS},
- {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
- setbusywaitinterval_doc},
- {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
- METH_NOARGS, getbusywaitinterval_doc},
- {NULL, NULL}
+ {"_flatten", Tkinter_Flatten, METH_VARARGS},
+ {"create", Tkinter_Create, METH_VARARGS},
+ {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
+ setbusywaitinterval_doc},
+ {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
+ METH_NOARGS, getbusywaitinterval_doc},
+ {NULL, NULL}
};
#ifdef WAIT_FOR_STDIN
@@ -2963,7 +2963,7 @@ static int stdin_ready = 0;
static void
MyFileProc(void *clientData, int mask)
{
- stdin_ready = 1;
+ stdin_ready = 1;
}
#endif
@@ -2975,57 +2975,57 @@ static int
EventHook(void)
{
#ifndef MS_WINDOWS
- int tfile;
+ int tfile;
#endif
#ifdef WITH_THREAD
- PyEval_RestoreThread(event_tstate);
+ PyEval_RestoreThread(event_tstate);
#endif
- stdin_ready = 0;
- errorInCmd = 0;
+ stdin_ready = 0;
+ errorInCmd = 0;
#ifndef MS_WINDOWS
- tfile = fileno(stdin);
- Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
+ tfile = fileno(stdin);
+ Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
#endif
- while (!errorInCmd && !stdin_ready) {
- int result;
+ while (!errorInCmd && !stdin_ready) {
+ int result;
#ifdef MS_WINDOWS
- if (_kbhit()) {
- stdin_ready = 1;
- break;
- }
+ if (_kbhit()) {
+ stdin_ready = 1;
+ break;
+ }
#endif
#if defined(WITH_THREAD) || defined(MS_WINDOWS)
- Py_BEGIN_ALLOW_THREADS
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
- tcl_tstate = event_tstate;
+ Py_BEGIN_ALLOW_THREADS
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
+ tcl_tstate = event_tstate;
- result = Tcl_DoOneEvent(TCL_DONT_WAIT);
+ result = Tcl_DoOneEvent(TCL_DONT_WAIT);
- tcl_tstate = NULL;
- if(tcl_lock)PyThread_release_lock(tcl_lock);
- if (result == 0)
- Sleep(Tkinter_busywaitinterval);
- Py_END_ALLOW_THREADS
+ tcl_tstate = NULL;
+ if(tcl_lock)PyThread_release_lock(tcl_lock);
+ if (result == 0)
+ Sleep(Tkinter_busywaitinterval);
+ Py_END_ALLOW_THREADS
#else
- result = Tcl_DoOneEvent(0);
+ result = Tcl_DoOneEvent(0);
#endif
- if (result < 0)
- break;
- }
+ if (result < 0)
+ break;
+ }
#ifndef MS_WINDOWS
- Tcl_DeleteFileHandler(tfile);
+ Tcl_DeleteFileHandler(tfile);
#endif
- if (errorInCmd) {
- errorInCmd = 0;
- PyErr_Restore(excInCmd, valInCmd, trbInCmd);
- excInCmd = valInCmd = trbInCmd = NULL;
- PyErr_Print();
- }
+ if (errorInCmd) {
+ errorInCmd = 0;
+ PyErr_Restore(excInCmd, valInCmd, trbInCmd);
+ excInCmd = valInCmd = trbInCmd = NULL;
+ PyErr_Print();
+ }
#ifdef WITH_THREAD
- PyEval_SaveThread();
+ PyEval_SaveThread();
#endif
- return 0;
+ return 0;
}
#endif
@@ -3034,12 +3034,12 @@ static void
EnableEventHook(void)
{
#ifdef WAIT_FOR_STDIN
- if (PyOS_InputHook == NULL) {
+ if (PyOS_InputHook == NULL) {
#ifdef WITH_THREAD
- event_tstate = PyThreadState_Get();
+ event_tstate = PyThreadState_Get();
#endif
- PyOS_InputHook = EventHook;
- }
+ PyOS_InputHook = EventHook;
+ }
#endif
}
@@ -3047,9 +3047,9 @@ static void
DisableEventHook(void)
{
#ifdef WAIT_FOR_STDIN
- if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
- PyOS_InputHook = NULL;
- }
+ if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
+ PyOS_InputHook = NULL;
+ }
#endif
}
@@ -3058,114 +3058,114 @@ DisableEventHook(void)
static void
ins_long(PyObject *d, char *name, long val)
{
- PyObject *v = PyLong_FromLong(val);
- if (v) {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyLong_FromLong(val);
+ if (v) {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
static void
ins_string(PyObject *d, char *name, char *val)
{
- PyObject *v = PyUnicode_FromString(val);
- if (v) {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyUnicode_FromString(val);
+ if (v) {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
static struct PyModuleDef _tkintermodule = {
- PyModuleDef_HEAD_INIT,
- "_tkinter",
- NULL,
- -1,
- moduleMethods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_tkinter",
+ NULL,
+ -1,
+ moduleMethods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__tkinter(void)
{
- PyObject *m, *d, *uexe, *cexe;
+ PyObject *m, *d, *uexe, *cexe;
- if (PyType_Ready(&Tkapp_Type) < 0)
- return NULL;
+ if (PyType_Ready(&Tkapp_Type) < 0)
+ return NULL;
#ifdef WITH_THREAD
- tcl_lock = PyThread_allocate_lock();
+ tcl_lock = PyThread_allocate_lock();
#endif
- m = PyModule_Create(&_tkintermodule);
- if (m == NULL)
- return NULL;
+ m = PyModule_Create(&_tkintermodule);
+ if (m == NULL)
+ return NULL;
- d = PyModule_GetDict(m);
- Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL);
- PyDict_SetItemString(d, "TclError", Tkinter_TclError);
+ d = PyModule_GetDict(m);
+ Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL);
+ PyDict_SetItemString(d, "TclError", Tkinter_TclError);
- ins_long(d, "READABLE", TCL_READABLE);
- ins_long(d, "WRITABLE", TCL_WRITABLE);
- ins_long(d, "EXCEPTION", TCL_EXCEPTION);
- ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
- ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
- ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
- ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
- ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
- ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
- ins_string(d, "TK_VERSION", TK_VERSION);
- ins_string(d, "TCL_VERSION", TCL_VERSION);
+ ins_long(d, "READABLE", TCL_READABLE);
+ ins_long(d, "WRITABLE", TCL_WRITABLE);
+ ins_long(d, "EXCEPTION", TCL_EXCEPTION);
+ ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
+ ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
+ ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
+ ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
+ ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
+ ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
+ ins_string(d, "TK_VERSION", TK_VERSION);
+ ins_string(d, "TCL_VERSION", TCL_VERSION);
- PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
+ PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
- if (PyType_Ready(&Tktt_Type) < 0)
- return NULL;
- PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
+ if (PyType_Ready(&Tktt_Type) < 0)
+ return NULL;
+ PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
- Py_TYPE(&PyTclObject_Type) = &PyType_Type;
- PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type);
+ Py_TYPE(&PyTclObject_Type) = &PyType_Type;
+ PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type);
#ifdef TK_AQUA
- /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems
- * start waking up. Note that Tcl_FindExecutable will do this, this
- * code must be above it! The original warning from
- * tkMacOSXAppInit.c is copied below.
- *
- * NB - You have to swap in the Tk Notifier BEFORE you start up the
- * Tcl interpreter for now. It probably should work to do this
- * in the other order, but for now it doesn't seem to.
- *
- */
- Tk_MacOSXSetupTkNotifier();
+ /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems
+ * start waking up. Note that Tcl_FindExecutable will do this, this
+ * code must be above it! The original warning from
+ * tkMacOSXAppInit.c is copied below.
+ *
+ * NB - You have to swap in the Tk Notifier BEFORE you start up the
+ * Tcl interpreter for now. It probably should work to do this
+ * in the other order, but for now it doesn't seem to.
+ *
+ */
+ Tk_MacOSXSetupTkNotifier();
#endif
- /* This helps the dynamic loader; in Unicode aware Tcl versions
- it also helps Tcl find its encodings. */
- uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1);
- if (uexe) {
- cexe = PyUnicode_AsEncodedString(uexe,
- Py_FileSystemDefaultEncoding,
- NULL);
- if (cexe)
- Tcl_FindExecutable(PyBytes_AsString(cexe));
- Py_XDECREF(cexe);
- Py_DECREF(uexe);
- }
-
- if (PyErr_Occurred()) {
- Py_DECREF(m);
- return NULL;
- }
+ /* This helps the dynamic loader; in Unicode aware Tcl versions
+ it also helps Tcl find its encodings. */
+ uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1);
+ if (uexe) {
+ cexe = PyUnicode_AsEncodedString(uexe,
+ Py_FileSystemDefaultEncoding,
+ NULL);
+ if (cexe)
+ Tcl_FindExecutable(PyBytes_AsString(cexe));
+ Py_XDECREF(cexe);
+ Py_DECREF(uexe);
+ }
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(m);
+ return NULL;
+ }
#if 0
- /* This was not a good idea; through <Destroy> bindings,
- Tcl_Finalize() may invoke Python code but at that point the
- interpreter and thread state have already been destroyed! */
- Py_AtExit(Tcl_Finalize);
+ /* This was not a good idea; through <Destroy> bindings,
+ Tcl_Finalize() may invoke Python code but at that point the
+ interpreter and thread state have already been destroyed! */
+ Py_AtExit(Tcl_Finalize);
#endif
- return m;
+ return m;
}
diff --git a/Modules/addrinfo.h b/Modules/addrinfo.h
index fe7e96f..1cb6f0e 100644
--- a/Modules/addrinfo.h
+++ b/Modules/addrinfo.h
@@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
* All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
@@ -13,7 +13,7 @@
* 3. Neither the name of the project 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 PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@@ -55,20 +55,20 @@
#define getaddrinfo fake_getaddrinfo
#endif /* EAI_ADDRFAMILY */
-#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
-#define EAI_AGAIN 2 /* temporary failure in name resolution */
-#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
-#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
-#define EAI_FAMILY 5 /* ai_family not supported */
-#define EAI_MEMORY 6 /* memory allocation failure */
-#define EAI_NODATA 7 /* no address associated with hostname */
-#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
-#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
-#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
-#define EAI_SYSTEM 11 /* system error returned in errno */
-#define EAI_BADHINTS 12
-#define EAI_PROTOCOL 13
-#define EAI_MAX 14
+#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
+#define EAI_AGAIN 2 /* temporary failure in name resolution */
+#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
+#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
+#define EAI_FAMILY 5 /* ai_family not supported */
+#define EAI_MEMORY 6 /* memory allocation failure */
+#define EAI_NODATA 7 /* no address associated with hostname */
+#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
+#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
+#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
+#define EAI_SYSTEM 11 /* system error returned in errno */
+#define EAI_BADHINTS 12
+#define EAI_PROTOCOL 13
+#define EAI_MAX 14
/*
* Flag values for getaddrinfo()
@@ -85,18 +85,18 @@
#undef AI_DEFAULT
#endif /* AI_PASSIVE */
-#define AI_PASSIVE 0x00000001 /* get address to use bind() */
-#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
-#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
+#define AI_PASSIVE 0x00000001 /* get address to use bind() */
+#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
+#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
/* valid flags for addrinfo */
-#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
+#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
-#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
-#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
-#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
-#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
+#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
+#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
+#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
+#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
/* special recommended flags for getipnodebyname */
-#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
+#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
#endif /* !HAVE_GETADDRINFO */
@@ -106,33 +106,33 @@
* Constants for getnameinfo()
*/
#ifndef NI_MAXHOST
-#define NI_MAXHOST 1025
-#define NI_MAXSERV 32
+#define NI_MAXHOST 1025
+#define NI_MAXSERV 32
#endif /* !NI_MAXHOST */
/*
* Flag values for getnameinfo()
*/
#ifndef NI_NOFQDN
-#define NI_NOFQDN 0x00000001
-#define NI_NUMERICHOST 0x00000002
-#define NI_NAMEREQD 0x00000004
-#define NI_NUMERICSERV 0x00000008
-#define NI_DGRAM 0x00000010
+#define NI_NOFQDN 0x00000001
+#define NI_NUMERICHOST 0x00000002
+#define NI_NAMEREQD 0x00000004
+#define NI_NUMERICSERV 0x00000008
+#define NI_DGRAM 0x00000010
#endif /* !NI_NOFQDN */
#endif /* !HAVE_GETNAMEINFO */
#ifndef HAVE_ADDRINFO
struct addrinfo {
- int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
- int ai_family; /* PF_xxx */
- int ai_socktype; /* SOCK_xxx */
- int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
- size_t ai_addrlen; /* length of ai_addr */
- char *ai_canonname; /* canonical name for hostname */
- struct sockaddr *ai_addr; /* binary address */
- struct addrinfo *ai_next; /* next structure in linked list */
+ int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
+ int ai_family; /* PF_xxx */
+ int ai_socktype; /* SOCK_xxx */
+ int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
+ size_t ai_addrlen; /* length of ai_addr */
+ char *ai_canonname; /* canonical name for hostname */
+ struct sockaddr *ai_addr; /* binary address */
+ struct addrinfo *ai_next; /* next structure in linked list */
};
#endif /* !HAVE_ADDRINFO */
@@ -140,30 +140,30 @@ struct addrinfo {
/*
* RFC 2553: protocol-independent placeholder for socket addresses
*/
-#define _SS_MAXSIZE 128
+#define _SS_MAXSIZE 128
#ifdef HAVE_LONG_LONG
-#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG))
+#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG))
#else
-#define _SS_ALIGNSIZE (sizeof(double))
+#define _SS_ALIGNSIZE (sizeof(double))
#endif /* HAVE_LONG_LONG */
-#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2)
-#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \
- _SS_PAD1SIZE - _SS_ALIGNSIZE)
+#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2)
+#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \
+ _SS_PAD1SIZE - _SS_ALIGNSIZE)
struct sockaddr_storage {
#ifdef HAVE_SOCKADDR_SA_LEN
- unsigned char ss_len; /* address length */
- unsigned char ss_family; /* address family */
+ unsigned char ss_len; /* address length */
+ unsigned char ss_family; /* address family */
#else
- unsigned short ss_family; /* address family */
+ unsigned short ss_family; /* address family */
#endif /* HAVE_SOCKADDR_SA_LEN */
- char __ss_pad1[_SS_PAD1SIZE];
+ char __ss_pad1[_SS_PAD1SIZE];
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG __ss_align; /* force desired structure storage alignment */
+ PY_LONG_LONG __ss_align; /* force desired structure storage alignment */
#else
- double __ss_align; /* force desired structure storage alignment */
+ double __ss_align; /* force desired structure storage alignment */
#endif /* HAVE_LONG_LONG */
- char __ss_pad2[_SS_PAD2SIZE];
+ char __ss_pad2[_SS_PAD2SIZE];
};
#endif /* !HAVE_SOCKADDR_STORAGE */
diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c
index 9c30a14..2729a77 100644
--- a/Modules/arraymodule.c
+++ b/Modules/arraymodule.c
@@ -11,7 +11,7 @@
#include <stddef.h>
#else /* !STDC_HEADERS */
#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h> /* For size_t */
+#include <sys/types.h> /* For size_t */
#endif /* HAVE_SYS_TYPES_H */
#endif /* !STDC_HEADERS */
@@ -22,22 +22,22 @@ struct arrayobject; /* Forward */
* functions aren't visible yet.
*/
struct arraydescr {
- int typecode;
- int itemsize;
- PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
- int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
- char *formats;
- int is_integer_type;
- int is_signed;
+ int typecode;
+ int itemsize;
+ PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
+ int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
+ char *formats;
+ int is_integer_type;
+ int is_signed;
};
typedef struct arrayobject {
- PyObject_VAR_HEAD
- char *ob_item;
- Py_ssize_t allocated;
- struct arraydescr *ob_descr;
- PyObject *weakreflist; /* List of weak references */
- int ob_exports; /* Number of exported buffers */
+ PyObject_VAR_HEAD
+ char *ob_item;
+ Py_ssize_t allocated;
+ struct arraydescr *ob_descr;
+ PyObject *weakreflist; /* List of weak references */
+ int ob_exports; /* Number of exported buffers */
} arrayobject;
static PyTypeObject Arraytype;
@@ -48,63 +48,63 @@ static PyTypeObject Arraytype;
static int
array_resize(arrayobject *self, Py_ssize_t newsize)
{
- char *items;
- size_t _new_size;
-
- if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
- PyErr_SetString(PyExc_BufferError,
- "cannot resize an array that is exporting buffers");
- return -1;
- }
-
- /* Bypass realloc() when a previous overallocation is large enough
- to accommodate the newsize. If the newsize is 16 smaller than the
- current size, then proceed with the realloc() to shrink the array.
- */
-
- if (self->allocated >= newsize &&
- Py_SIZE(self) < newsize + 16 &&
- self->ob_item != NULL) {
- Py_SIZE(self) = newsize;
- return 0;
- }
-
- if (newsize == 0) {
- PyMem_FREE(self->ob_item);
- self->ob_item = NULL;
- Py_SIZE(self) = 0;
- self->allocated = 0;
- return 0;
- }
-
- /* This over-allocates proportional to the array size, making room
- * for additional growth. The over-allocation is mild, but is
- * enough to give linear-time amortized behavior over a long
- * sequence of appends() in the presence of a poorly-performing
- * system realloc().
- * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
- * Note, the pattern starts out the same as for lists but then
- * grows at a smaller rate so that larger arrays only overallocate
- * by about 1/16th -- this is done because arrays are presumed to be more
- * memory critical.
- */
-
- _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
- items = self->ob_item;
- /* XXX The following multiplication and division does not optimize away
- like it does for lists since the size is not known at compile time */
- if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
- PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
- else
- items = NULL;
- if (items == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- self->ob_item = items;
- Py_SIZE(self) = newsize;
- self->allocated = _new_size;
- return 0;
+ char *items;
+ size_t _new_size;
+
+ if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
+ PyErr_SetString(PyExc_BufferError,
+ "cannot resize an array that is exporting buffers");
+ return -1;
+ }
+
+ /* Bypass realloc() when a previous overallocation is large enough
+ to accommodate the newsize. If the newsize is 16 smaller than the
+ current size, then proceed with the realloc() to shrink the array.
+ */
+
+ if (self->allocated >= newsize &&
+ Py_SIZE(self) < newsize + 16 &&
+ self->ob_item != NULL) {
+ Py_SIZE(self) = newsize;
+ return 0;
+ }
+
+ if (newsize == 0) {
+ PyMem_FREE(self->ob_item);
+ self->ob_item = NULL;
+ Py_SIZE(self) = 0;
+ self->allocated = 0;
+ return 0;
+ }
+
+ /* This over-allocates proportional to the array size, making room
+ * for additional growth. The over-allocation is mild, but is
+ * enough to give linear-time amortized behavior over a long
+ * sequence of appends() in the presence of a poorly-performing
+ * system realloc().
+ * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
+ * Note, the pattern starts out the same as for lists but then
+ * grows at a smaller rate so that larger arrays only overallocate
+ * by about 1/16th -- this is done because arrays are presumed to be more
+ * memory critical.
+ */
+
+ _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
+ items = self->ob_item;
+ /* XXX The following multiplication and division does not optimize away
+ like it does for lists since the size is not known at compile time */
+ if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
+ PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
+ else
+ items = NULL;
+ if (items == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->ob_item = items;
+ Py_SIZE(self) = newsize;
+ self->allocated = _new_size;
+ return 0;
}
/****************************************************************************
@@ -122,272 +122,272 @@ in bounds; that's the responsibility of the caller.
static PyObject *
b_getitem(arrayobject *ap, Py_ssize_t i)
{
- long x = ((char *)ap->ob_item)[i];
- if (x >= 128)
- x -= 256;
- return PyLong_FromLong(x);
+ long x = ((char *)ap->ob_item)[i];
+ if (x >= 128)
+ x -= 256;
+ return PyLong_FromLong(x);
}
static int
b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- short x;
- /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
- must use the next size up that is signed ('h') and manually do
- the overflow checking */
- if (!PyArg_Parse(v, "h;array item must be integer", &x))
- return -1;
- else if (x < -128) {
- PyErr_SetString(PyExc_OverflowError,
- "signed char is less than minimum");
- return -1;
- }
- else if (x > 127) {
- PyErr_SetString(PyExc_OverflowError,
- "signed char is greater than maximum");
- return -1;
- }
- if (i >= 0)
- ((char *)ap->ob_item)[i] = (char)x;
- return 0;
+ short x;
+ /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
+ must use the next size up that is signed ('h') and manually do
+ the overflow checking */
+ if (!PyArg_Parse(v, "h;array item must be integer", &x))
+ return -1;
+ else if (x < -128) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed char is less than minimum");
+ return -1;
+ }
+ else if (x > 127) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed char is greater than maximum");
+ return -1;
+ }
+ if (i >= 0)
+ ((char *)ap->ob_item)[i] = (char)x;
+ return 0;
}
static PyObject *
BB_getitem(arrayobject *ap, Py_ssize_t i)
{
- long x = ((unsigned char *)ap->ob_item)[i];
- return PyLong_FromLong(x);
+ long x = ((unsigned char *)ap->ob_item)[i];
+ return PyLong_FromLong(x);
}
static int
BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- unsigned char x;
- /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
- if (!PyArg_Parse(v, "b;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((char *)ap->ob_item)[i] = x;
- return 0;
+ unsigned char x;
+ /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
+ if (!PyArg_Parse(v, "b;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((char *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
u_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
+ return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
}
static int
u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- Py_UNICODE *p;
- Py_ssize_t len;
+ Py_UNICODE *p;
+ Py_ssize_t len;
- if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
- return -1;
- if (len != 1) {
- PyErr_SetString(PyExc_TypeError,
- "array item must be unicode character");
- return -1;
- }
- if (i >= 0)
- ((Py_UNICODE *)ap->ob_item)[i] = p[0];
- return 0;
+ if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
+ return -1;
+ if (len != 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "array item must be unicode character");
+ return -1;
+ }
+ if (i >= 0)
+ ((Py_UNICODE *)ap->ob_item)[i] = p[0];
+ return 0;
}
static PyObject *
h_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
+ return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
}
static int
h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- short x;
- /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
- if (!PyArg_Parse(v, "h;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((short *)ap->ob_item)[i] = x;
- return 0;
+ short x;
+ /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
+ if (!PyArg_Parse(v, "h;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((short *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
HH_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
+ return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
}
static int
HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- int x;
- /* PyArg_Parse's 'h' formatter is for a signed short, therefore
- must use the next size up and manually do the overflow checking */
- if (!PyArg_Parse(v, "i;array item must be integer", &x))
- return -1;
- else if (x < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned short is less than minimum");
- return -1;
- }
- else if (x > USHRT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned short is greater than maximum");
- return -1;
- }
- if (i >= 0)
- ((short *)ap->ob_item)[i] = (short)x;
- return 0;
+ int x;
+ /* PyArg_Parse's 'h' formatter is for a signed short, therefore
+ must use the next size up and manually do the overflow checking */
+ if (!PyArg_Parse(v, "i;array item must be integer", &x))
+ return -1;
+ else if (x < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned short is less than minimum");
+ return -1;
+ }
+ else if (x > USHRT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned short is greater than maximum");
+ return -1;
+ }
+ if (i >= 0)
+ ((short *)ap->ob_item)[i] = (short)x;
+ return 0;
}
static PyObject *
i_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
+ return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
}
static int
i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- int x;
- /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
- if (!PyArg_Parse(v, "i;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((int *)ap->ob_item)[i] = x;
- return 0;
+ int x;
+ /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
+ if (!PyArg_Parse(v, "i;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((int *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
II_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromUnsignedLong(
- (unsigned long) ((unsigned int *)ap->ob_item)[i]);
+ return PyLong_FromUnsignedLong(
+ (unsigned long) ((unsigned int *)ap->ob_item)[i]);
}
static int
II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- unsigned long x;
- if (PyLong_Check(v)) {
- x = PyLong_AsUnsignedLong(v);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return -1;
- }
- else {
- long y;
- if (!PyArg_Parse(v, "l;array item must be integer", &y))
- return -1;
- if (y < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned int is less than minimum");
- return -1;
- }
- x = (unsigned long)y;
-
- }
- if (x > UINT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned int is greater than maximum");
- return -1;
- }
-
- if (i >= 0)
- ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
- return 0;
+ unsigned long x;
+ if (PyLong_Check(v)) {
+ x = PyLong_AsUnsignedLong(v);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return -1;
+ }
+ else {
+ long y;
+ if (!PyArg_Parse(v, "l;array item must be integer", &y))
+ return -1;
+ if (y < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned int is less than minimum");
+ return -1;
+ }
+ x = (unsigned long)y;
+
+ }
+ if (x > UINT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned int is greater than maximum");
+ return -1;
+ }
+
+ if (i >= 0)
+ ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
+ return 0;
}
static PyObject *
l_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromLong(((long *)ap->ob_item)[i]);
+ return PyLong_FromLong(((long *)ap->ob_item)[i]);
}
static int
l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- long x;
- if (!PyArg_Parse(v, "l;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((long *)ap->ob_item)[i] = x;
- return 0;
+ long x;
+ if (!PyArg_Parse(v, "l;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((long *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
LL_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
+ return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
}
static int
LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- unsigned long x;
- if (PyLong_Check(v)) {
- x = PyLong_AsUnsignedLong(v);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return -1;
- }
- else {
- long y;
- if (!PyArg_Parse(v, "l;array item must be integer", &y))
- return -1;
- if (y < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned long is less than minimum");
- return -1;
- }
- x = (unsigned long)y;
-
- }
- if (x > ULONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned long is greater than maximum");
- return -1;
- }
-
- if (i >= 0)
- ((unsigned long *)ap->ob_item)[i] = x;
- return 0;
+ unsigned long x;
+ if (PyLong_Check(v)) {
+ x = PyLong_AsUnsignedLong(v);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return -1;
+ }
+ else {
+ long y;
+ if (!PyArg_Parse(v, "l;array item must be integer", &y))
+ return -1;
+ if (y < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned long is less than minimum");
+ return -1;
+ }
+ x = (unsigned long)y;
+
+ }
+ if (x > ULONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned long is greater than maximum");
+ return -1;
+ }
+
+ if (i >= 0)
+ ((unsigned long *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
f_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
+ return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
}
static int
f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- float x;
- if (!PyArg_Parse(v, "f;array item must be float", &x))
- return -1;
- if (i >= 0)
- ((float *)ap->ob_item)[i] = x;
- return 0;
+ float x;
+ if (!PyArg_Parse(v, "f;array item must be float", &x))
+ return -1;
+ if (i >= 0)
+ ((float *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
d_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
+ return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
}
static int
d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- double x;
- if (!PyArg_Parse(v, "d;array item must be float", &x))
- return -1;
- if (i >= 0)
- ((double *)ap->ob_item)[i] = x;
- return 0;
+ double x;
+ if (!PyArg_Parse(v, "d;array item must be float", &x))
+ return -1;
+ if (i >= 0)
+ ((double *)ap->ob_item)[i] = x;
+ return 0;
}
@@ -397,18 +397,18 @@ d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
* typecode.
*/
static struct arraydescr descriptors[] = {
- {'b', 1, b_getitem, b_setitem, "b", 1, 1},
- {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
- {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
- {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
- {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
- {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
- {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
- {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
- {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
- {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
- {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
- {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
+ {'b', 1, b_getitem, b_setitem, "b", 1, 1},
+ {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
+ {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
+ {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
+ {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
+ {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
+ {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
+ {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
+ {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
+ {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
+ {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
+ {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
};
/****************************************************************************
@@ -418,79 +418,79 @@ Implementations of array object methods.
static PyObject *
newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr)
{
- arrayobject *op;
- size_t nbytes;
-
- if (size < 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
-
- nbytes = size * descr->itemsize;
- /* Check for overflow */
- if (nbytes / descr->itemsize != (size_t)size) {
- return PyErr_NoMemory();
- }
- op = (arrayobject *) type->tp_alloc(type, 0);
- if (op == NULL) {
- return NULL;
- }
- op->ob_descr = descr;
- op->allocated = size;
- op->weakreflist = NULL;
- Py_SIZE(op) = size;
- if (size <= 0) {
- op->ob_item = NULL;
- }
- else {
- op->ob_item = PyMem_NEW(char, nbytes);
- if (op->ob_item == NULL) {
- Py_DECREF(op);
- return PyErr_NoMemory();
- }
- }
- op->ob_exports = 0;
- return (PyObject *) op;
+ arrayobject *op;
+ size_t nbytes;
+
+ if (size < 0) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ nbytes = size * descr->itemsize;
+ /* Check for overflow */
+ if (nbytes / descr->itemsize != (size_t)size) {
+ return PyErr_NoMemory();
+ }
+ op = (arrayobject *) type->tp_alloc(type, 0);
+ if (op == NULL) {
+ return NULL;
+ }
+ op->ob_descr = descr;
+ op->allocated = size;
+ op->weakreflist = NULL;
+ Py_SIZE(op) = size;
+ if (size <= 0) {
+ op->ob_item = NULL;
+ }
+ else {
+ op->ob_item = PyMem_NEW(char, nbytes);
+ if (op->ob_item == NULL) {
+ Py_DECREF(op);
+ return PyErr_NoMemory();
+ }
+ }
+ op->ob_exports = 0;
+ return (PyObject *) op;
}
static PyObject *
getarrayitem(PyObject *op, Py_ssize_t i)
{
- register arrayobject *ap;
- assert(array_Check(op));
- ap = (arrayobject *)op;
- assert(i>=0 && i<Py_SIZE(ap));
- return (*ap->ob_descr->getitem)(ap, i);
+ register arrayobject *ap;
+ assert(array_Check(op));
+ ap = (arrayobject *)op;
+ assert(i>=0 && i<Py_SIZE(ap));
+ return (*ap->ob_descr->getitem)(ap, i);
}
static int
ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
{
- char *items;
- Py_ssize_t n = Py_SIZE(self);
- if (v == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
- if ((*self->ob_descr->setitem)(self, -1, v) < 0)
- return -1;
-
- if (array_resize(self, n+1) == -1)
- return -1;
- items = self->ob_item;
- if (where < 0) {
- where += n;
- if (where < 0)
- where = 0;
- }
- if (where > n)
- where = n;
- /* appends don't need to call memmove() */
- if (where != n)
- memmove(items + (where+1)*self->ob_descr->itemsize,
- items + where*self->ob_descr->itemsize,
- (n-where)*self->ob_descr->itemsize);
- return (*self->ob_descr->setitem)(self, where, v);
+ char *items;
+ Py_ssize_t n = Py_SIZE(self);
+ if (v == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if ((*self->ob_descr->setitem)(self, -1, v) < 0)
+ return -1;
+
+ if (array_resize(self, n+1) == -1)
+ return -1;
+ items = self->ob_item;
+ if (where < 0) {
+ where += n;
+ if (where < 0)
+ where = 0;
+ }
+ if (where > n)
+ where = n;
+ /* appends don't need to call memmove() */
+ if (where != n)
+ memmove(items + (where+1)*self->ob_descr->itemsize,
+ items + where*self->ob_descr->itemsize,
+ (n-where)*self->ob_descr->itemsize);
+ return (*self->ob_descr->setitem)(self, where, v);
}
/* Methods */
@@ -498,141 +498,141 @@ ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
static void
array_dealloc(arrayobject *op)
{
- if (op->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) op);
- if (op->ob_item != NULL)
- PyMem_DEL(op->ob_item);
- Py_TYPE(op)->tp_free((PyObject *)op);
+ if (op->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) op);
+ if (op->ob_item != NULL)
+ PyMem_DEL(op->ob_item);
+ Py_TYPE(op)->tp_free((PyObject *)op);
}
static PyObject *
array_richcompare(PyObject *v, PyObject *w, int op)
{
- arrayobject *va, *wa;
- PyObject *vi = NULL;
- PyObject *wi = NULL;
- Py_ssize_t i, k;
- PyObject *res;
-
- if (!array_Check(v) || !array_Check(w)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- va = (arrayobject *)v;
- wa = (arrayobject *)w;
-
- if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
- /* Shortcut: if the lengths differ, the arrays differ */
- if (op == Py_EQ)
- res = Py_False;
- else
- res = Py_True;
- Py_INCREF(res);
- return res;
- }
-
- /* Search for the first index where items are different */
- k = 1;
- for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
- vi = getarrayitem(v, i);
- wi = getarrayitem(w, i);
- if (vi == NULL || wi == NULL) {
- Py_XDECREF(vi);
- Py_XDECREF(wi);
- return NULL;
- }
- k = PyObject_RichCompareBool(vi, wi, Py_EQ);
- if (k == 0)
- break; /* Keeping vi and wi alive! */
- Py_DECREF(vi);
- Py_DECREF(wi);
- if (k < 0)
- return NULL;
- }
-
- if (k) {
- /* No more items to compare -- compare sizes */
- Py_ssize_t vs = Py_SIZE(va);
- Py_ssize_t ws = Py_SIZE(wa);
- int cmp;
- switch (op) {
- case Py_LT: cmp = vs < ws; break;
- case Py_LE: cmp = vs <= ws; break;
- case Py_EQ: cmp = vs == ws; break;
- case Py_NE: cmp = vs != ws; break;
- case Py_GT: cmp = vs > ws; break;
- case Py_GE: cmp = vs >= ws; break;
- default: return NULL; /* cannot happen */
- }
- if (cmp)
- res = Py_True;
- else
- res = Py_False;
- Py_INCREF(res);
- return res;
- }
-
- /* We have an item that differs. First, shortcuts for EQ/NE */
- if (op == Py_EQ) {
- Py_INCREF(Py_False);
- res = Py_False;
- }
- else if (op == Py_NE) {
- Py_INCREF(Py_True);
- res = Py_True;
- }
- else {
- /* Compare the final item again using the proper operator */
- res = PyObject_RichCompare(vi, wi, op);
- }
- Py_DECREF(vi);
- Py_DECREF(wi);
- return res;
+ arrayobject *va, *wa;
+ PyObject *vi = NULL;
+ PyObject *wi = NULL;
+ Py_ssize_t i, k;
+ PyObject *res;
+
+ if (!array_Check(v) || !array_Check(w)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ va = (arrayobject *)v;
+ wa = (arrayobject *)w;
+
+ if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
+ /* Shortcut: if the lengths differ, the arrays differ */
+ if (op == Py_EQ)
+ res = Py_False;
+ else
+ res = Py_True;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* Search for the first index where items are different */
+ k = 1;
+ for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
+ vi = getarrayitem(v, i);
+ wi = getarrayitem(w, i);
+ if (vi == NULL || wi == NULL) {
+ Py_XDECREF(vi);
+ Py_XDECREF(wi);
+ return NULL;
+ }
+ k = PyObject_RichCompareBool(vi, wi, Py_EQ);
+ if (k == 0)
+ break; /* Keeping vi and wi alive! */
+ Py_DECREF(vi);
+ Py_DECREF(wi);
+ if (k < 0)
+ return NULL;
+ }
+
+ if (k) {
+ /* No more items to compare -- compare sizes */
+ Py_ssize_t vs = Py_SIZE(va);
+ Py_ssize_t ws = Py_SIZE(wa);
+ int cmp;
+ switch (op) {
+ case Py_LT: cmp = vs < ws; break;
+ case Py_LE: cmp = vs <= ws; break;
+ case Py_EQ: cmp = vs == ws; break;
+ case Py_NE: cmp = vs != ws; break;
+ case Py_GT: cmp = vs > ws; break;
+ case Py_GE: cmp = vs >= ws; break;
+ default: return NULL; /* cannot happen */
+ }
+ if (cmp)
+ res = Py_True;
+ else
+ res = Py_False;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* We have an item that differs. First, shortcuts for EQ/NE */
+ if (op == Py_EQ) {
+ Py_INCREF(Py_False);
+ res = Py_False;
+ }
+ else if (op == Py_NE) {
+ Py_INCREF(Py_True);
+ res = Py_True;
+ }
+ else {
+ /* Compare the final item again using the proper operator */
+ res = PyObject_RichCompare(vi, wi, op);
+ }
+ Py_DECREF(vi);
+ Py_DECREF(wi);
+ return res;
}
static Py_ssize_t
array_length(arrayobject *a)
{
- return Py_SIZE(a);
+ return Py_SIZE(a);
}
static PyObject *
array_item(arrayobject *a, Py_ssize_t i)
{
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError, "array index out of range");
- return NULL;
- }
- return getarrayitem((PyObject *)a, i);
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError, "array index out of range");
+ return NULL;
+ }
+ return getarrayitem((PyObject *)a, i);
}
static PyObject *
array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- arrayobject *np;
- if (ilow < 0)
- ilow = 0;
- else if (ilow > Py_SIZE(a))
- ilow = Py_SIZE(a);
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
- np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
- if (np == NULL)
- return NULL;
- memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
- (ihigh-ilow) * a->ob_descr->itemsize);
- return (PyObject *)np;
+ arrayobject *np;
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > Py_SIZE(a))
+ ilow = Py_SIZE(a);
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+ np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
+ if (np == NULL)
+ return NULL;
+ memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
+ (ihigh-ilow) * a->ob_descr->itemsize);
+ return (PyObject *)np;
}
static PyObject *
array_copy(arrayobject *a, PyObject *unused)
{
- return array_slice(a, 0, Py_SIZE(a));
+ return array_slice(a, 0, Py_SIZE(a));
}
PyDoc_STRVAR(copy_doc,
@@ -643,278 +643,278 @@ PyDoc_STRVAR(copy_doc,
static PyObject *
array_concat(arrayobject *a, PyObject *bb)
{
- Py_ssize_t size;
- arrayobject *np;
- if (!array_Check(bb)) {
- PyErr_Format(PyExc_TypeError,
- "can only append array (not \"%.200s\") to array",
- Py_TYPE(bb)->tp_name);
- return NULL;
- }
+ Py_ssize_t size;
+ arrayobject *np;
+ if (!array_Check(bb)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only append array (not \"%.200s\") to array",
+ Py_TYPE(bb)->tp_name);
+ return NULL;
+ }
#define b ((arrayobject *)bb)
- if (a->ob_descr != b->ob_descr) {
- PyErr_BadArgument();
- return NULL;
- }
- if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
- return PyErr_NoMemory();
- }
- size = Py_SIZE(a) + Py_SIZE(b);
- np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
- if (np == NULL) {
- return NULL;
- }
- memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
- memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
- b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
- return (PyObject *)np;
+ if (a->ob_descr != b->ob_descr) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
+ return PyErr_NoMemory();
+ }
+ size = Py_SIZE(a) + Py_SIZE(b);
+ np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
+ if (np == NULL) {
+ return NULL;
+ }
+ memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
+ memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
+ b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
+ return (PyObject *)np;
#undef b
}
static PyObject *
array_repeat(arrayobject *a, Py_ssize_t n)
{
- Py_ssize_t i;
- Py_ssize_t size;
- arrayobject *np;
- char *p;
- Py_ssize_t nbytes;
- if (n < 0)
- n = 0;
- if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
- return PyErr_NoMemory();
- }
- size = Py_SIZE(a) * n;
- np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
- if (np == NULL)
- return NULL;
- p = np->ob_item;
- nbytes = Py_SIZE(a) * a->ob_descr->itemsize;
- for (i = 0; i < n; i++) {
- memcpy(p, a->ob_item, nbytes);
- p += nbytes;
- }
- return (PyObject *) np;
+ Py_ssize_t i;
+ Py_ssize_t size;
+ arrayobject *np;
+ char *p;
+ Py_ssize_t nbytes;
+ if (n < 0)
+ n = 0;
+ if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
+ return PyErr_NoMemory();
+ }
+ size = Py_SIZE(a) * n;
+ np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
+ if (np == NULL)
+ return NULL;
+ p = np->ob_item;
+ nbytes = Py_SIZE(a) * a->ob_descr->itemsize;
+ for (i = 0; i < n; i++) {
+ memcpy(p, a->ob_item, nbytes);
+ p += nbytes;
+ }
+ return (PyObject *) np;
}
static int
array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
- char *item;
- Py_ssize_t n; /* Size of replacement array */
- Py_ssize_t d; /* Change in size */
+ char *item;
+ Py_ssize_t n; /* Size of replacement array */
+ Py_ssize_t d; /* Change in size */
#define b ((arrayobject *)v)
- if (v == NULL)
- n = 0;
- else if (array_Check(v)) {
- n = Py_SIZE(b);
- if (a == b) {
- /* Special case "a[i:j] = a" -- copy b first */
- int ret;
- v = array_slice(b, 0, n);
- if (!v)
- return -1;
- ret = array_ass_slice(a, ilow, ihigh, v);
- Py_DECREF(v);
- return ret;
- }
- if (b->ob_descr != a->ob_descr) {
- PyErr_BadArgument();
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "can only assign array (not \"%.200s\") to array slice",
- Py_TYPE(v)->tp_name);
- return -1;
- }
- if (ilow < 0)
- ilow = 0;
- else if (ilow > Py_SIZE(a))
- ilow = Py_SIZE(a);
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
- item = a->ob_item;
- d = n - (ihigh-ilow);
- /* Issue #4509: If the array has exported buffers and the slice
- assignment would change the size of the array, fail early to make
- sure we don't modify it. */
- if (d != 0 && a->ob_exports > 0) {
- PyErr_SetString(PyExc_BufferError,
- "cannot resize an array that is exporting buffers");
- return -1;
- }
- if (d < 0) { /* Delete -d items */
- memmove(item + (ihigh+d)*a->ob_descr->itemsize,
- item + ihigh*a->ob_descr->itemsize,
- (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
- if (array_resize(a, Py_SIZE(a) + d) == -1)
- return -1;
- }
- else if (d > 0) { /* Insert d items */
- if (array_resize(a, Py_SIZE(a) + d))
- return -1;
- memmove(item + (ihigh+d)*a->ob_descr->itemsize,
- item + ihigh*a->ob_descr->itemsize,
- (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
- }
- if (n > 0)
- memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
- n*b->ob_descr->itemsize);
- return 0;
+ if (v == NULL)
+ n = 0;
+ else if (array_Check(v)) {
+ n = Py_SIZE(b);
+ if (a == b) {
+ /* Special case "a[i:j] = a" -- copy b first */
+ int ret;
+ v = array_slice(b, 0, n);
+ if (!v)
+ return -1;
+ ret = array_ass_slice(a, ilow, ihigh, v);
+ Py_DECREF(v);
+ return ret;
+ }
+ if (b->ob_descr != a->ob_descr) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign array (not \"%.200s\") to array slice",
+ Py_TYPE(v)->tp_name);
+ return -1;
+ }
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > Py_SIZE(a))
+ ilow = Py_SIZE(a);
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+ item = a->ob_item;
+ d = n - (ihigh-ilow);
+ /* Issue #4509: If the array has exported buffers and the slice
+ assignment would change the size of the array, fail early to make
+ sure we don't modify it. */
+ if (d != 0 && a->ob_exports > 0) {
+ PyErr_SetString(PyExc_BufferError,
+ "cannot resize an array that is exporting buffers");
+ return -1;
+ }
+ if (d < 0) { /* Delete -d items */
+ memmove(item + (ihigh+d)*a->ob_descr->itemsize,
+ item + ihigh*a->ob_descr->itemsize,
+ (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
+ if (array_resize(a, Py_SIZE(a) + d) == -1)
+ return -1;
+ }
+ else if (d > 0) { /* Insert d items */
+ if (array_resize(a, Py_SIZE(a) + d))
+ return -1;
+ memmove(item + (ihigh+d)*a->ob_descr->itemsize,
+ item + ihigh*a->ob_descr->itemsize,
+ (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
+ }
+ if (n > 0)
+ memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
+ n*b->ob_descr->itemsize);
+ return 0;
#undef b
}
static int
array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
{
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError,
- "array assignment index out of range");
- return -1;
- }
- if (v == NULL)
- return array_ass_slice(a, i, i+1, v);
- return (*a->ob_descr->setitem)(a, i, v);
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError,
+ "array assignment index out of range");
+ return -1;
+ }
+ if (v == NULL)
+ return array_ass_slice(a, i, i+1, v);
+ return (*a->ob_descr->setitem)(a, i, v);
}
static int
setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
{
- assert(array_Check(a));
- return array_ass_item((arrayobject *)a, i, v);
+ assert(array_Check(a));
+ return array_ass_item((arrayobject *)a, i, v);
}
static int
array_iter_extend(arrayobject *self, PyObject *bb)
{
- PyObject *it, *v;
+ PyObject *it, *v;
- it = PyObject_GetIter(bb);
- if (it == NULL)
- return -1;
+ it = PyObject_GetIter(bb);
+ if (it == NULL)
+ return -1;
- while ((v = PyIter_Next(it)) != NULL) {
- if (ins1(self, (int) Py_SIZE(self), v) != 0) {
- Py_DECREF(v);
- Py_DECREF(it);
- return -1;
- }
- Py_DECREF(v);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return -1;
- return 0;
+ while ((v = PyIter_Next(it)) != NULL) {
+ if (ins1(self, (int) Py_SIZE(self), v) != 0) {
+ Py_DECREF(v);
+ Py_DECREF(it);
+ return -1;
+ }
+ Py_DECREF(v);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return -1;
+ return 0;
}
static int
array_do_extend(arrayobject *self, PyObject *bb)
{
- Py_ssize_t size, oldsize, bbsize;
-
- if (!array_Check(bb))
- return array_iter_extend(self, bb);
+ Py_ssize_t size, oldsize, bbsize;
+
+ if (!array_Check(bb))
+ return array_iter_extend(self, bb);
#define b ((arrayobject *)bb)
- if (self->ob_descr != b->ob_descr) {
- PyErr_SetString(PyExc_TypeError,
- "can only extend with array of same kind");
- return -1;
- }
- if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
- ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
- PyErr_NoMemory();
- return -1;
- }
- oldsize = Py_SIZE(self);
- /* Get the size of bb before resizing the array since bb could be self. */
- bbsize = Py_SIZE(bb);
- size = oldsize + Py_SIZE(b);
- if (array_resize(self, size) == -1)
- return -1;
- memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
- b->ob_item, bbsize * b->ob_descr->itemsize);
-
- return 0;
+ if (self->ob_descr != b->ob_descr) {
+ PyErr_SetString(PyExc_TypeError,
+ "can only extend with array of same kind");
+ return -1;
+ }
+ if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
+ ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ oldsize = Py_SIZE(self);
+ /* Get the size of bb before resizing the array since bb could be self. */
+ bbsize = Py_SIZE(bb);
+ size = oldsize + Py_SIZE(b);
+ if (array_resize(self, size) == -1)
+ return -1;
+ memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
+ b->ob_item, bbsize * b->ob_descr->itemsize);
+
+ return 0;
#undef b
}
static PyObject *
array_inplace_concat(arrayobject *self, PyObject *bb)
{
- if (!array_Check(bb)) {
- PyErr_Format(PyExc_TypeError,
- "can only extend array with array (not \"%.200s\")",
- Py_TYPE(bb)->tp_name);
- return NULL;
- }
- if (array_do_extend(self, bb) == -1)
- return NULL;
- Py_INCREF(self);
- return (PyObject *)self;
+ if (!array_Check(bb)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only extend array with array (not \"%.200s\")",
+ Py_TYPE(bb)->tp_name);
+ return NULL;
+ }
+ if (array_do_extend(self, bb) == -1)
+ return NULL;
+ Py_INCREF(self);
+ return (PyObject *)self;
}
static PyObject *
array_inplace_repeat(arrayobject *self, Py_ssize_t n)
{
- char *items, *p;
- Py_ssize_t size, i;
-
- if (Py_SIZE(self) > 0) {
- if (n < 0)
- n = 0;
- items = self->ob_item;
- if ((self->ob_descr->itemsize != 0) &&
- (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
- return PyErr_NoMemory();
- }
- size = Py_SIZE(self) * self->ob_descr->itemsize;
- if (n > 0 && size > PY_SSIZE_T_MAX / n) {
- return PyErr_NoMemory();
- }
- if (array_resize(self, n * Py_SIZE(self)) == -1)
- return NULL;
- items = p = self->ob_item;
- for (i = 1; i < n; i++) {
- p += size;
- memcpy(p, items, size);
- }
- }
- Py_INCREF(self);
- return (PyObject *)self;
+ char *items, *p;
+ Py_ssize_t size, i;
+
+ if (Py_SIZE(self) > 0) {
+ if (n < 0)
+ n = 0;
+ items = self->ob_item;
+ if ((self->ob_descr->itemsize != 0) &&
+ (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
+ return PyErr_NoMemory();
+ }
+ size = Py_SIZE(self) * self->ob_descr->itemsize;
+ if (n > 0 && size > PY_SSIZE_T_MAX / n) {
+ return PyErr_NoMemory();
+ }
+ if (array_resize(self, n * Py_SIZE(self)) == -1)
+ return NULL;
+ items = p = self->ob_item;
+ for (i = 1; i < n; i++) {
+ p += size;
+ memcpy(p, items, size);
+ }
+ }
+ Py_INCREF(self);
+ return (PyObject *)self;
}
static PyObject *
ins(arrayobject *self, Py_ssize_t where, PyObject *v)
{
- if (ins1(self, where, v) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (ins1(self, where, v) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_count(arrayobject *self, PyObject *v)
{
- Py_ssize_t count = 0;
- Py_ssize_t i;
+ Py_ssize_t count = 0;
+ Py_ssize_t i;
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self, i);
- int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- if (cmp > 0)
- count++;
- else if (cmp < 0)
- return NULL;
- }
- return PyLong_FromSsize_t(count);
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self, i);
+ int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ if (cmp > 0)
+ count++;
+ else if (cmp < 0)
+ return NULL;
+ }
+ return PyLong_FromSsize_t(count);
}
PyDoc_STRVAR(count_doc,
@@ -925,20 +925,20 @@ Return number of occurrences of x in the array.");
static PyObject *
array_index(arrayobject *self, PyObject *v)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self, i);
- int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- if (cmp > 0) {
- return PyLong_FromLong((long)i);
- }
- else if (cmp < 0)
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
- return NULL;
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self, i);
+ int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ if (cmp > 0) {
+ return PyLong_FromLong((long)i);
+ }
+ else if (cmp < 0)
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
+ return NULL;
}
PyDoc_STRVAR(index_doc,
@@ -949,38 +949,38 @@ Return index of first occurrence of x in the array.");
static int
array_contains(arrayobject *self, PyObject *v)
{
- Py_ssize_t i;
- int cmp;
+ Py_ssize_t i;
+ int cmp;
- for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self, i);
- cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- }
- return cmp;
+ for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self, i);
+ cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ }
+ return cmp;
}
static PyObject *
array_remove(arrayobject *self, PyObject *v)
{
- int i;
-
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self,i);
- int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- if (cmp > 0) {
- if (array_ass_slice(self, i, i+1,
- (PyObject *)NULL) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
- }
- else if (cmp < 0)
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
- return NULL;
+ int i;
+
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self,i);
+ int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ if (cmp > 0) {
+ if (array_ass_slice(self, i, i+1,
+ (PyObject *)NULL) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else if (cmp < 0)
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
+ return NULL;
}
PyDoc_STRVAR(remove_doc,
@@ -991,27 +991,27 @@ Remove the first occurrence of x in the array.");
static PyObject *
array_pop(arrayobject *self, PyObject *args)
{
- Py_ssize_t i = -1;
- PyObject *v;
- if (!PyArg_ParseTuple(args, "|n:pop", &i))
- return NULL;
- if (Py_SIZE(self) == 0) {
- /* Special-case most common failure cause */
- PyErr_SetString(PyExc_IndexError, "pop from empty array");
- return NULL;
- }
- if (i < 0)
- i += Py_SIZE(self);
- if (i < 0 || i >= Py_SIZE(self)) {
- PyErr_SetString(PyExc_IndexError, "pop index out of range");
- return NULL;
- }
- v = getarrayitem((PyObject *)self,i);
- if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
- Py_DECREF(v);
- return NULL;
- }
- return v;
+ Py_ssize_t i = -1;
+ PyObject *v;
+ if (!PyArg_ParseTuple(args, "|n:pop", &i))
+ return NULL;
+ if (Py_SIZE(self) == 0) {
+ /* Special-case most common failure cause */
+ PyErr_SetString(PyExc_IndexError, "pop from empty array");
+ return NULL;
+ }
+ if (i < 0)
+ i += Py_SIZE(self);
+ if (i < 0 || i >= Py_SIZE(self)) {
+ PyErr_SetString(PyExc_IndexError, "pop index out of range");
+ return NULL;
+ }
+ v = getarrayitem((PyObject *)self,i);
+ if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ return v;
}
PyDoc_STRVAR(pop_doc,
@@ -1022,10 +1022,10 @@ Return the i-th element and delete it from the array. i defaults to -1.");
static PyObject *
array_extend(arrayobject *self, PyObject *bb)
{
- if (array_do_extend(self, bb) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (array_do_extend(self, bb) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(extend_doc,
@@ -1036,11 +1036,11 @@ PyDoc_STRVAR(extend_doc,
static PyObject *
array_insert(arrayobject *self, PyObject *args)
{
- Py_ssize_t i;
- PyObject *v;
- if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
- return NULL;
- return ins(self, i, v);
+ Py_ssize_t i;
+ PyObject *v;
+ if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
+ return NULL;
+ return ins(self, i, v);
}
PyDoc_STRVAR(insert_doc,
@@ -1052,15 +1052,15 @@ Insert a new item x into the array before position i.");
static PyObject *
array_buffer_info(arrayobject *self, PyObject *unused)
{
- PyObject* retval = NULL;
- retval = PyTuple_New(2);
- if (!retval)
- return NULL;
+ PyObject* retval = NULL;
+ retval = PyTuple_New(2);
+ if (!retval)
+ return NULL;
- PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
- PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self))));
+ PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
+ PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self))));
- return retval;
+ return retval;
}
PyDoc_STRVAR(buffer_info_doc,
@@ -1075,7 +1075,7 @@ the buffer length in bytes.");
static PyObject *
array_append(arrayobject *self, PyObject *v)
{
- return ins(self, (int) Py_SIZE(self), v);
+ return ins(self, (int) Py_SIZE(self), v);
}
PyDoc_STRVAR(append_doc,
@@ -1087,52 +1087,52 @@ Append new value x to the end of the array.");
static PyObject *
array_byteswap(arrayobject *self, PyObject *unused)
{
- char *p;
- Py_ssize_t i;
-
- switch (self->ob_descr->itemsize) {
- case 1:
- break;
- case 2:
- for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
- char p0 = p[0];
- p[0] = p[1];
- p[1] = p0;
- }
- break;
- case 4:
- for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
- char p0 = p[0];
- char p1 = p[1];
- p[0] = p[3];
- p[1] = p[2];
- p[2] = p1;
- p[3] = p0;
- }
- break;
- case 8:
- for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
- char p0 = p[0];
- char p1 = p[1];
- char p2 = p[2];
- char p3 = p[3];
- p[0] = p[7];
- p[1] = p[6];
- p[2] = p[5];
- p[3] = p[4];
- p[4] = p3;
- p[5] = p2;
- p[6] = p1;
- p[7] = p0;
- }
- break;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "don't know how to byteswap this array type");
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ char *p;
+ Py_ssize_t i;
+
+ switch (self->ob_descr->itemsize) {
+ case 1:
+ break;
+ case 2:
+ for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
+ char p0 = p[0];
+ p[0] = p[1];
+ p[1] = p0;
+ }
+ break;
+ case 4:
+ for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
+ char p0 = p[0];
+ char p1 = p[1];
+ p[0] = p[3];
+ p[1] = p[2];
+ p[2] = p1;
+ p[3] = p0;
+ }
+ break;
+ case 8:
+ for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
+ char p0 = p[0];
+ char p1 = p[1];
+ char p2 = p[2];
+ char p3 = p[3];
+ p[0] = p[7];
+ p[1] = p[6];
+ p[2] = p[5];
+ p[3] = p[4];
+ p[4] = p3;
+ p[5] = p2;
+ p[6] = p1;
+ p[7] = p0;
+ }
+ break;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "don't know how to byteswap this array type");
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(byteswap_doc,
@@ -1144,28 +1144,28 @@ Byteswap all items of the array. If the items in the array are not 1, 2,\n\
static PyObject *
array_reverse(arrayobject *self, PyObject *unused)
{
- register Py_ssize_t itemsize = self->ob_descr->itemsize;
- register char *p, *q;
- /* little buffer to hold items while swapping */
- char tmp[256]; /* 8 is probably enough -- but why skimp */
- assert((size_t)itemsize <= sizeof(tmp));
-
- if (Py_SIZE(self) > 1) {
- for (p = self->ob_item,
- q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
- p < q;
- p += itemsize, q -= itemsize) {
- /* memory areas guaranteed disjoint, so memcpy
- * is safe (& memmove may be slower).
- */
- memcpy(tmp, p, itemsize);
- memcpy(p, q, itemsize);
- memcpy(q, tmp, itemsize);
- }
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ register Py_ssize_t itemsize = self->ob_descr->itemsize;
+ register char *p, *q;
+ /* little buffer to hold items while swapping */
+ char tmp[256]; /* 8 is probably enough -- but why skimp */
+ assert((size_t)itemsize <= sizeof(tmp));
+
+ if (Py_SIZE(self) > 1) {
+ for (p = self->ob_item,
+ q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
+ p < q;
+ p += itemsize, q -= itemsize) {
+ /* memory areas guaranteed disjoint, so memcpy
+ * is safe (& memmove may be slower).
+ */
+ memcpy(tmp, p, itemsize);
+ memcpy(p, q, itemsize);
+ memcpy(q, tmp, itemsize);
+ }
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(reverse_doc,
@@ -1180,51 +1180,51 @@ static PyObject *array_fromstring(arrayobject *self, PyObject *args);
static PyObject *
array_fromfile(arrayobject *self, PyObject *args)
{
- PyObject *f, *b, *res;
- Py_ssize_t itemsize = self->ob_descr->itemsize;
- Py_ssize_t n, nbytes;
- int not_enough_bytes;
+ PyObject *f, *b, *res;
+ Py_ssize_t itemsize = self->ob_descr->itemsize;
+ Py_ssize_t n, nbytes;
+ int not_enough_bytes;
- if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
- return NULL;
+ if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
+ return NULL;
- nbytes = n * itemsize;
- if (nbytes < 0 || nbytes/itemsize != n) {
- PyErr_NoMemory();
- return NULL;
- }
+ nbytes = n * itemsize;
+ if (nbytes < 0 || nbytes/itemsize != n) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- b = PyObject_CallMethod(f, "read", "n", nbytes);
- if (b == NULL)
- return NULL;
+ b = PyObject_CallMethod(f, "read", "n", nbytes);
+ if (b == NULL)
+ return NULL;
- if (!PyBytes_Check(b)) {
- PyErr_SetString(PyExc_TypeError,
- "read() didn't return bytes");
- Py_DECREF(b);
- return NULL;
- }
+ if (!PyBytes_Check(b)) {
+ PyErr_SetString(PyExc_TypeError,
+ "read() didn't return bytes");
+ Py_DECREF(b);
+ return NULL;
+ }
- not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
+ not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
- args = Py_BuildValue("(O)", b);
- Py_DECREF(b);
- if (args == NULL)
- return NULL;
+ args = Py_BuildValue("(O)", b);
+ Py_DECREF(b);
+ if (args == NULL)
+ return NULL;
- res = array_fromstring(self, args);
- Py_DECREF(args);
- if (res == NULL)
- return NULL;
+ res = array_fromstring(self, args);
+ Py_DECREF(args);
+ if (res == NULL)
+ return NULL;
- if (not_enough_bytes) {
- PyErr_SetString(PyExc_EOFError,
- "read() didn't return enough bytes");
- Py_DECREF(res);
- return NULL;
- }
+ if (not_enough_bytes) {
+ PyErr_SetString(PyExc_EOFError,
+ "read() didn't return enough bytes");
+ Py_DECREF(res);
+ return NULL;
+ }
- return res;
+ return res;
}
PyDoc_STRVAR(fromfile_doc,
@@ -1237,35 +1237,35 @@ array.");
static PyObject *
array_tofile(arrayobject *self, PyObject *f)
{
- Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
- /* Write 64K blocks at a time */
- /* XXX Make the block size settable */
- int BLOCKSIZE = 64*1024;
- Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
- Py_ssize_t i;
-
- if (Py_SIZE(self) == 0)
- goto done;
-
- for (i = 0; i < nblocks; i++) {
- char* ptr = self->ob_item + i*BLOCKSIZE;
- Py_ssize_t size = BLOCKSIZE;
- PyObject *bytes, *res;
- if (i*BLOCKSIZE + size > nbytes)
- size = nbytes - i*BLOCKSIZE;
- bytes = PyBytes_FromStringAndSize(ptr, size);
- if (bytes == NULL)
- return NULL;
- res = PyObject_CallMethod(f, "write", "O", bytes);
- Py_DECREF(bytes);
- if (res == NULL)
- return NULL;
- Py_DECREF(res); /* drop write result */
- }
+ Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
+ /* Write 64K blocks at a time */
+ /* XXX Make the block size settable */
+ int BLOCKSIZE = 64*1024;
+ Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
+ Py_ssize_t i;
+
+ if (Py_SIZE(self) == 0)
+ goto done;
+
+ for (i = 0; i < nblocks; i++) {
+ char* ptr = self->ob_item + i*BLOCKSIZE;
+ Py_ssize_t size = BLOCKSIZE;
+ PyObject *bytes, *res;
+ if (i*BLOCKSIZE + size > nbytes)
+ size = nbytes - i*BLOCKSIZE;
+ bytes = PyBytes_FromStringAndSize(ptr, size);
+ if (bytes == NULL)
+ return NULL;
+ res = PyObject_CallMethod(f, "write", "O", bytes);
+ Py_DECREF(bytes);
+ if (res == NULL)
+ return NULL;
+ Py_DECREF(res); /* drop write result */
+ }
done:
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(tofile_doc,
@@ -1277,29 +1277,29 @@ Write all items (as machine values) to the file object f.");
static PyObject *
array_fromlist(arrayobject *self, PyObject *list)
{
- Py_ssize_t n;
-
- if (!PyList_Check(list)) {
- PyErr_SetString(PyExc_TypeError, "arg must be list");
- return NULL;
- }
- n = PyList_Size(list);
- if (n > 0) {
- Py_ssize_t i, old_size;
- old_size = Py_SIZE(self);
- if (array_resize(self, old_size + n) == -1)
- return NULL;
- for (i = 0; i < n; i++) {
- PyObject *v = PyList_GetItem(list, i);
- if ((*self->ob_descr->setitem)(self,
- Py_SIZE(self) - n + i, v) != 0) {
- array_resize(self, old_size);
- return NULL;
- }
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t n;
+
+ if (!PyList_Check(list)) {
+ PyErr_SetString(PyExc_TypeError, "arg must be list");
+ return NULL;
+ }
+ n = PyList_Size(list);
+ if (n > 0) {
+ Py_ssize_t i, old_size;
+ old_size = Py_SIZE(self);
+ if (array_resize(self, old_size + n) == -1)
+ return NULL;
+ for (i = 0; i < n; i++) {
+ PyObject *v = PyList_GetItem(list, i);
+ if ((*self->ob_descr->setitem)(self,
+ Py_SIZE(self) - n + i, v) != 0) {
+ array_resize(self, old_size);
+ return NULL;
+ }
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromlist_doc,
@@ -1310,20 +1310,20 @@ Append items to array from list.");
static PyObject *
array_tolist(arrayobject *self, PyObject *unused)
{
- PyObject *list = PyList_New(Py_SIZE(self));
- Py_ssize_t i;
+ PyObject *list = PyList_New(Py_SIZE(self));
+ Py_ssize_t i;
- if (list == NULL)
- return NULL;
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *v = getarrayitem((PyObject *)self, i);
- if (v == NULL) {
- Py_DECREF(list);
- return NULL;
- }
- PyList_SetItem(list, i, v);
- }
- return list;
+ if (list == NULL)
+ return NULL;
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *v = getarrayitem((PyObject *)self, i);
+ if (v == NULL) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ PyList_SetItem(list, i, v);
+ }
+ return list;
}
PyDoc_STRVAR(tolist_doc,
@@ -1335,30 +1335,30 @@ Convert array to an ordinary list with the same items.");
static PyObject *
array_fromstring(arrayobject *self, PyObject *args)
{
- char *str;
- Py_ssize_t n;
- int itemsize = self->ob_descr->itemsize;
- if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n))
- return NULL;
- if (n % itemsize != 0) {
- PyErr_SetString(PyExc_ValueError,
- "string length not a multiple of item size");
- return NULL;
- }
- n = n / itemsize;
- if (n > 0) {
- Py_ssize_t old_size = Py_SIZE(self);
- if ((n > PY_SSIZE_T_MAX - old_size) ||
- ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
- return PyErr_NoMemory();
- }
- if (array_resize(self, old_size + n) == -1)
- return NULL;
- memcpy(self->ob_item + old_size * itemsize,
- str, n * itemsize);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ Py_ssize_t n;
+ int itemsize = self->ob_descr->itemsize;
+ if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n))
+ return NULL;
+ if (n % itemsize != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "string length not a multiple of item size");
+ return NULL;
+ }
+ n = n / itemsize;
+ if (n > 0) {
+ Py_ssize_t old_size = Py_SIZE(self);
+ if ((n > PY_SSIZE_T_MAX - old_size) ||
+ ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
+ return PyErr_NoMemory();
+ }
+ if (array_resize(self, old_size + n) == -1)
+ return NULL;
+ memcpy(self->ob_item + old_size * itemsize,
+ str, n * itemsize);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromstring_doc,
@@ -1371,12 +1371,12 @@ values, as if it had been read from a file using the fromfile() method).");
static PyObject *
array_tostring(arrayobject *self, PyObject *unused)
{
- if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
- return PyBytes_FromStringAndSize(self->ob_item,
- Py_SIZE(self) * self->ob_descr->itemsize);
- } else {
- return PyErr_NoMemory();
- }
+ if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
+ return PyBytes_FromStringAndSize(self->ob_item,
+ Py_SIZE(self) * self->ob_descr->itemsize);
+ } else {
+ return PyErr_NoMemory();
+ }
}
PyDoc_STRVAR(tostring_doc,
@@ -1390,29 +1390,29 @@ representation.");
static PyObject *
array_fromunicode(arrayobject *self, PyObject *args)
{
- Py_UNICODE *ustr;
- Py_ssize_t n;
- char typecode;
-
- if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
- return NULL;
- typecode = self->ob_descr->typecode;
- if ((typecode != 'u')) {
- PyErr_SetString(PyExc_ValueError,
- "fromunicode() may only be called on "
- "unicode type arrays");
- return NULL;
- }
- if (n > 0) {
- Py_ssize_t old_size = Py_SIZE(self);
- if (array_resize(self, old_size + n) == -1)
- return NULL;
- memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
- ustr, n * sizeof(Py_UNICODE));
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_UNICODE *ustr;
+ Py_ssize_t n;
+ char typecode;
+
+ if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
+ return NULL;
+ typecode = self->ob_descr->typecode;
+ if ((typecode != 'u')) {
+ PyErr_SetString(PyExc_ValueError,
+ "fromunicode() may only be called on "
+ "unicode type arrays");
+ return NULL;
+ }
+ if (n > 0) {
+ Py_ssize_t old_size = Py_SIZE(self);
+ if (array_resize(self, old_size + n) == -1)
+ return NULL;
+ memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
+ ustr, n * sizeof(Py_UNICODE));
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromunicode_doc,
@@ -1427,14 +1427,14 @@ append Unicode data to an array of some other type.");
static PyObject *
array_tounicode(arrayobject *self, PyObject *unused)
{
- char typecode;
- typecode = self->ob_descr->typecode;
- if ((typecode != 'u')) {
- PyErr_SetString(PyExc_ValueError,
- "tounicode() may only be called on unicode type arrays");
- return NULL;
- }
- return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
+ char typecode;
+ typecode = self->ob_descr->typecode;
+ if ((typecode != 'u')) {
+ PyErr_SetString(PyExc_ValueError,
+ "tounicode() may only be called on unicode type arrays");
+ return NULL;
+ }
+ return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
}
PyDoc_STRVAR(tounicode_doc,
@@ -1450,71 +1450,71 @@ an array of some other type.");
/*********************** Pickling support ************************/
enum machine_format_code {
- UNKNOWN_FORMAT = -1,
- /* UNKNOWN_FORMAT is used to indicate that the machine format for an
- * array type code cannot be interpreted. When this occurs, a list of
- * Python objects is used to represent the content of the array
- * instead of using the memory content of the array directly. In that
- * case, the array_reconstructor mechanism is bypassed completely, and
- * the standard array constructor is used instead.
- *
- * This is will most likely occur when the machine doesn't use IEEE
- * floating-point numbers.
- */
-
- UNSIGNED_INT8 = 0,
- SIGNED_INT8 = 1,
- UNSIGNED_INT16_LE = 2,
- UNSIGNED_INT16_BE = 3,
- SIGNED_INT16_LE = 4,
- SIGNED_INT16_BE = 5,
- UNSIGNED_INT32_LE = 6,
- UNSIGNED_INT32_BE = 7,
- SIGNED_INT32_LE = 8,
- SIGNED_INT32_BE = 9,
- UNSIGNED_INT64_LE = 10,
- UNSIGNED_INT64_BE = 11,
- SIGNED_INT64_LE = 12,
- SIGNED_INT64_BE = 13,
- IEEE_754_FLOAT_LE = 14,
- IEEE_754_FLOAT_BE = 15,
- IEEE_754_DOUBLE_LE = 16,
- IEEE_754_DOUBLE_BE = 17,
- UTF16_LE = 18,
- UTF16_BE = 19,
- UTF32_LE = 20,
- UTF32_BE = 21
+ UNKNOWN_FORMAT = -1,
+ /* UNKNOWN_FORMAT is used to indicate that the machine format for an
+ * array type code cannot be interpreted. When this occurs, a list of
+ * Python objects is used to represent the content of the array
+ * instead of using the memory content of the array directly. In that
+ * case, the array_reconstructor mechanism is bypassed completely, and
+ * the standard array constructor is used instead.
+ *
+ * This is will most likely occur when the machine doesn't use IEEE
+ * floating-point numbers.
+ */
+
+ UNSIGNED_INT8 = 0,
+ SIGNED_INT8 = 1,
+ UNSIGNED_INT16_LE = 2,
+ UNSIGNED_INT16_BE = 3,
+ SIGNED_INT16_LE = 4,
+ SIGNED_INT16_BE = 5,
+ UNSIGNED_INT32_LE = 6,
+ UNSIGNED_INT32_BE = 7,
+ SIGNED_INT32_LE = 8,
+ SIGNED_INT32_BE = 9,
+ UNSIGNED_INT64_LE = 10,
+ UNSIGNED_INT64_BE = 11,
+ SIGNED_INT64_LE = 12,
+ SIGNED_INT64_BE = 13,
+ IEEE_754_FLOAT_LE = 14,
+ IEEE_754_FLOAT_BE = 15,
+ IEEE_754_DOUBLE_LE = 16,
+ IEEE_754_DOUBLE_BE = 17,
+ UTF16_LE = 18,
+ UTF16_BE = 19,
+ UTF32_LE = 20,
+ UTF32_BE = 21
};
#define MACHINE_FORMAT_CODE_MIN 0
#define MACHINE_FORMAT_CODE_MAX 21
static const struct mformatdescr {
- size_t size;
- int is_signed;
- int is_big_endian;
+ size_t size;
+ int is_signed;
+ int is_big_endian;
} mformat_descriptors[] = {
- {1, 0, 0}, /* 0: UNSIGNED_INT8 */
- {1, 1, 0}, /* 1: SIGNED_INT8 */
- {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
- {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
- {2, 1, 0}, /* 4: SIGNED_INT16_LE */
- {2, 1, 1}, /* 5: SIGNED_INT16_BE */
- {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
- {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
- {4, 1, 0}, /* 8: SIGNED_INT32_LE */
- {4, 1, 1}, /* 9: SIGNED_INT32_BE */
- {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
- {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
- {8, 1, 0}, /* 12: SIGNED_INT64_LE */
- {8, 1, 1}, /* 13: SIGNED_INT64_BE */
- {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
- {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
- {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
- {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
- {4, 0, 0}, /* 18: UTF16_LE */
- {4, 0, 1}, /* 19: UTF16_BE */
- {8, 0, 0}, /* 20: UTF32_LE */
- {8, 0, 1} /* 21: UTF32_BE */
+ {1, 0, 0}, /* 0: UNSIGNED_INT8 */
+ {1, 1, 0}, /* 1: SIGNED_INT8 */
+ {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
+ {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
+ {2, 1, 0}, /* 4: SIGNED_INT16_LE */
+ {2, 1, 1}, /* 5: SIGNED_INT16_BE */
+ {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
+ {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
+ {4, 1, 0}, /* 8: SIGNED_INT32_LE */
+ {4, 1, 1}, /* 9: SIGNED_INT32_BE */
+ {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
+ {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
+ {8, 1, 0}, /* 12: SIGNED_INT64_LE */
+ {8, 1, 1}, /* 13: SIGNED_INT64_BE */
+ {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
+ {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
+ {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
+ {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
+ {4, 0, 0}, /* 18: UTF16_LE */
+ {4, 0, 1}, /* 19: UTF16_BE */
+ {8, 0, 0}, /* 20: UTF32_LE */
+ {8, 0, 1} /* 21: UTF32_BE */
};
@@ -1527,86 +1527,86 @@ static enum machine_format_code
typecode_to_mformat_code(int typecode)
{
#ifdef WORDS_BIGENDIAN
- const int is_big_endian = 1;
+ const int is_big_endian = 1;
#else
- const int is_big_endian = 0;
+ const int is_big_endian = 0;
#endif
- size_t intsize;
- int is_signed;
-
- switch (typecode) {
- case 'b':
- return SIGNED_INT8;
- case 'B':
- return UNSIGNED_INT8;
-
- case 'u':
- if (sizeof(Py_UNICODE) == 2) {
- return UTF16_LE + is_big_endian;
- }
- if (sizeof(Py_UNICODE) == 4) {
- return UTF32_LE + is_big_endian;
- }
- return UNKNOWN_FORMAT;
-
- case 'f':
- if (sizeof(float) == 4) {
- const float y = 16711938.0;
- if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
- return IEEE_754_FLOAT_BE;
- if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
- return IEEE_754_FLOAT_LE;
- }
- return UNKNOWN_FORMAT;
-
- case 'd':
- if (sizeof(double) == 8) {
- const double x = 9006104071832581.0;
- if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
- return IEEE_754_DOUBLE_BE;
- if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
- return IEEE_754_DOUBLE_LE;
- }
- return UNKNOWN_FORMAT;
-
- /* Integers */
- case 'h':
- intsize = sizeof(short);
- is_signed = 1;
- break;
- case 'H':
- intsize = sizeof(short);
- is_signed = 0;
- break;
- case 'i':
- intsize = sizeof(int);
- is_signed = 1;
- break;
- case 'I':
- intsize = sizeof(int);
- is_signed = 0;
- break;
- case 'l':
- intsize = sizeof(long);
- is_signed = 1;
- break;
- case 'L':
- intsize = sizeof(long);
- is_signed = 0;
- break;
- default:
- return UNKNOWN_FORMAT;
- }
- switch (intsize) {
- case 2:
- return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
- case 4:
- return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
- case 8:
- return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
- default:
- return UNKNOWN_FORMAT;
- }
+ size_t intsize;
+ int is_signed;
+
+ switch (typecode) {
+ case 'b':
+ return SIGNED_INT8;
+ case 'B':
+ return UNSIGNED_INT8;
+
+ case 'u':
+ if (sizeof(Py_UNICODE) == 2) {
+ return UTF16_LE + is_big_endian;
+ }
+ if (sizeof(Py_UNICODE) == 4) {
+ return UTF32_LE + is_big_endian;
+ }
+ return UNKNOWN_FORMAT;
+
+ case 'f':
+ if (sizeof(float) == 4) {
+ const float y = 16711938.0;
+ if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
+ return IEEE_754_FLOAT_BE;
+ if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
+ return IEEE_754_FLOAT_LE;
+ }
+ return UNKNOWN_FORMAT;
+
+ case 'd':
+ if (sizeof(double) == 8) {
+ const double x = 9006104071832581.0;
+ if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
+ return IEEE_754_DOUBLE_BE;
+ if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
+ return IEEE_754_DOUBLE_LE;
+ }
+ return UNKNOWN_FORMAT;
+
+ /* Integers */
+ case 'h':
+ intsize = sizeof(short);
+ is_signed = 1;
+ break;
+ case 'H':
+ intsize = sizeof(short);
+ is_signed = 0;
+ break;
+ case 'i':
+ intsize = sizeof(int);
+ is_signed = 1;
+ break;
+ case 'I':
+ intsize = sizeof(int);
+ is_signed = 0;
+ break;
+ case 'l':
+ intsize = sizeof(long);
+ is_signed = 1;
+ break;
+ case 'L':
+ intsize = sizeof(long);
+ is_signed = 0;
+ break;
+ default:
+ return UNKNOWN_FORMAT;
+ }
+ switch (intsize) {
+ case 2:
+ return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
+ case 4:
+ return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
+ case 8:
+ return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
+ default:
+ return UNKNOWN_FORMAT;
+ }
}
/* Forward declaration. */
@@ -1619,38 +1619,38 @@ static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
* Unicode character value, like 'i' or 'f' for example, representing an array
* type code. The items argument is a bytes or a list object from which
* contains the initial value of the array.
- *
+ *
* On success, this functions returns the array object created. Otherwise,
* NULL is returned to indicate a failure.
*/
static PyObject *
make_array(PyTypeObject *arraytype, int typecode, PyObject *items)
{
- PyObject *new_args;
- PyObject *array_obj;
- PyObject *typecode_obj;
- Py_UNICODE typecode_str[1] = {typecode};
+ PyObject *new_args;
+ PyObject *array_obj;
+ PyObject *typecode_obj;
+ Py_UNICODE typecode_str[1] = {typecode};
- assert(arraytype != NULL);
- assert(items != NULL);
+ assert(arraytype != NULL);
+ assert(items != NULL);
- typecode_obj = PyUnicode_FromUnicode(typecode_str, 1);
- if (typecode_obj == NULL)
- return NULL;
+ typecode_obj = PyUnicode_FromUnicode(typecode_str, 1);
+ if (typecode_obj == NULL)
+ return NULL;
- new_args = PyTuple_New(2);
- if (new_args == NULL)
- return NULL;
- Py_INCREF(items);
- PyTuple_SET_ITEM(new_args, 0, typecode_obj);
- PyTuple_SET_ITEM(new_args, 1, items);
+ new_args = PyTuple_New(2);
+ if (new_args == NULL)
+ return NULL;
+ Py_INCREF(items);
+ PyTuple_SET_ITEM(new_args, 0, typecode_obj);
+ PyTuple_SET_ITEM(new_args, 1, items);
- array_obj = array_new(arraytype, new_args, NULL);
- Py_DECREF(new_args);
- if (array_obj == NULL)
- return NULL;
+ array_obj = array_new(arraytype, new_args, NULL);
+ Py_DECREF(new_args);
+ if (array_obj == NULL)
+ return NULL;
- return array_obj;
+ return array_obj;
}
/*
@@ -1660,283 +1660,283 @@ make_array(PyTypeObject *arraytype, int typecode, PyObject *items)
static PyObject *
array_reconstructor(PyObject *self, PyObject *args)
{
- PyTypeObject *arraytype;
- PyObject *items;
- PyObject *converted_items;
- PyObject *result;
- int typecode;
- enum machine_format_code mformat_code;
- struct arraydescr *descr;
-
- if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor",
- &arraytype, &typecode, &mformat_code, &items))
- return NULL;
-
- if (!PyType_Check(arraytype)) {
- PyErr_Format(PyExc_TypeError,
- "first argument must a type object, not %.200s",
- Py_TYPE(arraytype)->tp_name);
- return NULL;
- }
- if (!PyType_IsSubtype(arraytype, &Arraytype)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s is not a subtype of %.200s",
- arraytype->tp_name, Arraytype.tp_name);
- return NULL;
- }
- for (descr = descriptors; descr->typecode != '\0'; descr++) {
- if (descr->typecode == typecode)
- break;
- }
- if (descr->typecode == '\0') {
- PyErr_SetString(PyExc_ValueError,
- "second argument must be a valid type code");
- return NULL;
- }
- if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
- mformat_code > MACHINE_FORMAT_CODE_MAX) {
- PyErr_SetString(PyExc_ValueError,
- "third argument must be a valid machine format code.");
- return NULL;
- }
- if (!PyBytes_Check(items)) {
- PyErr_Format(PyExc_TypeError,
- "fourth argument should be bytes, not %.200s",
- Py_TYPE(items)->tp_name);
- return NULL;
- }
-
- /* Fast path: No decoding has to be done. */
- if (mformat_code == typecode_to_mformat_code(typecode) ||
- mformat_code == UNKNOWN_FORMAT) {
- return make_array(arraytype, typecode, items);
- }
-
- /* Slow path: Decode the byte string according to the given machine
- * format code. This occurs when the computer unpickling the array
- * object is architecturally different from the one that pickled the
- * array.
- */
- if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
- PyErr_SetString(PyExc_ValueError,
- "string length not a multiple of item size");
- return NULL;
- }
- switch (mformat_code) {
- case IEEE_754_FLOAT_LE:
- case IEEE_754_FLOAT_BE: {
- int i;
- int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
- Py_ssize_t itemcount = Py_SIZE(items) / 4;
- const unsigned char *memstr =
- (unsigned char *)PyBytes_AS_STRING(items);
-
- converted_items = PyList_New(itemcount);
- if (converted_items == NULL)
- return NULL;
- for (i = 0; i < itemcount; i++) {
- PyObject *pyfloat = PyFloat_FromDouble(
- _PyFloat_Unpack4(&memstr[i * 4], le));
- if (pyfloat == NULL) {
- Py_DECREF(converted_items);
- return NULL;
- }
- PyList_SET_ITEM(converted_items, i, pyfloat);
- }
- break;
- }
- case IEEE_754_DOUBLE_LE:
- case IEEE_754_DOUBLE_BE: {
- int i;
- int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
- Py_ssize_t itemcount = Py_SIZE(items) / 8;
- const unsigned char *memstr =
- (unsigned char *)PyBytes_AS_STRING(items);
-
- converted_items = PyList_New(itemcount);
- if (converted_items == NULL)
- return NULL;
- for (i = 0; i < itemcount; i++) {
- PyObject *pyfloat = PyFloat_FromDouble(
- _PyFloat_Unpack8(&memstr[i * 8], le));
- if (pyfloat == NULL) {
- Py_DECREF(converted_items);
- return NULL;
- }
- PyList_SET_ITEM(converted_items, i, pyfloat);
- }
- break;
- }
- case UTF16_LE:
- case UTF16_BE: {
- int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
- converted_items = PyUnicode_DecodeUTF16(
- PyBytes_AS_STRING(items), Py_SIZE(items),
- "strict", &byteorder);
- if (converted_items == NULL)
- return NULL;
- break;
- }
- case UTF32_LE:
- case UTF32_BE: {
- int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
- converted_items = PyUnicode_DecodeUTF32(
- PyBytes_AS_STRING(items), Py_SIZE(items),
- "strict", &byteorder);
- if (converted_items == NULL)
- return NULL;
- break;
- }
-
- case UNSIGNED_INT8:
- case SIGNED_INT8:
- case UNSIGNED_INT16_LE:
- case UNSIGNED_INT16_BE:
- case SIGNED_INT16_LE:
- case SIGNED_INT16_BE:
- case UNSIGNED_INT32_LE:
- case UNSIGNED_INT32_BE:
- case SIGNED_INT32_LE:
- case SIGNED_INT32_BE:
- case UNSIGNED_INT64_LE:
- case UNSIGNED_INT64_BE:
- case SIGNED_INT64_LE:
- case SIGNED_INT64_BE: {
- int i;
- const struct mformatdescr mf_descr =
- mformat_descriptors[mformat_code];
- Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
- const unsigned char *memstr =
- (unsigned char *)PyBytes_AS_STRING(items);
- struct arraydescr *descr;
-
- /* If possible, try to pack array's items using a data type
- * that fits better. This may result in an array with narrower
- * or wider elements.
- *
- * For example, if a 32-bit machine pickles a L-code array of
- * unsigned longs, then the array will be unpickled by 64-bit
- * machine as an I-code array of unsigned ints.
- *
- * XXX: Is it possible to write a unit test for this?
- */
- for (descr = descriptors; descr->typecode != '\0'; descr++) {
- if (descr->is_integer_type &&
- descr->itemsize == mf_descr.size &&
- descr->is_signed == mf_descr.is_signed)
- typecode = descr->typecode;
- }
-
- converted_items = PyList_New(itemcount);
- if (converted_items == NULL)
- return NULL;
- for (i = 0; i < itemcount; i++) {
- PyObject *pylong;
-
- pylong = _PyLong_FromByteArray(
- &memstr[i * mf_descr.size],
- mf_descr.size,
- !mf_descr.is_big_endian,
- mf_descr.is_signed);
- if (pylong == NULL) {
- Py_DECREF(converted_items);
- return NULL;
- }
- PyList_SET_ITEM(converted_items, i, pylong);
- }
- break;
- }
- case UNKNOWN_FORMAT:
- /* Impossible, but needed to shut up GCC about the unhandled
- * enumeration value.
- */
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- result = make_array(arraytype, typecode, converted_items);
- Py_DECREF(converted_items);
- return result;
+ PyTypeObject *arraytype;
+ PyObject *items;
+ PyObject *converted_items;
+ PyObject *result;
+ int typecode;
+ enum machine_format_code mformat_code;
+ struct arraydescr *descr;
+
+ if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor",
+ &arraytype, &typecode, &mformat_code, &items))
+ return NULL;
+
+ if (!PyType_Check(arraytype)) {
+ PyErr_Format(PyExc_TypeError,
+ "first argument must a type object, not %.200s",
+ Py_TYPE(arraytype)->tp_name);
+ return NULL;
+ }
+ if (!PyType_IsSubtype(arraytype, &Arraytype)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s is not a subtype of %.200s",
+ arraytype->tp_name, Arraytype.tp_name);
+ return NULL;
+ }
+ for (descr = descriptors; descr->typecode != '\0'; descr++) {
+ if (descr->typecode == typecode)
+ break;
+ }
+ if (descr->typecode == '\0') {
+ PyErr_SetString(PyExc_ValueError,
+ "second argument must be a valid type code");
+ return NULL;
+ }
+ if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
+ mformat_code > MACHINE_FORMAT_CODE_MAX) {
+ PyErr_SetString(PyExc_ValueError,
+ "third argument must be a valid machine format code.");
+ return NULL;
+ }
+ if (!PyBytes_Check(items)) {
+ PyErr_Format(PyExc_TypeError,
+ "fourth argument should be bytes, not %.200s",
+ Py_TYPE(items)->tp_name);
+ return NULL;
+ }
+
+ /* Fast path: No decoding has to be done. */
+ if (mformat_code == typecode_to_mformat_code(typecode) ||
+ mformat_code == UNKNOWN_FORMAT) {
+ return make_array(arraytype, typecode, items);
+ }
+
+ /* Slow path: Decode the byte string according to the given machine
+ * format code. This occurs when the computer unpickling the array
+ * object is architecturally different from the one that pickled the
+ * array.
+ */
+ if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "string length not a multiple of item size");
+ return NULL;
+ }
+ switch (mformat_code) {
+ case IEEE_754_FLOAT_LE:
+ case IEEE_754_FLOAT_BE: {
+ int i;
+ int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
+ Py_ssize_t itemcount = Py_SIZE(items) / 4;
+ const unsigned char *memstr =
+ (unsigned char *)PyBytes_AS_STRING(items);
+
+ converted_items = PyList_New(itemcount);
+ if (converted_items == NULL)
+ return NULL;
+ for (i = 0; i < itemcount; i++) {
+ PyObject *pyfloat = PyFloat_FromDouble(
+ _PyFloat_Unpack4(&memstr[i * 4], le));
+ if (pyfloat == NULL) {
+ Py_DECREF(converted_items);
+ return NULL;
+ }
+ PyList_SET_ITEM(converted_items, i, pyfloat);
+ }
+ break;
+ }
+ case IEEE_754_DOUBLE_LE:
+ case IEEE_754_DOUBLE_BE: {
+ int i;
+ int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
+ Py_ssize_t itemcount = Py_SIZE(items) / 8;
+ const unsigned char *memstr =
+ (unsigned char *)PyBytes_AS_STRING(items);
+
+ converted_items = PyList_New(itemcount);
+ if (converted_items == NULL)
+ return NULL;
+ for (i = 0; i < itemcount; i++) {
+ PyObject *pyfloat = PyFloat_FromDouble(
+ _PyFloat_Unpack8(&memstr[i * 8], le));
+ if (pyfloat == NULL) {
+ Py_DECREF(converted_items);
+ return NULL;
+ }
+ PyList_SET_ITEM(converted_items, i, pyfloat);
+ }
+ break;
+ }
+ case UTF16_LE:
+ case UTF16_BE: {
+ int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
+ converted_items = PyUnicode_DecodeUTF16(
+ PyBytes_AS_STRING(items), Py_SIZE(items),
+ "strict", &byteorder);
+ if (converted_items == NULL)
+ return NULL;
+ break;
+ }
+ case UTF32_LE:
+ case UTF32_BE: {
+ int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
+ converted_items = PyUnicode_DecodeUTF32(
+ PyBytes_AS_STRING(items), Py_SIZE(items),
+ "strict", &byteorder);
+ if (converted_items == NULL)
+ return NULL;
+ break;
+ }
+
+ case UNSIGNED_INT8:
+ case SIGNED_INT8:
+ case UNSIGNED_INT16_LE:
+ case UNSIGNED_INT16_BE:
+ case SIGNED_INT16_LE:
+ case SIGNED_INT16_BE:
+ case UNSIGNED_INT32_LE:
+ case UNSIGNED_INT32_BE:
+ case SIGNED_INT32_LE:
+ case SIGNED_INT32_BE:
+ case UNSIGNED_INT64_LE:
+ case UNSIGNED_INT64_BE:
+ case SIGNED_INT64_LE:
+ case SIGNED_INT64_BE: {
+ int i;
+ const struct mformatdescr mf_descr =
+ mformat_descriptors[mformat_code];
+ Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
+ const unsigned char *memstr =
+ (unsigned char *)PyBytes_AS_STRING(items);
+ struct arraydescr *descr;
+
+ /* If possible, try to pack array's items using a data type
+ * that fits better. This may result in an array with narrower
+ * or wider elements.
+ *
+ * For example, if a 32-bit machine pickles a L-code array of
+ * unsigned longs, then the array will be unpickled by 64-bit
+ * machine as an I-code array of unsigned ints.
+ *
+ * XXX: Is it possible to write a unit test for this?
+ */
+ for (descr = descriptors; descr->typecode != '\0'; descr++) {
+ if (descr->is_integer_type &&
+ descr->itemsize == mf_descr.size &&
+ descr->is_signed == mf_descr.is_signed)
+ typecode = descr->typecode;
+ }
+
+ converted_items = PyList_New(itemcount);
+ if (converted_items == NULL)
+ return NULL;
+ for (i = 0; i < itemcount; i++) {
+ PyObject *pylong;
+
+ pylong = _PyLong_FromByteArray(
+ &memstr[i * mf_descr.size],
+ mf_descr.size,
+ !mf_descr.is_big_endian,
+ mf_descr.is_signed);
+ if (pylong == NULL) {
+ Py_DECREF(converted_items);
+ return NULL;
+ }
+ PyList_SET_ITEM(converted_items, i, pylong);
+ }
+ break;
+ }
+ case UNKNOWN_FORMAT:
+ /* Impossible, but needed to shut up GCC about the unhandled
+ * enumeration value.
+ */
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ result = make_array(arraytype, typecode, converted_items);
+ Py_DECREF(converted_items);
+ return result;
}
static PyObject *
array_reduce_ex(arrayobject *array, PyObject *value)
{
- PyObject *dict;
- PyObject *result;
- PyObject *array_str;
- int typecode = array->ob_descr->typecode;
- int mformat_code;
- static PyObject *array_reconstructor = NULL;
- long protocol;
-
- if (array_reconstructor == NULL) {
- PyObject *array_module = PyImport_ImportModule("array");
- if (array_module == NULL)
- return NULL;
- array_reconstructor = PyObject_GetAttrString(
- array_module,
- "_array_reconstructor");
- Py_DECREF(array_module);
- if (array_reconstructor == NULL)
- return NULL;
- }
-
- if (!PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "__reduce_ex__ argument should an integer");
- return NULL;
- }
- protocol = PyLong_AsLong(value);
- if (protocol == -1 && PyErr_Occurred())
- return NULL;
-
- dict = PyObject_GetAttrString((PyObject *)array, "__dict__");
- if (dict == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- dict = Py_None;
- Py_INCREF(dict);
- }
-
- mformat_code = typecode_to_mformat_code(typecode);
- if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
- /* Convert the array to a list if we got something weird
- * (e.g., non-IEEE floats), or we are pickling the array using
- * a Python 2.x compatible protocol.
- *
- * It is necessary to use a list representation for Python 2.x
- * compatible pickle protocol, since Python 2's str objects
- * are unpickled as unicode by Python 3. Thus it is impossible
- * to make arrays unpicklable by Python 3 by using their memory
- * representation, unless we resort to ugly hacks such as
- * coercing unicode objects to bytes in array_reconstructor.
- */
- PyObject *list;
- list = array_tolist(array, NULL);
- if (list == NULL) {
- Py_DECREF(dict);
- return NULL;
- }
- result = Py_BuildValue(
- "O(CO)O", Py_TYPE(array), typecode, list, dict);
- Py_DECREF(list);
- Py_DECREF(dict);
- return result;
- }
-
- array_str = array_tostring(array, NULL);
- if (array_str == NULL) {
- Py_DECREF(dict);
- return NULL;
- }
- result = Py_BuildValue(
- "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode,
- mformat_code, array_str, dict);
- Py_DECREF(dict);
- return result;
+ PyObject *dict;
+ PyObject *result;
+ PyObject *array_str;
+ int typecode = array->ob_descr->typecode;
+ int mformat_code;
+ static PyObject *array_reconstructor = NULL;
+ long protocol;
+
+ if (array_reconstructor == NULL) {
+ PyObject *array_module = PyImport_ImportModule("array");
+ if (array_module == NULL)
+ return NULL;
+ array_reconstructor = PyObject_GetAttrString(
+ array_module,
+ "_array_reconstructor");
+ Py_DECREF(array_module);
+ if (array_reconstructor == NULL)
+ return NULL;
+ }
+
+ if (!PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__reduce_ex__ argument should an integer");
+ return NULL;
+ }
+ protocol = PyLong_AsLong(value);
+ if (protocol == -1 && PyErr_Occurred())
+ return NULL;
+
+ dict = PyObject_GetAttrString((PyObject *)array, "__dict__");
+ if (dict == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ dict = Py_None;
+ Py_INCREF(dict);
+ }
+
+ mformat_code = typecode_to_mformat_code(typecode);
+ if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
+ /* Convert the array to a list if we got something weird
+ * (e.g., non-IEEE floats), or we are pickling the array using
+ * a Python 2.x compatible protocol.
+ *
+ * It is necessary to use a list representation for Python 2.x
+ * compatible pickle protocol, since Python 2's str objects
+ * are unpickled as unicode by Python 3. Thus it is impossible
+ * to make arrays unpicklable by Python 3 by using their memory
+ * representation, unless we resort to ugly hacks such as
+ * coercing unicode objects to bytes in array_reconstructor.
+ */
+ PyObject *list;
+ list = array_tolist(array, NULL);
+ if (list == NULL) {
+ Py_DECREF(dict);
+ return NULL;
+ }
+ result = Py_BuildValue(
+ "O(CO)O", Py_TYPE(array), typecode, list, dict);
+ Py_DECREF(list);
+ Py_DECREF(dict);
+ return result;
+ }
+
+ array_str = array_tostring(array, NULL);
+ if (array_str == NULL) {
+ Py_DECREF(dict);
+ return NULL;
+ }
+ result = Py_BuildValue(
+ "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode,
+ mformat_code, array_str, dict);
+ Py_DECREF(dict);
+ return result;
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
@@ -1944,313 +1944,313 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyObject *
array_get_typecode(arrayobject *a, void *closure)
{
- char tc = a->ob_descr->typecode;
- return PyUnicode_FromStringAndSize(&tc, 1);
+ char tc = a->ob_descr->typecode;
+ return PyUnicode_FromStringAndSize(&tc, 1);
}
static PyObject *
array_get_itemsize(arrayobject *a, void *closure)
{
- return PyLong_FromLong((long)a->ob_descr->itemsize);
+ return PyLong_FromLong((long)a->ob_descr->itemsize);
}
static PyGetSetDef array_getsets [] = {
- {"typecode", (getter) array_get_typecode, NULL,
- "the typecode character used to create the array"},
- {"itemsize", (getter) array_get_itemsize, NULL,
- "the size, in bytes, of one array item"},
- {NULL}
+ {"typecode", (getter) array_get_typecode, NULL,
+ "the typecode character used to create the array"},
+ {"itemsize", (getter) array_get_itemsize, NULL,
+ "the size, in bytes, of one array item"},
+ {NULL}
};
static PyMethodDef array_methods[] = {
- {"append", (PyCFunction)array_append, METH_O,
- append_doc},
- {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
- buffer_info_doc},
- {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
- byteswap_doc},
- {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
- copy_doc},
- {"count", (PyCFunction)array_count, METH_O,
- count_doc},
- {"__deepcopy__",(PyCFunction)array_copy, METH_O,
- copy_doc},
- {"extend", (PyCFunction)array_extend, METH_O,
- extend_doc},
- {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
- fromfile_doc},
- {"fromlist", (PyCFunction)array_fromlist, METH_O,
- fromlist_doc},
- {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
- fromstring_doc},
- {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
- fromunicode_doc},
- {"index", (PyCFunction)array_index, METH_O,
- index_doc},
- {"insert", (PyCFunction)array_insert, METH_VARARGS,
- insert_doc},
- {"pop", (PyCFunction)array_pop, METH_VARARGS,
- pop_doc},
- {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O,
- reduce_doc},
- {"remove", (PyCFunction)array_remove, METH_O,
- remove_doc},
- {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
- reverse_doc},
-/* {"sort", (PyCFunction)array_sort, METH_VARARGS,
- sort_doc},*/
- {"tofile", (PyCFunction)array_tofile, METH_O,
- tofile_doc},
- {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
- tolist_doc},
- {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
- tostring_doc},
- {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
- tounicode_doc},
- {NULL, NULL} /* sentinel */
+ {"append", (PyCFunction)array_append, METH_O,
+ append_doc},
+ {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
+ buffer_info_doc},
+ {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
+ byteswap_doc},
+ {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
+ copy_doc},
+ {"count", (PyCFunction)array_count, METH_O,
+ count_doc},
+ {"__deepcopy__",(PyCFunction)array_copy, METH_O,
+ copy_doc},
+ {"extend", (PyCFunction)array_extend, METH_O,
+ extend_doc},
+ {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
+ fromfile_doc},
+ {"fromlist", (PyCFunction)array_fromlist, METH_O,
+ fromlist_doc},
+ {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
+ fromstring_doc},
+ {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
+ fromunicode_doc},
+ {"index", (PyCFunction)array_index, METH_O,
+ index_doc},
+ {"insert", (PyCFunction)array_insert, METH_VARARGS,
+ insert_doc},
+ {"pop", (PyCFunction)array_pop, METH_VARARGS,
+ pop_doc},
+ {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O,
+ reduce_doc},
+ {"remove", (PyCFunction)array_remove, METH_O,
+ remove_doc},
+ {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
+ reverse_doc},
+/* {"sort", (PyCFunction)array_sort, METH_VARARGS,
+ sort_doc},*/
+ {"tofile", (PyCFunction)array_tofile, METH_O,
+ tofile_doc},
+ {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
+ tolist_doc},
+ {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
+ tostring_doc},
+ {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
+ tounicode_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
array_repr(arrayobject *a)
{
- char typecode;
- PyObject *s, *v = NULL;
- Py_ssize_t len;
+ char typecode;
+ PyObject *s, *v = NULL;
+ Py_ssize_t len;
- len = Py_SIZE(a);
- typecode = a->ob_descr->typecode;
- if (len == 0) {
- return PyUnicode_FromFormat("array('%c')", typecode);
- }
- if ((typecode == 'u'))
- v = array_tounicode(a, NULL);
- else
- v = array_tolist(a, NULL);
+ len = Py_SIZE(a);
+ typecode = a->ob_descr->typecode;
+ if (len == 0) {
+ return PyUnicode_FromFormat("array('%c')", typecode);
+ }
+ if ((typecode == 'u'))
+ v = array_tounicode(a, NULL);
+ else
+ v = array_tolist(a, NULL);
- s = PyUnicode_FromFormat("array('%c', %R)", typecode, v);
- Py_DECREF(v);
- return s;
+ s = PyUnicode_FromFormat("array('%c', %R)", typecode, v);
+ Py_DECREF(v);
+ return s;
}
static PyObject*
array_subscr(arrayobject* self, PyObject* item)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i==-1 && PyErr_Occurred()) {
- return NULL;
- }
- if (i < 0)
- i += Py_SIZE(self);
- return array_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength, cur, i;
- PyObject* result;
- arrayobject* ar;
- int itemsize = self->ob_descr->itemsize;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
- &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return newarrayobject(&Arraytype, 0, self->ob_descr);
- }
- else if (step == 1) {
- PyObject *result = newarrayobject(&Arraytype,
- slicelength, self->ob_descr);
- if (result == NULL)
- return NULL;
- memcpy(((arrayobject *)result)->ob_item,
- self->ob_item + start * itemsize,
- slicelength * itemsize);
- return result;
- }
- else {
- result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
- if (!result) return NULL;
-
- ar = (arrayobject*)result;
-
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- memcpy(ar->ob_item + i*itemsize,
- self->ob_item + cur*itemsize,
- itemsize);
- }
-
- return result;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "array indices must be integers");
- return NULL;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i==-1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ if (i < 0)
+ i += Py_SIZE(self);
+ return array_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength, cur, i;
+ PyObject* result;
+ arrayobject* ar;
+ int itemsize = self->ob_descr->itemsize;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+ &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return newarrayobject(&Arraytype, 0, self->ob_descr);
+ }
+ else if (step == 1) {
+ PyObject *result = newarrayobject(&Arraytype,
+ slicelength, self->ob_descr);
+ if (result == NULL)
+ return NULL;
+ memcpy(((arrayobject *)result)->ob_item,
+ self->ob_item + start * itemsize,
+ slicelength * itemsize);
+ return result;
+ }
+ else {
+ result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
+ if (!result) return NULL;
+
+ ar = (arrayobject*)result;
+
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ memcpy(ar->ob_item + i*itemsize,
+ self->ob_item + cur*itemsize,
+ itemsize);
+ }
+
+ return result;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "array indices must be integers");
+ return NULL;
+ }
}
static int
array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
{
- Py_ssize_t start, stop, step, slicelength, needed;
- arrayobject* other;
- int itemsize;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += Py_SIZE(self);
- if (i < 0 || i >= Py_SIZE(self)) {
- PyErr_SetString(PyExc_IndexError,
- "array assignment index out of range");
- return -1;
- }
- if (value == NULL) {
- /* Fall through to slice assignment */
- start = i;
- stop = i + 1;
- step = 1;
- slicelength = 1;
- }
- else
- return (*self->ob_descr->setitem)(self, i, value);
- }
- else if (PySlice_Check(item)) {
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- Py_SIZE(self), &start, &stop,
- &step, &slicelength) < 0) {
- return -1;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "array indices must be integer");
- return -1;
- }
- if (value == NULL) {
- other = NULL;
- needed = 0;
- }
- else if (array_Check(value)) {
- other = (arrayobject *)value;
- needed = Py_SIZE(other);
- if (self == other) {
- /* Special case "self[i:j] = self" -- copy self first */
- int ret;
- value = array_slice(other, 0, needed);
- if (value == NULL)
- return -1;
- ret = array_ass_subscr(self, item, value);
- Py_DECREF(value);
- return ret;
- }
- if (other->ob_descr != self->ob_descr) {
- PyErr_BadArgument();
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "can only assign array (not \"%.200s\") to array slice",
- Py_TYPE(value)->tp_name);
- return -1;
- }
- itemsize = self->ob_descr->itemsize;
- /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
- if ((step > 0 && stop < start) ||
- (step < 0 && stop > start))
- stop = start;
-
- /* Issue #4509: If the array has exported buffers and the slice
- assignment would change the size of the array, fail early to make
- sure we don't modify it. */
- if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
- PyErr_SetString(PyExc_BufferError,
- "cannot resize an array that is exporting buffers");
- return -1;
- }
-
- if (step == 1) {
- if (slicelength > needed) {
- memmove(self->ob_item + (start + needed) * itemsize,
- self->ob_item + stop * itemsize,
- (Py_SIZE(self) - stop) * itemsize);
- if (array_resize(self, Py_SIZE(self) +
- needed - slicelength) < 0)
- return -1;
- }
- else if (slicelength < needed) {
- if (array_resize(self, Py_SIZE(self) +
- needed - slicelength) < 0)
- return -1;
- memmove(self->ob_item + (start + needed) * itemsize,
- self->ob_item + stop * itemsize,
- (Py_SIZE(self) - start - needed) * itemsize);
- }
- if (needed > 0)
- memcpy(self->ob_item + start * itemsize,
- other->ob_item, needed * itemsize);
- return 0;
- }
- else if (needed == 0) {
- /* Delete slice */
- size_t cur;
- Py_ssize_t i;
-
- if (step < 0) {
- stop = start + 1;
- start = stop + step * (slicelength - 1) - 1;
- step = -step;
- }
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- Py_ssize_t lim = step - 1;
-
- if (cur + step >= (size_t)Py_SIZE(self))
- lim = Py_SIZE(self) - cur - 1;
- memmove(self->ob_item + (cur - i) * itemsize,
- self->ob_item + (cur + 1) * itemsize,
- lim * itemsize);
- }
- cur = start + slicelength * step;
- if (cur < (size_t)Py_SIZE(self)) {
- memmove(self->ob_item + (cur-slicelength) * itemsize,
- self->ob_item + cur * itemsize,
- (Py_SIZE(self) - cur) * itemsize);
- }
- if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
- return -1;
- return 0;
- }
- else {
- Py_ssize_t cur, i;
-
- if (needed != slicelength) {
- PyErr_Format(PyExc_ValueError,
- "attempt to assign array of size %zd "
- "to extended slice of size %zd",
- needed, slicelength);
- return -1;
- }
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- memcpy(self->ob_item + cur * itemsize,
- other->ob_item + i * itemsize,
- itemsize);
- }
- return 0;
- }
+ Py_ssize_t start, stop, step, slicelength, needed;
+ arrayobject* other;
+ int itemsize;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += Py_SIZE(self);
+ if (i < 0 || i >= Py_SIZE(self)) {
+ PyErr_SetString(PyExc_IndexError,
+ "array assignment index out of range");
+ return -1;
+ }
+ if (value == NULL) {
+ /* Fall through to slice assignment */
+ start = i;
+ stop = i + 1;
+ step = 1;
+ slicelength = 1;
+ }
+ else
+ return (*self->ob_descr->setitem)(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ Py_SIZE(self), &start, &stop,
+ &step, &slicelength) < 0) {
+ return -1;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "array indices must be integer");
+ return -1;
+ }
+ if (value == NULL) {
+ other = NULL;
+ needed = 0;
+ }
+ else if (array_Check(value)) {
+ other = (arrayobject *)value;
+ needed = Py_SIZE(other);
+ if (self == other) {
+ /* Special case "self[i:j] = self" -- copy self first */
+ int ret;
+ value = array_slice(other, 0, needed);
+ if (value == NULL)
+ return -1;
+ ret = array_ass_subscr(self, item, value);
+ Py_DECREF(value);
+ return ret;
+ }
+ if (other->ob_descr != self->ob_descr) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign array (not \"%.200s\") to array slice",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ itemsize = self->ob_descr->itemsize;
+ /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
+ if ((step > 0 && stop < start) ||
+ (step < 0 && stop > start))
+ stop = start;
+
+ /* Issue #4509: If the array has exported buffers and the slice
+ assignment would change the size of the array, fail early to make
+ sure we don't modify it. */
+ if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
+ PyErr_SetString(PyExc_BufferError,
+ "cannot resize an array that is exporting buffers");
+ return -1;
+ }
+
+ if (step == 1) {
+ if (slicelength > needed) {
+ memmove(self->ob_item + (start + needed) * itemsize,
+ self->ob_item + stop * itemsize,
+ (Py_SIZE(self) - stop) * itemsize);
+ if (array_resize(self, Py_SIZE(self) +
+ needed - slicelength) < 0)
+ return -1;
+ }
+ else if (slicelength < needed) {
+ if (array_resize(self, Py_SIZE(self) +
+ needed - slicelength) < 0)
+ return -1;
+ memmove(self->ob_item + (start + needed) * itemsize,
+ self->ob_item + stop * itemsize,
+ (Py_SIZE(self) - start - needed) * itemsize);
+ }
+ if (needed > 0)
+ memcpy(self->ob_item + start * itemsize,
+ other->ob_item, needed * itemsize);
+ return 0;
+ }
+ else if (needed == 0) {
+ /* Delete slice */
+ size_t cur;
+ Py_ssize_t i;
+
+ if (step < 0) {
+ stop = start + 1;
+ start = stop + step * (slicelength - 1) - 1;
+ step = -step;
+ }
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ Py_ssize_t lim = step - 1;
+
+ if (cur + step >= (size_t)Py_SIZE(self))
+ lim = Py_SIZE(self) - cur - 1;
+ memmove(self->ob_item + (cur - i) * itemsize,
+ self->ob_item + (cur + 1) * itemsize,
+ lim * itemsize);
+ }
+ cur = start + slicelength * step;
+ if (cur < (size_t)Py_SIZE(self)) {
+ memmove(self->ob_item + (cur-slicelength) * itemsize,
+ self->ob_item + cur * itemsize,
+ (Py_SIZE(self) - cur) * itemsize);
+ }
+ if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
+ return -1;
+ return 0;
+ }
+ else {
+ Py_ssize_t cur, i;
+
+ if (needed != slicelength) {
+ PyErr_Format(PyExc_ValueError,
+ "attempt to assign array of size %zd "
+ "to extended slice of size %zd",
+ needed, slicelength);
+ return -1;
+ }
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ memcpy(self->ob_item + cur * itemsize,
+ other->ob_item + i * itemsize,
+ itemsize);
+ }
+ return 0;
+ }
}
static PyMappingMethods array_as_mapping = {
- (lenfunc)array_length,
- (binaryfunc)array_subscr,
- (objobjargproc)array_ass_subscr
+ (lenfunc)array_length,
+ (binaryfunc)array_subscr,
+ (objobjargproc)array_ass_subscr
};
static const void *emptybuf = "";
@@ -2259,173 +2259,173 @@ static const void *emptybuf = "";
static int
array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
{
- if (view==NULL) goto finish;
-
- view->buf = (void *)self->ob_item;
- view->obj = (PyObject*)self;
- Py_INCREF(self);
- if (view->buf == NULL)
- view->buf = (void *)emptybuf;
- view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
- view->readonly = 0;
- view->ndim = 1;
- view->itemsize = self->ob_descr->itemsize;
- view->suboffsets = NULL;
- view->shape = NULL;
- if ((flags & PyBUF_ND)==PyBUF_ND) {
- view->shape = &((Py_SIZE(self)));
- }
- view->strides = NULL;
- if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
- view->strides = &(view->itemsize);
- view->format = NULL;
- view->internal = NULL;
- if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
- view->format = self->ob_descr->formats;
+ if (view==NULL) goto finish;
+
+ view->buf = (void *)self->ob_item;
+ view->obj = (PyObject*)self;
+ Py_INCREF(self);
+ if (view->buf == NULL)
+ view->buf = (void *)emptybuf;
+ view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
+ view->readonly = 0;
+ view->ndim = 1;
+ view->itemsize = self->ob_descr->itemsize;
+ view->suboffsets = NULL;
+ view->shape = NULL;
+ if ((flags & PyBUF_ND)==PyBUF_ND) {
+ view->shape = &((Py_SIZE(self)));
+ }
+ view->strides = NULL;
+ if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
+ view->strides = &(view->itemsize);
+ view->format = NULL;
+ view->internal = NULL;
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
+ view->format = self->ob_descr->formats;
#ifdef Py_UNICODE_WIDE
- if (self->ob_descr->typecode == 'u') {
- view->format = "w";
- }
-#endif
+ if (self->ob_descr->typecode == 'u') {
+ view->format = "w";
}
+#endif
+ }
finish:
- self->ob_exports++;
- return 0;
+ self->ob_exports++;
+ return 0;
}
static void
array_buffer_relbuf(arrayobject *self, Py_buffer *view)
{
- self->ob_exports--;
+ self->ob_exports--;
}
static PySequenceMethods array_as_sequence = {
- (lenfunc)array_length, /*sq_length*/
- (binaryfunc)array_concat, /*sq_concat*/
- (ssizeargfunc)array_repeat, /*sq_repeat*/
- (ssizeargfunc)array_item, /*sq_item*/
- 0, /*sq_slice*/
- (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
- (objobjproc)array_contains, /*sq_contains*/
- (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
- (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
+ (lenfunc)array_length, /*sq_length*/
+ (binaryfunc)array_concat, /*sq_concat*/
+ (ssizeargfunc)array_repeat, /*sq_repeat*/
+ (ssizeargfunc)array_item, /*sq_item*/
+ 0, /*sq_slice*/
+ (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
+ 0, /*sq_ass_slice*/
+ (objobjproc)array_contains, /*sq_contains*/
+ (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
+ (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
};
static PyBufferProcs array_as_buffer = {
- (getbufferproc)array_buffer_getbuf,
- (releasebufferproc)array_buffer_relbuf
+ (getbufferproc)array_buffer_getbuf,
+ (releasebufferproc)array_buffer_relbuf
};
static PyObject *
array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- int c;
- PyObject *initial = NULL, *it = NULL;
- struct arraydescr *descr;
-
- if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
- return NULL;
-
- if (!(initial == NULL || PyList_Check(initial)
- || PyByteArray_Check(initial)
- || PyBytes_Check(initial)
- || PyTuple_Check(initial)
- || ((c=='u') && PyUnicode_Check(initial)))) {
- it = PyObject_GetIter(initial);
- if (it == NULL)
- return NULL;
- /* We set initial to NULL so that the subsequent code
- will create an empty array of the appropriate type
- and afterwards we can use array_iter_extend to populate
- the array.
- */
- initial = NULL;
- }
- for (descr = descriptors; descr->typecode != '\0'; descr++) {
- if (descr->typecode == c) {
- PyObject *a;
- Py_ssize_t len;
-
- if (initial == NULL || !(PyList_Check(initial)
- || PyTuple_Check(initial)))
- len = 0;
- else
- len = PySequence_Size(initial);
-
- a = newarrayobject(type, len, descr);
- if (a == NULL)
- return NULL;
-
- if (len > 0) {
- Py_ssize_t i;
- for (i = 0; i < len; i++) {
- PyObject *v =
- PySequence_GetItem(initial, i);
- if (v == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- if (setarrayitem(a, i, v) != 0) {
- Py_DECREF(v);
- Py_DECREF(a);
- return NULL;
- }
- Py_DECREF(v);
- }
- }
- else if (initial != NULL && (PyByteArray_Check(initial) ||
- PyBytes_Check(initial))) {
- PyObject *t_initial, *v;
- t_initial = PyTuple_Pack(1, initial);
- if (t_initial == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- v = array_fromstring((arrayobject *)a,
- t_initial);
- Py_DECREF(t_initial);
- if (v == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- Py_DECREF(v);
- }
- else if (initial != NULL && PyUnicode_Check(initial)) {
- Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial);
- if (n > 0) {
- arrayobject *self = (arrayobject *)a;
- char *item = self->ob_item;
- item = (char *)PyMem_Realloc(item, n);
- if (item == NULL) {
- PyErr_NoMemory();
- Py_DECREF(a);
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) = n / sizeof(Py_UNICODE);
- memcpy(item, PyUnicode_AS_DATA(initial), n);
- self->allocated = Py_SIZE(self);
- }
- }
- if (it != NULL) {
- if (array_iter_extend((arrayobject *)a, it) == -1) {
- Py_DECREF(it);
- Py_DECREF(a);
- return NULL;
- }
- Py_DECREF(it);
- }
- return a;
- }
- }
- PyErr_SetString(PyExc_ValueError,
- "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
- return NULL;
+ int c;
+ PyObject *initial = NULL, *it = NULL;
+ struct arraydescr *descr;
+
+ if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
+ return NULL;
+
+ if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
+ return NULL;
+
+ if (!(initial == NULL || PyList_Check(initial)
+ || PyByteArray_Check(initial)
+ || PyBytes_Check(initial)
+ || PyTuple_Check(initial)
+ || ((c=='u') && PyUnicode_Check(initial)))) {
+ it = PyObject_GetIter(initial);
+ if (it == NULL)
+ return NULL;
+ /* We set initial to NULL so that the subsequent code
+ will create an empty array of the appropriate type
+ and afterwards we can use array_iter_extend to populate
+ the array.
+ */
+ initial = NULL;
+ }
+ for (descr = descriptors; descr->typecode != '\0'; descr++) {
+ if (descr->typecode == c) {
+ PyObject *a;
+ Py_ssize_t len;
+
+ if (initial == NULL || !(PyList_Check(initial)
+ || PyTuple_Check(initial)))
+ len = 0;
+ else
+ len = PySequence_Size(initial);
+
+ a = newarrayobject(type, len, descr);
+ if (a == NULL)
+ return NULL;
+
+ if (len > 0) {
+ Py_ssize_t i;
+ for (i = 0; i < len; i++) {
+ PyObject *v =
+ PySequence_GetItem(initial, i);
+ if (v == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ if (setarrayitem(a, i, v) != 0) {
+ Py_DECREF(v);
+ Py_DECREF(a);
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ }
+ else if (initial != NULL && (PyByteArray_Check(initial) ||
+ PyBytes_Check(initial))) {
+ PyObject *t_initial, *v;
+ t_initial = PyTuple_Pack(1, initial);
+ if (t_initial == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ v = array_fromstring((arrayobject *)a,
+ t_initial);
+ Py_DECREF(t_initial);
+ if (v == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ else if (initial != NULL && PyUnicode_Check(initial)) {
+ Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial);
+ if (n > 0) {
+ arrayobject *self = (arrayobject *)a;
+ char *item = self->ob_item;
+ item = (char *)PyMem_Realloc(item, n);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ Py_DECREF(a);
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) = n / sizeof(Py_UNICODE);
+ memcpy(item, PyUnicode_AS_DATA(initial), n);
+ self->allocated = Py_SIZE(self);
+ }
+ }
+ if (it != NULL) {
+ if (array_iter_extend((arrayobject *)a, it) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(a);
+ return NULL;
+ }
+ Py_DECREF(it);
+ }
+ return a;
+ }
+ }
+ PyErr_SetString(PyExc_ValueError,
+ "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
+ return NULL;
}
@@ -2496,55 +2496,55 @@ itemsize -- the length in bytes of one array item\n\
static PyObject *array_iter(arrayobject *ao);
static PyTypeObject Arraytype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "array.array",
- sizeof(arrayobject),
- 0,
- (destructor)array_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)array_repr, /* tp_repr */
- 0, /* tp_as_number*/
- &array_as_sequence, /* tp_as_sequence*/
- &array_as_mapping, /* tp_as_mapping*/
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- &array_as_buffer, /* tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- arraytype_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- array_richcompare, /* tp_richcompare */
- offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
- (getiterfunc)array_iter, /* tp_iter */
- 0, /* tp_iternext */
- array_methods, /* tp_methods */
- 0, /* tp_members */
- array_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- array_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "array.array",
+ sizeof(arrayobject),
+ 0,
+ (destructor)array_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)array_repr, /* tp_repr */
+ 0, /* tp_as_number*/
+ &array_as_sequence, /* tp_as_sequence*/
+ &array_as_mapping, /* tp_as_mapping*/
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ &array_as_buffer, /* tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ arraytype_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ array_richcompare, /* tp_richcompare */
+ offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
+ (getiterfunc)array_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ array_methods, /* tp_methods */
+ 0, /* tp_members */
+ array_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ array_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
/*********************** Array Iterator **************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t index;
- arrayobject *ao;
- PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
+ PyObject_HEAD
+ Py_ssize_t index;
+ arrayobject *ao;
+ PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
} arrayiterobject;
static PyTypeObject PyArrayIter_Type;
@@ -2554,79 +2554,79 @@ static PyTypeObject PyArrayIter_Type;
static PyObject *
array_iter(arrayobject *ao)
{
- arrayiterobject *it;
+ arrayiterobject *it;
- if (!array_Check(ao)) {
- PyErr_BadInternalCall();
- return NULL;
- }
+ if (!array_Check(ao)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
- it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
- if (it == NULL)
- return NULL;
+ it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
+ if (it == NULL)
+ return NULL;
- Py_INCREF(ao);
- it->ao = ao;
- it->index = 0;
- it->getitem = ao->ob_descr->getitem;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ Py_INCREF(ao);
+ it->ao = ao;
+ it->index = 0;
+ it->getitem = ao->ob_descr->getitem;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static PyObject *
arrayiter_next(arrayiterobject *it)
{
- assert(PyArrayIter_Check(it));
- if (it->index < Py_SIZE(it->ao))
- return (*it->getitem)(it->ao, it->index++);
- return NULL;
+ assert(PyArrayIter_Check(it));
+ if (it->index < Py_SIZE(it->ao))
+ return (*it->getitem)(it->ao, it->index++);
+ return NULL;
}
static void
arrayiter_dealloc(arrayiterobject *it)
{
- PyObject_GC_UnTrack(it);
- Py_XDECREF(it->ao);
- PyObject_GC_Del(it);
+ PyObject_GC_UnTrack(it);
+ Py_XDECREF(it->ao);
+ PyObject_GC_Del(it);
}
static int
arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->ao);
- return 0;
+ Py_VISIT(it->ao);
+ return 0;
}
static PyTypeObject PyArrayIter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "arrayiterator", /* tp_name */
- sizeof(arrayiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arrayiter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)arrayiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)arrayiter_next, /* tp_iternext */
- 0, /* tp_methods */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "arrayiterator", /* tp_name */
+ sizeof(arrayiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arrayiter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)arrayiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)arrayiter_next, /* tp_iternext */
+ 0, /* tp_methods */
};
@@ -2640,54 +2640,54 @@ static PyMethodDef a_methods[] = {
};
static struct PyModuleDef arraymodule = {
- PyModuleDef_HEAD_INIT,
- "array",
- module_doc,
- -1,
- a_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "array",
+ module_doc,
+ -1,
+ a_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_array(void)
{
- PyObject *m;
- PyObject *typecodes;
- Py_ssize_t size = 0;
- register Py_UNICODE *p;
- struct arraydescr *descr;
-
- if (PyType_Ready(&Arraytype) < 0)
- return NULL;
- Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
- m = PyModule_Create(&arraymodule);
- if (m == NULL)
- return NULL;
-
- Py_INCREF((PyObject *)&Arraytype);
- PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
- Py_INCREF((PyObject *)&Arraytype);
- PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
-
- for (descr=descriptors; descr->typecode != '\0'; descr++) {
- size++;
- }
-
- typecodes = PyUnicode_FromStringAndSize(NULL, size);
- p = PyUnicode_AS_UNICODE(typecodes);
- for (descr = descriptors; descr->typecode != '\0'; descr++) {
- *p++ = (char)descr->typecode;
- }
-
- PyModule_AddObject(m, "typecodes", (PyObject *)typecodes);
-
- if (PyErr_Occurred()) {
- Py_DECREF(m);
- m = NULL;
- }
- return m;
+ PyObject *m;
+ PyObject *typecodes;
+ Py_ssize_t size = 0;
+ register Py_UNICODE *p;
+ struct arraydescr *descr;
+
+ if (PyType_Ready(&Arraytype) < 0)
+ return NULL;
+ Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
+ m = PyModule_Create(&arraymodule);
+ if (m == NULL)
+ return NULL;
+
+ Py_INCREF((PyObject *)&Arraytype);
+ PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
+ Py_INCREF((PyObject *)&Arraytype);
+ PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
+
+ for (descr=descriptors; descr->typecode != '\0'; descr++) {
+ size++;
+ }
+
+ typecodes = PyUnicode_FromStringAndSize(NULL, size);
+ p = PyUnicode_AS_UNICODE(typecodes);
+ for (descr = descriptors; descr->typecode != '\0'; descr++) {
+ *p++ = (char)descr->typecode;
+ }
+
+ PyModule_AddObject(m, "typecodes", (PyObject *)typecodes);
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(m);
+ m = NULL;
+ }
+ return m;
}
diff --git a/Modules/audioop.c b/Modules/audioop.c
index 0acf672..3985ca6 100644
--- a/Modules/audioop.c
+++ b/Modules/audioop.c
@@ -53,13 +53,13 @@ static PyInt16 seg_uend[8] = {0x3F, 0x7F, 0xFF, 0x1FF,
static PyInt16
search(PyInt16 val, PyInt16 *table, int size)
{
- int i;
+ int i;
- for (i = 0; i < size; i++) {
- if (val <= *table++)
- return (i);
- }
- return (size);
+ for (i = 0; i < size; i++) {
+ if (val <= *table++)
+ return (i);
+ }
+ return (size);
}
#define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc])
#define st_alaw2linear16(uc) (_st_alaw2linear16[uc])
@@ -83,7 +83,7 @@ static PyInt16 _st_ulaw2linear16[256] = {
-228, -212, -196, -180, -164, -148, -132,
-120, -112, -104, -96, -88, -80, -72,
-64, -56, -48, -40, -32, -24, -16,
- -8, 0, 32124, 31100, 30076, 29052, 28028,
+ -8, 0, 32124, 31100, 30076, 29052, 28028,
27004, 25980, 24956, 23932, 22908, 21884, 20860,
19836, 18812, 17788, 16764, 15996, 15484, 14972,
14460, 13948, 13436, 12924, 12412, 11900, 11388,
@@ -100,8 +100,8 @@ static PyInt16 _st_ulaw2linear16[256] = {
372, 356, 340, 324, 308, 292, 276,
260, 244, 228, 212, 196, 180, 164,
148, 132, 120, 112, 104, 96, 88,
- 80, 72, 64, 56, 48, 40, 32,
- 24, 16, 8, 0
+ 80, 72, 64, 56, 48, 40, 32,
+ 24, 16, 8, 0
};
/*
@@ -137,39 +137,39 @@ static PyInt16 _st_ulaw2linear16[256] = {
* John Wiley & Sons, pps 98-111 and 472-476.
*/
static unsigned char
-st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */
+st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */
{
- PyInt16 mask;
- PyInt16 seg;
- unsigned char uval;
-
- /* The original sox code does this in the calling function, not here */
- pcm_val = pcm_val >> 2;
-
- /* u-law inverts all bits */
- /* Get the sign and the magnitude of the value. */
- if (pcm_val < 0) {
- pcm_val = -pcm_val;
- mask = 0x7F;
- } else {
- mask = 0xFF;
- }
- if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
- pcm_val += (BIAS >> 2);
-
- /* Convert the scaled magnitude to segment number. */
- seg = search(pcm_val, seg_uend, 8);
-
- /*
- * Combine the sign, segment, quantization bits;
- * and complement the code word.
- */
- if (seg >= 8) /* out of range, return maximum value. */
- return (unsigned char) (0x7F ^ mask);
- else {
- uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
- return (uval ^ mask);
- }
+ PyInt16 mask;
+ PyInt16 seg;
+ unsigned char uval;
+
+ /* The original sox code does this in the calling function, not here */
+ pcm_val = pcm_val >> 2;
+
+ /* u-law inverts all bits */
+ /* Get the sign and the magnitude of the value. */
+ if (pcm_val < 0) {
+ pcm_val = -pcm_val;
+ mask = 0x7F;
+ } else {
+ mask = 0xFF;
+ }
+ if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
+ pcm_val += (BIAS >> 2);
+
+ /* Convert the scaled magnitude to segment number. */
+ seg = search(pcm_val, seg_uend, 8);
+
+ /*
+ * Combine the sign, segment, quantization bits;
+ * and complement the code word.
+ */
+ if (seg >= 8) /* out of range, return maximum value. */
+ return (unsigned char) (0x7F ^ mask);
+ else {
+ uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
+ return (uval ^ mask);
+ }
}
@@ -234,59 +234,59 @@ static PyInt16 _st_alaw2linear16[256] = {
* John Wiley & Sons, pps 98-111 and 472-476.
*/
static unsigned char
-st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */
+st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */
{
- PyInt16 mask;
- short seg;
- unsigned char aval;
-
- /* The original sox code does this in the calling function, not here */
- pcm_val = pcm_val >> 3;
-
- /* A-law using even bit inversion */
- if (pcm_val >= 0) {
- mask = 0xD5; /* sign (7th) bit = 1 */
- } else {
- mask = 0x55; /* sign bit = 0 */
- pcm_val = -pcm_val - 1;
- }
-
- /* Convert the scaled magnitude to segment number. */
- seg = search(pcm_val, seg_aend, 8);
-
- /* Combine the sign, segment, and quantization bits. */
-
- if (seg >= 8) /* out of range, return maximum value. */
- return (unsigned char) (0x7F ^ mask);
- else {
- aval = (unsigned char) seg << SEG_SHIFT;
- if (seg < 2)
- aval |= (pcm_val >> 1) & QUANT_MASK;
- else
- aval |= (pcm_val >> seg) & QUANT_MASK;
- return (aval ^ mask);
- }
+ PyInt16 mask;
+ short seg;
+ unsigned char aval;
+
+ /* The original sox code does this in the calling function, not here */
+ pcm_val = pcm_val >> 3;
+
+ /* A-law using even bit inversion */
+ if (pcm_val >= 0) {
+ mask = 0xD5; /* sign (7th) bit = 1 */
+ } else {
+ mask = 0x55; /* sign bit = 0 */
+ pcm_val = -pcm_val - 1;
+ }
+
+ /* Convert the scaled magnitude to segment number. */
+ seg = search(pcm_val, seg_aend, 8);
+
+ /* Combine the sign, segment, and quantization bits. */
+
+ if (seg >= 8) /* out of range, return maximum value. */
+ return (unsigned char) (0x7F ^ mask);
+ else {
+ aval = (unsigned char) seg << SEG_SHIFT;
+ if (seg < 2)
+ aval |= (pcm_val >> 1) & QUANT_MASK;
+ else
+ aval |= (pcm_val >> seg) & QUANT_MASK;
+ return (aval ^ mask);
+ }
}
/* End of code taken from sox */
/* Intel ADPCM step variation table */
static int indexTable[16] = {
- -1, -1, -1, -1, 2, 4, 6, 8,
- -1, -1, -1, -1, 2, 4, 6, 8,
+ -1, -1, -1, -1, 2, 4, 6, 8,
+ -1, -1, -1, -1, 2, 4, 6, 8,
};
static int stepsizeTable[89] = {
- 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
- 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
- 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
- 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
- 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
- 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
- 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
- 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
- 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
+ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
+ 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
+ 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
+ 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
+ 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
+ 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
+ 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
+ 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
+ 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
};
-
+
#define CHARP(cp, i) ((signed char *)(cp+i))
#define SHORTP(cp, i) ((short *)(cp+i))
#define LONGP(cp, i) ((Py_Int32 *)(cp+i))
@@ -298,137 +298,137 @@ static PyObject *AudioopError;
static PyObject *
audioop_getsample(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- if ( i < 0 || i >= len/size ) {
- PyErr_SetString(AudioopError, "Index out of range");
- return 0;
- }
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i*2);
- else if ( size == 4 ) val = (int)*LONGP(cp, i*4);
- return PyLong_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ if ( i < 0 || i >= len/size ) {
+ PyErr_SetString(AudioopError, "Index out of range");
+ return 0;
+ }
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i*2);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i*4);
+ return PyLong_FromLong(val);
}
static PyObject *
audioop_max(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- int max = 0;
-
- if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- if ( val < 0 ) val = (-val);
- if ( val > max ) max = val;
- }
- return PyLong_FromLong(max);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ int max = 0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ if ( val < 0 ) val = (-val);
+ if ( val > max ) max = val;
+ }
+ return PyLong_FromLong(max);
}
static PyObject *
audioop_minmax(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- int min = 0x7fffffff, max = -0x7fffffff;
-
- if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size))
- return NULL;
- if (size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return NULL;
- }
- for (i = 0; i < len; i += size) {
- if (size == 1) val = (int) *CHARP(cp, i);
- else if (size == 2) val = (int) *SHORTP(cp, i);
- else if (size == 4) val = (int) *LONGP(cp, i);
- if (val > max) max = val;
- if (val < min) min = val;
- }
- return Py_BuildValue("(ii)", min, max);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ int min = 0x7fffffff, max = -0x7fffffff;
+
+ if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size))
+ return NULL;
+ if (size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return NULL;
+ }
+ for (i = 0; i < len; i += size) {
+ if (size == 1) val = (int) *CHARP(cp, i);
+ else if (size == 2) val = (int) *SHORTP(cp, i);
+ else if (size == 4) val = (int) *LONGP(cp, i);
+ if (val > max) max = val;
+ if (val < min) min = val;
+ }
+ return Py_BuildValue("(ii)", min, max);
}
static PyObject *
audioop_avg(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- double avg = 0.0;
-
- if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- avg += val;
- }
- if ( len == 0 )
- val = 0;
- else
- val = (int)(avg / (double)(len/size));
- return PyLong_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ double avg = 0.0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ avg += val;
+ }
+ if ( len == 0 )
+ val = 0;
+ else
+ val = (int)(avg / (double)(len/size));
+ return PyLong_FromLong(val);
}
static PyObject *
audioop_rms(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- double sum_squares = 0.0;
-
- if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- sum_squares += (double)val*(double)val;
- }
- if ( len == 0 )
- val = 0;
- else
- val = (int)sqrt(sum_squares / (double)(len/size));
- return PyLong_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ double sum_squares = 0.0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ sum_squares += (double)val*(double)val;
+ }
+ if ( len == 0 )
+ val = 0;
+ else
+ val = (int)sqrt(sum_squares / (double)(len/size));
+ return PyLong_FromLong(val);
}
static double _sum2(short *a, short *b, int len)
{
- int i;
- double sum = 0.0;
+ int i;
+ double sum = 0.0;
- for( i=0; i<len; i++) {
- sum = sum + (double)a[i]*(double)b[i];
- }
- return sum;
+ for( i=0; i<len; i++) {
+ sum = sum + (double)a[i]*(double)b[i];
+ }
+ return sum;
}
/*
@@ -466,60 +466,60 @@ static double _sum2(short *a, short *b, int len)
static PyObject *
audioop_findfit(PyObject *self, PyObject *args)
{
- short *cp1, *cp2;
- int len1, len2;
- int j, best_j;
- double aj_m1, aj_lm1;
- double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor;
-
- /* Passing a short** for an 's' argument is correct only
- if the string contents is aligned for interpretation
- as short[]. Due to the definition of PyBytesObject,
- this is currently (Python 2.6) the case. */
- if ( !PyArg_ParseTuple(args, "s#s#:findfit",
- (char**)&cp1, &len1, (char**)&cp2, &len2) )
- return 0;
- if ( len1 & 1 || len2 & 1 ) {
- PyErr_SetString(AudioopError, "Strings should be even-sized");
- return 0;
- }
- len1 >>= 1;
- len2 >>= 1;
-
- if ( len1 < len2 ) {
- PyErr_SetString(AudioopError, "First sample should be longer");
- return 0;
- }
- sum_ri_2 = _sum2(cp2, cp2, len2);
- sum_aij_2 = _sum2(cp1, cp1, len2);
- sum_aij_ri = _sum2(cp1, cp2, len2);
-
- result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2;
-
- best_result = result;
- best_j = 0;
- j = 0;
-
- for ( j=1; j<=len1-len2; j++) {
- aj_m1 = (double)cp1[j-1];
- aj_lm1 = (double)cp1[j+len2-1];
-
- sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1;
- sum_aij_ri = _sum2(cp1+j, cp2, len2);
-
- result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri)
- / sum_aij_2;
-
- if ( result < best_result ) {
- best_result = result;
- best_j = j;
- }
-
- }
-
- factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2;
-
- return Py_BuildValue("(if)", best_j, factor);
+ short *cp1, *cp2;
+ int len1, len2;
+ int j, best_j;
+ double aj_m1, aj_lm1;
+ double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor;
+
+ /* Passing a short** for an 's' argument is correct only
+ if the string contents is aligned for interpretation
+ as short[]. Due to the definition of PyBytesObject,
+ this is currently (Python 2.6) the case. */
+ if ( !PyArg_ParseTuple(args, "s#s#:findfit",
+ (char**)&cp1, &len1, (char**)&cp2, &len2) )
+ return 0;
+ if ( len1 & 1 || len2 & 1 ) {
+ PyErr_SetString(AudioopError, "Strings should be even-sized");
+ return 0;
+ }
+ len1 >>= 1;
+ len2 >>= 1;
+
+ if ( len1 < len2 ) {
+ PyErr_SetString(AudioopError, "First sample should be longer");
+ return 0;
+ }
+ sum_ri_2 = _sum2(cp2, cp2, len2);
+ sum_aij_2 = _sum2(cp1, cp1, len2);
+ sum_aij_ri = _sum2(cp1, cp2, len2);
+
+ result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2;
+
+ best_result = result;
+ best_j = 0;
+ j = 0;
+
+ for ( j=1; j<=len1-len2; j++) {
+ aj_m1 = (double)cp1[j-1];
+ aj_lm1 = (double)cp1[j+len2-1];
+
+ sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1;
+ sum_aij_ri = _sum2(cp1+j, cp2, len2);
+
+ result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri)
+ / sum_aij_2;
+
+ if ( result < best_result ) {
+ best_result = result;
+ best_j = j;
+ }
+
+ }
+
+ factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2;
+
+ return Py_BuildValue("(if)", best_j, factor);
}
/*
@@ -529,28 +529,28 @@ audioop_findfit(PyObject *self, PyObject *args)
static PyObject *
audioop_findfactor(PyObject *self, PyObject *args)
{
- short *cp1, *cp2;
- int len1, len2;
- double sum_ri_2, sum_aij_ri, result;
-
- if ( !PyArg_ParseTuple(args, "s#s#:findfactor",
- (char**)&cp1, &len1, (char**)&cp2, &len2) )
- return 0;
- if ( len1 & 1 || len2 & 1 ) {
- PyErr_SetString(AudioopError, "Strings should be even-sized");
- return 0;
- }
- if ( len1 != len2 ) {
- PyErr_SetString(AudioopError, "Samples should be same size");
- return 0;
- }
- len2 >>= 1;
- sum_ri_2 = _sum2(cp2, cp2, len2);
- sum_aij_ri = _sum2(cp1, cp2, len2);
-
- result = sum_aij_ri / sum_ri_2;
-
- return PyFloat_FromDouble(result);
+ short *cp1, *cp2;
+ int len1, len2;
+ double sum_ri_2, sum_aij_ri, result;
+
+ if ( !PyArg_ParseTuple(args, "s#s#:findfactor",
+ (char**)&cp1, &len1, (char**)&cp2, &len2) )
+ return 0;
+ if ( len1 & 1 || len2 & 1 ) {
+ PyErr_SetString(AudioopError, "Strings should be even-sized");
+ return 0;
+ }
+ if ( len1 != len2 ) {
+ PyErr_SetString(AudioopError, "Samples should be same size");
+ return 0;
+ }
+ len2 >>= 1;
+ sum_ri_2 = _sum2(cp2, cp2, len2);
+ sum_aij_ri = _sum2(cp1, cp2, len2);
+
+ result = sum_aij_ri / sum_ri_2;
+
+ return PyFloat_FromDouble(result);
}
/*
@@ -560,1114 +560,1114 @@ audioop_findfactor(PyObject *self, PyObject *args)
static PyObject *
audioop_findmax(PyObject *self, PyObject *args)
{
- short *cp1;
- int len1, len2;
- int j, best_j;
- double aj_m1, aj_lm1;
- double result, best_result;
-
- if ( !PyArg_ParseTuple(args, "s#i:findmax",
- (char**)&cp1, &len1, &len2) )
- return 0;
- if ( len1 & 1 ) {
- PyErr_SetString(AudioopError, "Strings should be even-sized");
- return 0;
- }
- len1 >>= 1;
-
- if ( len2 < 0 || len1 < len2 ) {
- PyErr_SetString(AudioopError, "Input sample should be longer");
- return 0;
- }
+ short *cp1;
+ int len1, len2;
+ int j, best_j;
+ double aj_m1, aj_lm1;
+ double result, best_result;
- result = _sum2(cp1, cp1, len2);
+ if ( !PyArg_ParseTuple(args, "s#i:findmax",
+ (char**)&cp1, &len1, &len2) )
+ return 0;
+ if ( len1 & 1 ) {
+ PyErr_SetString(AudioopError, "Strings should be even-sized");
+ return 0;
+ }
+ len1 >>= 1;
- best_result = result;
- best_j = 0;
- j = 0;
+ if ( len2 < 0 || len1 < len2 ) {
+ PyErr_SetString(AudioopError, "Input sample should be longer");
+ return 0;
+ }
- for ( j=1; j<=len1-len2; j++) {
- aj_m1 = (double)cp1[j-1];
- aj_lm1 = (double)cp1[j+len2-1];
+ result = _sum2(cp1, cp1, len2);
- result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1;
+ best_result = result;
+ best_j = 0;
+ j = 0;
- if ( result > best_result ) {
- best_result = result;
- best_j = j;
- }
-
+ for ( j=1; j<=len1-len2; j++) {
+ aj_m1 = (double)cp1[j-1];
+ aj_lm1 = (double)cp1[j+len2-1];
+
+ result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1;
+
+ if ( result > best_result ) {
+ best_result = result;
+ best_j = j;
}
- return PyLong_FromLong(best_j);
+ }
+
+ return PyLong_FromLong(best_j);
}
static PyObject *
audioop_avgpp(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0, prevval = 0, prevextremevalid = 0,
- prevextreme = 0;
- int i;
- double avg = 0.0;
- int diff, prevdiff, extremediff, nextreme = 0;
-
- if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- /* Compute first delta value ahead. Also automatically makes us
- ** skip the first extreme value
- */
- if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
- else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
- else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
- if ( size == 1 ) val = (int)*CHARP(cp, size);
- else if ( size == 2 ) val = (int)*SHORTP(cp, size);
- else if ( size == 4 ) val = (int)*LONGP(cp, size);
- prevdiff = val - prevval;
-
- for ( i=size; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- diff = val - prevval;
- if ( diff*prevdiff < 0 ) {
- /* Derivative changed sign. Compute difference to last
- ** extreme value and remember.
- */
- if ( prevextremevalid ) {
- extremediff = prevval - prevextreme;
- if ( extremediff < 0 )
- extremediff = -extremediff;
- avg += extremediff;
- nextreme++;
- }
- prevextremevalid = 1;
- prevextreme = prevval;
- }
- prevval = val;
- if ( diff != 0 )
- prevdiff = diff;
- }
- if ( nextreme == 0 )
- val = 0;
- else
- val = (int)(avg / (double)nextreme);
- return PyLong_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0, prevval = 0, prevextremevalid = 0,
+ prevextreme = 0;
+ int i;
+ double avg = 0.0;
+ int diff, prevdiff, extremediff, nextreme = 0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ /* Compute first delta value ahead. Also automatically makes us
+ ** skip the first extreme value
+ */
+ if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
+ else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
+ else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
+ if ( size == 1 ) val = (int)*CHARP(cp, size);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, size);
+ else if ( size == 4 ) val = (int)*LONGP(cp, size);
+ prevdiff = val - prevval;
+
+ for ( i=size; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ diff = val - prevval;
+ if ( diff*prevdiff < 0 ) {
+ /* Derivative changed sign. Compute difference to last
+ ** extreme value and remember.
+ */
+ if ( prevextremevalid ) {
+ extremediff = prevval - prevextreme;
+ if ( extremediff < 0 )
+ extremediff = -extremediff;
+ avg += extremediff;
+ nextreme++;
+ }
+ prevextremevalid = 1;
+ prevextreme = prevval;
+ }
+ prevval = val;
+ if ( diff != 0 )
+ prevdiff = diff;
+ }
+ if ( nextreme == 0 )
+ val = 0;
+ else
+ val = (int)(avg / (double)nextreme);
+ return PyLong_FromLong(val);
}
static PyObject *
audioop_maxpp(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0, prevval = 0, prevextremevalid = 0,
- prevextreme = 0;
- int i;
- int max = 0;
- int diff, prevdiff, extremediff;
-
- if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- /* Compute first delta value ahead. Also automatically makes us
- ** skip the first extreme value
- */
- if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
- else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
- else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
- if ( size == 1 ) val = (int)*CHARP(cp, size);
- else if ( size == 2 ) val = (int)*SHORTP(cp, size);
- else if ( size == 4 ) val = (int)*LONGP(cp, size);
- prevdiff = val - prevval;
-
- for ( i=size; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- diff = val - prevval;
- if ( diff*prevdiff < 0 ) {
- /* Derivative changed sign. Compute difference to
- ** last extreme value and remember.
- */
- if ( prevextremevalid ) {
- extremediff = prevval - prevextreme;
- if ( extremediff < 0 )
- extremediff = -extremediff;
- if ( extremediff > max )
- max = extremediff;
- }
- prevextremevalid = 1;
- prevextreme = prevval;
- }
- prevval = val;
- if ( diff != 0 )
- prevdiff = diff;
- }
- return PyLong_FromLong(max);
+ signed char *cp;
+ int len, size, val = 0, prevval = 0, prevextremevalid = 0,
+ prevextreme = 0;
+ int i;
+ int max = 0;
+ int diff, prevdiff, extremediff;
+
+ if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ /* Compute first delta value ahead. Also automatically makes us
+ ** skip the first extreme value
+ */
+ if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
+ else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
+ else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
+ if ( size == 1 ) val = (int)*CHARP(cp, size);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, size);
+ else if ( size == 4 ) val = (int)*LONGP(cp, size);
+ prevdiff = val - prevval;
+
+ for ( i=size; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ diff = val - prevval;
+ if ( diff*prevdiff < 0 ) {
+ /* Derivative changed sign. Compute difference to
+ ** last extreme value and remember.
+ */
+ if ( prevextremevalid ) {
+ extremediff = prevval - prevextreme;
+ if ( extremediff < 0 )
+ extremediff = -extremediff;
+ if ( extremediff > max )
+ max = extremediff;
+ }
+ prevextremevalid = 1;
+ prevextreme = prevval;
+ }
+ prevval = val;
+ if ( diff != 0 )
+ prevdiff = diff;
+ }
+ return PyLong_FromLong(max);
}
static PyObject *
audioop_cross(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- int prevval, ncross;
-
- if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- ncross = -1;
- prevval = 17; /* Anything <> 0,1 */
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) >> 7;
- else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15;
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31;
- val = val & 1;
- if ( val != prevval ) ncross++;
- prevval = val;
- }
- return PyLong_FromLong(ncross);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ int prevval, ncross;
+
+ if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ ncross = -1;
+ prevval = 17; /* Anything <> 0,1 */
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) >> 7;
+ else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15;
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31;
+ val = val & 1;
+ if ( val != prevval ) ncross++;
+ prevval = val;
+ }
+ return PyLong_FromLong(ncross);
}
static PyObject *
audioop_mul(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, size, val = 0;
- double factor, fval, maxval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) )
- return 0;
-
- if ( size == 1 ) maxval = (double) 0x7f;
- else if ( size == 2 ) maxval = (double) 0x7fff;
- else if ( size == 4 ) maxval = (double) 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- fval = (double)val*factor;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val = (int)fval;
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)val;
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)val;
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)val;
- }
- return rv;
+ signed char *cp, *ncp;
+ int len, size, val = 0;
+ double factor, fval, maxval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) )
+ return 0;
+
+ if ( size == 1 ) maxval = (double) 0x7f;
+ else if ( size == 2 ) maxval = (double) 0x7fff;
+ else if ( size == 4 ) maxval = (double) 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ fval = (double)val*factor;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val = (int)fval;
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)val;
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)val;
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)val;
+ }
+ return rv;
}
static PyObject *
audioop_tomono(PyObject *self, PyObject *args)
{
- Py_buffer pcp;
- signed char *cp, *ncp;
- int len, size, val1 = 0, val2 = 0;
- double fac1, fac2, fval, maxval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s*idd:tomono",
- &pcp, &size, &fac1, &fac2 ) )
- return 0;
- cp = pcp.buf;
- len = pcp.len;
-
- if ( size == 1 ) maxval = (double) 0x7f;
- else if ( size == 2 ) maxval = (double) 0x7fff;
- else if ( size == 4 ) maxval = (double) 0x7fffffff;
- else {
- PyBuffer_Release(&pcp);
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len/2);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
-
- for ( i=0; i < len; i += size*2 ) {
- if ( size == 1 ) val1 = (int)*CHARP(cp, i);
- else if ( size == 2 ) val1 = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val1 = (int)*LONGP(cp, i);
- if ( size == 1 ) val2 = (int)*CHARP(cp, i+1);
- else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2);
- else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4);
- fval = (double)val1*fac1 + (double)val2*fac2;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val1 = (int)fval;
- if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1;
- else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1;
- else if ( size == 4 ) *LONGP(ncp, i/2)= (Py_Int32)val1;
- }
- PyBuffer_Release(&pcp);
- return rv;
+ Py_buffer pcp;
+ signed char *cp, *ncp;
+ int len, size, val1 = 0, val2 = 0;
+ double fac1, fac2, fval, maxval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s*idd:tomono",
+ &pcp, &size, &fac1, &fac2 ) )
+ return 0;
+ cp = pcp.buf;
+ len = pcp.len;
+
+ if ( size == 1 ) maxval = (double) 0x7f;
+ else if ( size == 2 ) maxval = (double) 0x7fff;
+ else if ( size == 4 ) maxval = (double) 0x7fffffff;
+ else {
+ PyBuffer_Release(&pcp);
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len/2);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+
+ for ( i=0; i < len; i += size*2 ) {
+ if ( size == 1 ) val1 = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val1 = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val1 = (int)*LONGP(cp, i);
+ if ( size == 1 ) val2 = (int)*CHARP(cp, i+1);
+ else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2);
+ else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4);
+ fval = (double)val1*fac1 + (double)val2*fac2;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val1 = (int)fval;
+ if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1;
+ else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1;
+ else if ( size == 4 ) *LONGP(ncp, i/2)= (Py_Int32)val1;
+ }
+ PyBuffer_Release(&pcp);
+ return rv;
}
static PyObject *
audioop_tostereo(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, new_len, size, val1, val2, val = 0;
- double fac1, fac2, fval, maxval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#idd:tostereo",
- &cp, &len, &size, &fac1, &fac2 ) )
- return 0;
-
- if ( size == 1 ) maxval = (double) 0x7f;
- else if ( size == 2 ) maxval = (double) 0x7fff;
- else if ( size == 4 ) maxval = (double) 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = len*2;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
-
- fval = (double)val*fac1;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val1 = (int)fval;
-
- fval = (double)val*fac2;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val2 = (int)fval;
-
- if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1;
- else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1;
- else if ( size == 4 ) *LONGP(ncp, i*2) = (Py_Int32)val1;
-
- if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2;
- else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2;
- else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2;
- }
- return rv;
+ signed char *cp, *ncp;
+ int len, new_len, size, val1, val2, val = 0;
+ double fac1, fac2, fval, maxval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#idd:tostereo",
+ &cp, &len, &size, &fac1, &fac2 ) )
+ return 0;
+
+ if ( size == 1 ) maxval = (double) 0x7f;
+ else if ( size == 2 ) maxval = (double) 0x7fff;
+ else if ( size == 4 ) maxval = (double) 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = len*2;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+
+ fval = (double)val*fac1;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val1 = (int)fval;
+
+ fval = (double)val*fac2;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val2 = (int)fval;
+
+ if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1;
+ else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1;
+ else if ( size == 4 ) *LONGP(ncp, i*2) = (Py_Int32)val1;
+
+ if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2;
+ else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2;
+ else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2;
+ }
+ return rv;
}
static PyObject *
audioop_add(PyObject *self, PyObject *args)
{
- signed char *cp1, *cp2, *ncp;
- int len1, len2, size, val1 = 0, val2 = 0, maxval, newval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#s#i:add",
- &cp1, &len1, &cp2, &len2, &size ) )
- return 0;
-
- if ( len1 != len2 ) {
- PyErr_SetString(AudioopError, "Lengths should be the same");
- return 0;
- }
-
- if ( size == 1 ) maxval = 0x7f;
- else if ( size == 2 ) maxval = 0x7fff;
- else if ( size == 4 ) maxval = 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len1);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
- for ( i=0; i < len1; i += size ) {
- if ( size == 1 ) val1 = (int)*CHARP(cp1, i);
- else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i);
- else if ( size == 4 ) val1 = (int)*LONGP(cp1, i);
-
- if ( size == 1 ) val2 = (int)*CHARP(cp2, i);
- else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i);
- else if ( size == 4 ) val2 = (int)*LONGP(cp2, i);
-
- newval = val1 + val2;
- /* truncate in case of overflow */
- if (newval > maxval) newval = maxval;
- else if (newval < -maxval) newval = -maxval;
- else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0)
- newval = val1 > 0 ? maxval : - maxval;
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval;
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval;
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval;
- }
- return rv;
+ signed char *cp1, *cp2, *ncp;
+ int len1, len2, size, val1 = 0, val2 = 0, maxval, newval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#s#i:add",
+ &cp1, &len1, &cp2, &len2, &size ) )
+ return 0;
+
+ if ( len1 != len2 ) {
+ PyErr_SetString(AudioopError, "Lengths should be the same");
+ return 0;
+ }
+
+ if ( size == 1 ) maxval = 0x7f;
+ else if ( size == 2 ) maxval = 0x7fff;
+ else if ( size == 4 ) maxval = 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len1);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+ for ( i=0; i < len1; i += size ) {
+ if ( size == 1 ) val1 = (int)*CHARP(cp1, i);
+ else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i);
+ else if ( size == 4 ) val1 = (int)*LONGP(cp1, i);
+
+ if ( size == 1 ) val2 = (int)*CHARP(cp2, i);
+ else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i);
+ else if ( size == 4 ) val2 = (int)*LONGP(cp2, i);
+
+ newval = val1 + val2;
+ /* truncate in case of overflow */
+ if (newval > maxval) newval = maxval;
+ else if (newval < -maxval) newval = -maxval;
+ else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0)
+ newval = val1 > 0 ? maxval : - maxval;
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval;
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval;
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval;
+ }
+ return rv;
}
static PyObject *
audioop_bias(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i;
- int bias;
-
- if ( !PyArg_ParseTuple(args, "s#ii:bias",
- &cp, &len, &size , &bias) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias);
- }
- return rv;
+ signed char *cp, *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i;
+ int bias;
+
+ if ( !PyArg_ParseTuple(args, "s#ii:bias",
+ &cp, &len, &size , &bias) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias);
+ }
+ return rv;
}
static PyObject *
audioop_reverse(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i, j;
-
- if ( !PyArg_ParseTuple(args, "s#i:reverse",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyBytes_AsString(rv);
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- j = len - i - size;
-
- if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
- else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val);
- else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i, j;
+
+ if ( !PyArg_ParseTuple(args, "s#i:reverse",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyBytes_AsString(rv);
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ j = len - i - size;
+
+ if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val);
+ else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static PyObject *
audioop_lin2lin(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, new_len, size, size2, val = 0;
- PyObject *rv;
- int i, j;
-
- if ( !PyArg_ParseTuple(args, "s#ii:lin2lin",
- &cp, &len, &size, &size2) )
- return 0;
-
- if ( (size != 1 && size != 2 && size != 4) ||
- (size2 != 1 && size2 != 2 && size2 != 4)) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = (len/size)*size2;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- rv = PyBytes_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyBytes_AsString(rv);
-
- for ( i=0, j=0; i < len; i += size, j += size2 ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
- else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val);
- else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, new_len, size, size2, val = 0;
+ PyObject *rv;
+ int i, j;
+
+ if ( !PyArg_ParseTuple(args, "s#ii:lin2lin",
+ &cp, &len, &size, &size2) )
+ return 0;
+
+ if ( (size != 1 && size != 2 && size != 4) ||
+ (size2 != 1 && size2 != 2 && size2 != 4)) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = (len/size)*size2;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ rv = PyBytes_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyBytes_AsString(rv);
+
+ for ( i=0, j=0; i < len; i += size, j += size2 ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
+ else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val);
+ else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static int
gcd(int a, int b)
{
- while (b > 0) {
- int tmp = a % b;
- a = b;
- b = tmp;
- }
- return a;
+ while (b > 0) {
+ int tmp = a % b;
+ a = b;
+ b = tmp;
+ }
+ return a;
}
static PyObject *
audioop_ratecv(PyObject *self, PyObject *args)
{
- char *cp, *ncp;
- int len, size, nchannels, inrate, outrate, weightA, weightB;
- int chan, d, *prev_i, *cur_i, cur_o;
- PyObject *state, *samps, *str, *rv = NULL;
- int bytes_per_frame;
- size_t alloc_size;
-
- weightA = 1;
- weightB = 0;
- if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size,
- &nchannels, &inrate, &outrate, &state,
- &weightA, &weightB))
- return NULL;
- if (size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return NULL;
- }
- if (nchannels < 1) {
- PyErr_SetString(AudioopError, "# of channels should be >= 1");
- return NULL;
- }
- bytes_per_frame = size * nchannels;
- if (bytes_per_frame / nchannels != size) {
- /* This overflow test is rigorously correct because
- both multiplicands are >= 1. Use the argument names
- from the docs for the error msg. */
- PyErr_SetString(PyExc_OverflowError,
- "width * nchannels too big for a C int");
- return NULL;
- }
- if (weightA < 1 || weightB < 0) {
- PyErr_SetString(AudioopError,
- "weightA should be >= 1, weightB should be >= 0");
- return NULL;
- }
- if (len % bytes_per_frame != 0) {
- PyErr_SetString(AudioopError, "not a whole number of frames");
- return NULL;
- }
- if (inrate <= 0 || outrate <= 0) {
- PyErr_SetString(AudioopError, "sampling rate not > 0");
- return NULL;
- }
- /* divide inrate and outrate by their greatest common divisor */
- d = gcd(inrate, outrate);
- inrate /= d;
- outrate /= d;
-
- alloc_size = sizeof(int) * (unsigned)nchannels;
- if (alloc_size < (unsigned)nchannels) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- prev_i = (int *) malloc(alloc_size);
- cur_i = (int *) malloc(alloc_size);
- if (prev_i == NULL || cur_i == NULL) {
- (void) PyErr_NoMemory();
+ char *cp, *ncp;
+ int len, size, nchannels, inrate, outrate, weightA, weightB;
+ int chan, d, *prev_i, *cur_i, cur_o;
+ PyObject *state, *samps, *str, *rv = NULL;
+ int bytes_per_frame;
+ size_t alloc_size;
+
+ weightA = 1;
+ weightB = 0;
+ if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size,
+ &nchannels, &inrate, &outrate, &state,
+ &weightA, &weightB))
+ return NULL;
+ if (size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return NULL;
+ }
+ if (nchannels < 1) {
+ PyErr_SetString(AudioopError, "# of channels should be >= 1");
+ return NULL;
+ }
+ bytes_per_frame = size * nchannels;
+ if (bytes_per_frame / nchannels != size) {
+ /* This overflow test is rigorously correct because
+ both multiplicands are >= 1. Use the argument names
+ from the docs for the error msg. */
+ PyErr_SetString(PyExc_OverflowError,
+ "width * nchannels too big for a C int");
+ return NULL;
+ }
+ if (weightA < 1 || weightB < 0) {
+ PyErr_SetString(AudioopError,
+ "weightA should be >= 1, weightB should be >= 0");
+ return NULL;
+ }
+ if (len % bytes_per_frame != 0) {
+ PyErr_SetString(AudioopError, "not a whole number of frames");
+ return NULL;
+ }
+ if (inrate <= 0 || outrate <= 0) {
+ PyErr_SetString(AudioopError, "sampling rate not > 0");
+ return NULL;
+ }
+ /* divide inrate and outrate by their greatest common divisor */
+ d = gcd(inrate, outrate);
+ inrate /= d;
+ outrate /= d;
+
+ alloc_size = sizeof(int) * (unsigned)nchannels;
+ if (alloc_size < (unsigned)nchannels) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ prev_i = (int *) malloc(alloc_size);
+ cur_i = (int *) malloc(alloc_size);
+ if (prev_i == NULL || cur_i == NULL) {
+ (void) PyErr_NoMemory();
+ goto exit;
+ }
+
+ len /= bytes_per_frame; /* # of frames */
+
+ if (state == Py_None) {
+ d = -outrate;
+ for (chan = 0; chan < nchannels; chan++)
+ prev_i[chan] = cur_i[chan] = 0;
+ }
+ else {
+ if (!PyArg_ParseTuple(state,
+ "iO!;audioop.ratecv: illegal state argument",
+ &d, &PyTuple_Type, &samps))
+ goto exit;
+ if (PyTuple_Size(samps) != nchannels) {
+ PyErr_SetString(AudioopError,
+ "illegal state argument");
+ goto exit;
+ }
+ for (chan = 0; chan < nchannels; chan++) {
+ if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan),
+ "ii:ratecv", &prev_i[chan],
+ &cur_i[chan]))
goto exit;
}
-
- len /= bytes_per_frame; /* # of frames */
-
- if (state == Py_None) {
- d = -outrate;
+ }
+
+ /* str <- Space for the output buffer. */
+ {
+ /* There are len input frames, so we need (mathematically)
+ ceiling(len*outrate/inrate) output frames, and each frame
+ requires bytes_per_frame bytes. Computing this
+ without spurious overflow is the challenge; we can
+ settle for a reasonable upper bound, though. */
+ int ceiling; /* the number of output frames */
+ int nbytes; /* the number of output bytes needed */
+ int q = len / inrate;
+ /* Now len = q * inrate + r exactly (with r = len % inrate),
+ and this is less than q * inrate + inrate = (q+1)*inrate.
+ So a reasonable upper bound on len*outrate/inrate is
+ ((q+1)*inrate)*outrate/inrate =
+ (q+1)*outrate.
+ */
+ ceiling = (q+1) * outrate;
+ nbytes = ceiling * bytes_per_frame;
+ /* See whether anything overflowed; if not, get the space. */
+ if (q+1 < 0 ||
+ ceiling / outrate != q+1 ||
+ nbytes / bytes_per_frame != ceiling)
+ str = NULL;
+ else
+ str = PyBytes_FromStringAndSize(NULL, nbytes);
+
+ if (str == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ goto exit;
+ }
+ }
+ ncp = PyBytes_AsString(str);
+
+ for (;;) {
+ while (d < 0) {
+ if (len == 0) {
+ samps = PyTuple_New(nchannels);
+ if (samps == NULL)
+ goto exit;
for (chan = 0; chan < nchannels; chan++)
- prev_i[chan] = cur_i[chan] = 0;
- }
- else {
- if (!PyArg_ParseTuple(state,
- "iO!;audioop.ratecv: illegal state argument",
- &d, &PyTuple_Type, &samps))
- goto exit;
- if (PyTuple_Size(samps) != nchannels) {
- PyErr_SetString(AudioopError,
- "illegal state argument");
- goto exit;
- }
- for (chan = 0; chan < nchannels; chan++) {
- if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan),
- "ii:ratecv", &prev_i[chan],
- &cur_i[chan]))
- goto exit;
- }
- }
-
- /* str <- Space for the output buffer. */
- {
- /* There are len input frames, so we need (mathematically)
- ceiling(len*outrate/inrate) output frames, and each frame
- requires bytes_per_frame bytes. Computing this
- without spurious overflow is the challenge; we can
- settle for a reasonable upper bound, though. */
- int ceiling; /* the number of output frames */
- int nbytes; /* the number of output bytes needed */
- int q = len / inrate;
- /* Now len = q * inrate + r exactly (with r = len % inrate),
- and this is less than q * inrate + inrate = (q+1)*inrate.
- So a reasonable upper bound on len*outrate/inrate is
- ((q+1)*inrate)*outrate/inrate =
- (q+1)*outrate.
- */
- ceiling = (q+1) * outrate;
- nbytes = ceiling * bytes_per_frame;
- /* See whether anything overflowed; if not, get the space. */
- if (q+1 < 0 ||
- ceiling / outrate != q+1 ||
- nbytes / bytes_per_frame != ceiling)
- str = NULL;
- else
- str = PyBytes_FromStringAndSize(NULL, nbytes);
-
- if (str == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- goto exit;
- }
- }
- ncp = PyBytes_AsString(str);
-
- for (;;) {
- while (d < 0) {
- if (len == 0) {
- samps = PyTuple_New(nchannels);
- if (samps == NULL)
- goto exit;
- for (chan = 0; chan < nchannels; chan++)
- PyTuple_SetItem(samps, chan,
- Py_BuildValue("(ii)",
- prev_i[chan],
- cur_i[chan]));
- if (PyErr_Occurred())
- goto exit;
- /* We have checked before that the length
- * of the string fits into int. */
- len = (int)(ncp - PyBytes_AsString(str));
- rv = PyBytes_FromStringAndSize
- (PyBytes_AsString(str), len);
- Py_DECREF(str);
- str = rv;
- if (str == NULL)
- goto exit;
- rv = Py_BuildValue("(O(iO))", str, d, samps);
- Py_DECREF(samps);
- Py_DECREF(str);
- goto exit; /* return rv */
- }
- for (chan = 0; chan < nchannels; chan++) {
- prev_i[chan] = cur_i[chan];
- if (size == 1)
- cur_i[chan] = ((int)*CHARP(cp, 0)) << 8;
- else if (size == 2)
- cur_i[chan] = (int)*SHORTP(cp, 0);
- else if (size == 4)
- cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16;
- cp += size;
- /* implements a simple digital filter */
- cur_i[chan] =
- (weightA * cur_i[chan] +
- weightB * prev_i[chan]) /
- (weightA + weightB);
- }
- len--;
- d += outrate;
- }
- while (d >= 0) {
- for (chan = 0; chan < nchannels; chan++) {
- cur_o = (prev_i[chan] * d +
- cur_i[chan] * (outrate - d)) /
- outrate;
- if (size == 1)
- *CHARP(ncp, 0) = (signed char)(cur_o >> 8);
- else if (size == 2)
- *SHORTP(ncp, 0) = (short)(cur_o);
- else if (size == 4)
- *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16);
- ncp += size;
- }
- d -= inrate;
- }
- }
+ PyTuple_SetItem(samps, chan,
+ Py_BuildValue("(ii)",
+ prev_i[chan],
+ cur_i[chan]));
+ if (PyErr_Occurred())
+ goto exit;
+ /* We have checked before that the length
+ * of the string fits into int. */
+ len = (int)(ncp - PyBytes_AsString(str));
+ rv = PyBytes_FromStringAndSize
+ (PyBytes_AsString(str), len);
+ Py_DECREF(str);
+ str = rv;
+ if (str == NULL)
+ goto exit;
+ rv = Py_BuildValue("(O(iO))", str, d, samps);
+ Py_DECREF(samps);
+ Py_DECREF(str);
+ goto exit; /* return rv */
+ }
+ for (chan = 0; chan < nchannels; chan++) {
+ prev_i[chan] = cur_i[chan];
+ if (size == 1)
+ cur_i[chan] = ((int)*CHARP(cp, 0)) << 8;
+ else if (size == 2)
+ cur_i[chan] = (int)*SHORTP(cp, 0);
+ else if (size == 4)
+ cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16;
+ cp += size;
+ /* implements a simple digital filter */
+ cur_i[chan] =
+ (weightA * cur_i[chan] +
+ weightB * prev_i[chan]) /
+ (weightA + weightB);
+ }
+ len--;
+ d += outrate;
+ }
+ while (d >= 0) {
+ for (chan = 0; chan < nchannels; chan++) {
+ cur_o = (prev_i[chan] * d +
+ cur_i[chan] * (outrate - d)) /
+ outrate;
+ if (size == 1)
+ *CHARP(ncp, 0) = (signed char)(cur_o >> 8);
+ else if (size == 2)
+ *SHORTP(ncp, 0) = (short)(cur_o);
+ else if (size == 4)
+ *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16);
+ ncp += size;
+ }
+ d -= inrate;
+ }
+ }
exit:
- if (prev_i != NULL)
- free(prev_i);
- if (cur_i != NULL)
- free(cur_i);
- return rv;
+ if (prev_i != NULL)
+ free(prev_i);
+ if (cur_i != NULL)
+ free(cur_i);
+ return rv;
}
static PyObject *
audioop_lin2ulaw(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw",
- &cp, &len, &size) )
- return 0 ;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len/size);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyBytes_AsString(rv);
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- *ncp++ = st_14linear2ulaw(val);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw",
+ &cp, &len, &size) )
+ return 0 ;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len/size);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyBytes_AsString(rv);
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ *ncp++ = st_14linear2ulaw(val);
+ }
+ return rv;
}
static PyObject *
audioop_ulaw2lin(PyObject *self, PyObject *args)
{
- unsigned char *cp;
- unsigned char cval;
- signed char *ncp;
- int len, new_len, size, val;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = len*size;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- rv = PyBytes_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
- for ( i=0; i < new_len; i += size ) {
- cval = *cp++;
- val = st_ulaw2linear16(cval);
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
- }
- return rv;
+ unsigned char *cp;
+ unsigned char cval;
+ signed char *ncp;
+ int len, new_len, size, val;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = len*size;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ rv = PyBytes_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+ for ( i=0; i < new_len; i += size ) {
+ cval = *cp++;
+ val = st_ulaw2linear16(cval);
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static PyObject *
audioop_lin2alaw(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:lin2alaw",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyBytes_FromStringAndSize(NULL, len/size);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyBytes_AsString(rv);
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- *ncp++ = st_linear2alaw(val);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:lin2alaw",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyBytes_FromStringAndSize(NULL, len/size);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyBytes_AsString(rv);
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ *ncp++ = st_linear2alaw(val);
+ }
+ return rv;
}
static PyObject *
audioop_alaw2lin(PyObject *self, PyObject *args)
{
- unsigned char *cp;
- unsigned char cval;
- signed char *ncp;
- int len, new_len, size, val;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:alaw2lin",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = len*size;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- rv = PyBytes_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(rv);
-
- for ( i=0; i < new_len; i += size ) {
- cval = *cp++;
- val = st_alaw2linear16(cval);
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
- }
- return rv;
+ unsigned char *cp;
+ unsigned char cval;
+ signed char *ncp;
+ int len, new_len, size, val;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:alaw2lin",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = len*size;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ rv = PyBytes_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(rv);
+
+ for ( i=0; i < new_len; i += size ) {
+ cval = *cp++;
+ val = st_alaw2linear16(cval);
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static PyObject *
audioop_lin2adpcm(PyObject *self, PyObject *args)
{
- signed char *cp;
- signed char *ncp;
- int len, size, val = 0, step, valpred, delta,
- index, sign, vpdiff, diff;
- PyObject *rv, *state, *str;
- int i, outputbuffer = 0, bufferstep;
-
- if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm",
- &cp, &len, &size, &state) )
- return 0;
-
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
+ signed char *cp;
+ signed char *ncp;
+ int len, size, val = 0, step, valpred, delta,
+ index, sign, vpdiff, diff;
+ PyObject *rv, *state, *str;
+ int i, outputbuffer = 0, bufferstep;
+
+ if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm",
+ &cp, &len, &size, &state) )
+ return 0;
+
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ str = PyBytes_FromStringAndSize(NULL, len/(size*2));
+ if ( str == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(str);
+
+ /* Decode state, should have (value, step) */
+ if ( state == Py_None ) {
+ /* First time, it seems. Set defaults */
+ valpred = 0;
+ step = 7;
+ index = 0;
+ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
+ return 0;
+
+ step = stepsizeTable[index];
+ bufferstep = 1;
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ /* Step 1 - compute difference with previous value */
+ diff = val - valpred;
+ sign = (diff < 0) ? 8 : 0;
+ if ( sign ) diff = (-diff);
+
+ /* Step 2 - Divide and clamp */
+ /* Note:
+ ** This code *approximately* computes:
+ ** delta = diff*4/step;
+ ** vpdiff = (delta+0.5)*step/4;
+ ** but in shift step bits are dropped. The net result of this
+ ** is that even if you have fast mul/div hardware you cannot
+ ** put it to good use since the fixup would be too expensive.
+ */
+ delta = 0;
+ vpdiff = (step >> 3);
+
+ if ( diff >= step ) {
+ delta = 4;
+ diff -= step;
+ vpdiff += step;
}
-
- str = PyBytes_FromStringAndSize(NULL, len/(size*2));
- if ( str == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(str);
-
- /* Decode state, should have (value, step) */
- if ( state == Py_None ) {
- /* First time, it seems. Set defaults */
- valpred = 0;
- step = 7;
- index = 0;
- } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
- return 0;
+ step >>= 1;
+ if ( diff >= step ) {
+ delta |= 2;
+ diff -= step;
+ vpdiff += step;
+ }
+ step >>= 1;
+ if ( diff >= step ) {
+ delta |= 1;
+ vpdiff += step;
+ }
+
+ /* Step 3 - Update previous value */
+ if ( sign )
+ valpred -= vpdiff;
+ else
+ valpred += vpdiff;
+ /* Step 4 - Clamp previous value to 16 bits */
+ if ( valpred > 32767 )
+ valpred = 32767;
+ else if ( valpred < -32768 )
+ valpred = -32768;
+
+ /* Step 5 - Assemble value, update index and step values */
+ delta |= sign;
+
+ index += indexTable[delta];
+ if ( index < 0 ) index = 0;
+ if ( index > 88 ) index = 88;
step = stepsizeTable[index];
- bufferstep = 1;
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- /* Step 1 - compute difference with previous value */
- diff = val - valpred;
- sign = (diff < 0) ? 8 : 0;
- if ( sign ) diff = (-diff);
-
- /* Step 2 - Divide and clamp */
- /* Note:
- ** This code *approximately* computes:
- ** delta = diff*4/step;
- ** vpdiff = (delta+0.5)*step/4;
- ** but in shift step bits are dropped. The net result of this
- ** is that even if you have fast mul/div hardware you cannot
- ** put it to good use since the fixup would be too expensive.
- */
- delta = 0;
- vpdiff = (step >> 3);
-
- if ( diff >= step ) {
- delta = 4;
- diff -= step;
- vpdiff += step;
- }
- step >>= 1;
- if ( diff >= step ) {
- delta |= 2;
- diff -= step;
- vpdiff += step;
- }
- step >>= 1;
- if ( diff >= step ) {
- delta |= 1;
- vpdiff += step;
- }
-
- /* Step 3 - Update previous value */
- if ( sign )
- valpred -= vpdiff;
- else
- valpred += vpdiff;
-
- /* Step 4 - Clamp previous value to 16 bits */
- if ( valpred > 32767 )
- valpred = 32767;
- else if ( valpred < -32768 )
- valpred = -32768;
-
- /* Step 5 - Assemble value, update index and step values */
- delta |= sign;
-
- index += indexTable[delta];
- if ( index < 0 ) index = 0;
- if ( index > 88 ) index = 88;
- step = stepsizeTable[index];
-
- /* Step 6 - Output value */
- if ( bufferstep ) {
- outputbuffer = (delta << 4) & 0xf0;
- } else {
- *ncp++ = (delta & 0x0f) | outputbuffer;
- }
- bufferstep = !bufferstep;
+
+ /* Step 6 - Output value */
+ if ( bufferstep ) {
+ outputbuffer = (delta << 4) & 0xf0;
+ } else {
+ *ncp++ = (delta & 0x0f) | outputbuffer;
}
- rv = Py_BuildValue("(O(ii))", str, valpred, index);
- Py_DECREF(str);
- return rv;
+ bufferstep = !bufferstep;
+ }
+ rv = Py_BuildValue("(O(ii))", str, valpred, index);
+ Py_DECREF(str);
+ return rv;
}
static PyObject *
audioop_adpcm2lin(PyObject *self, PyObject *args)
{
- signed char *cp;
- signed char *ncp;
- int len, new_len, size, valpred, step, delta, index, sign, vpdiff;
- PyObject *rv, *str, *state;
- int i, inputbuffer = 0, bufferstep;
-
- if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin",
- &cp, &len, &size, &state) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- /* Decode state, should have (value, step) */
- if ( state == Py_None ) {
- /* First time, it seems. Set defaults */
- valpred = 0;
- step = 7;
- index = 0;
- } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
- return 0;
-
- new_len = len*size*2;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
+ signed char *cp;
+ signed char *ncp;
+ int len, new_len, size, valpred, step, delta, index, sign, vpdiff;
+ PyObject *rv, *str, *state;
+ int i, inputbuffer = 0, bufferstep;
+
+ if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin",
+ &cp, &len, &size, &state) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ /* Decode state, should have (value, step) */
+ if ( state == Py_None ) {
+ /* First time, it seems. Set defaults */
+ valpred = 0;
+ step = 7;
+ index = 0;
+ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
+ return 0;
+
+ new_len = len*size*2;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ str = PyBytes_FromStringAndSize(NULL, new_len);
+ if ( str == 0 )
+ return 0;
+ ncp = (signed char *)PyBytes_AsString(str);
+
+ step = stepsizeTable[index];
+ bufferstep = 0;
+
+ for ( i=0; i < new_len; i += size ) {
+ /* Step 1 - get the delta value and compute next index */
+ if ( bufferstep ) {
+ delta = inputbuffer & 0xf;
+ } else {
+ inputbuffer = *cp++;
+ delta = (inputbuffer >> 4) & 0xf;
}
- str = PyBytes_FromStringAndSize(NULL, new_len);
- if ( str == 0 )
- return 0;
- ncp = (signed char *)PyBytes_AsString(str);
+ bufferstep = !bufferstep;
+
+ /* Step 2 - Find new index value (for later) */
+ index += indexTable[delta];
+ if ( index < 0 ) index = 0;
+ if ( index > 88 ) index = 88;
+
+ /* Step 3 - Separate sign and magnitude */
+ sign = delta & 8;
+ delta = delta & 7;
+
+ /* Step 4 - Compute difference and new predicted value */
+ /*
+ ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
+ ** in adpcm_coder.
+ */
+ vpdiff = step >> 3;
+ if ( delta & 4 ) vpdiff += step;
+ if ( delta & 2 ) vpdiff += step>>1;
+ if ( delta & 1 ) vpdiff += step>>2;
+
+ if ( sign )
+ valpred -= vpdiff;
+ else
+ valpred += vpdiff;
+
+ /* Step 5 - clamp output value */
+ if ( valpred > 32767 )
+ valpred = 32767;
+ else if ( valpred < -32768 )
+ valpred = -32768;
+
+ /* Step 6 - Update step value */
step = stepsizeTable[index];
- bufferstep = 0;
-
- for ( i=0; i < new_len; i += size ) {
- /* Step 1 - get the delta value and compute next index */
- if ( bufferstep ) {
- delta = inputbuffer & 0xf;
- } else {
- inputbuffer = *cp++;
- delta = (inputbuffer >> 4) & 0xf;
- }
-
- bufferstep = !bufferstep;
-
- /* Step 2 - Find new index value (for later) */
- index += indexTable[delta];
- if ( index < 0 ) index = 0;
- if ( index > 88 ) index = 88;
-
- /* Step 3 - Separate sign and magnitude */
- sign = delta & 8;
- delta = delta & 7;
-
- /* Step 4 - Compute difference and new predicted value */
- /*
- ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
- ** in adpcm_coder.
- */
- vpdiff = step >> 3;
- if ( delta & 4 ) vpdiff += step;
- if ( delta & 2 ) vpdiff += step>>1;
- if ( delta & 1 ) vpdiff += step>>2;
-
- if ( sign )
- valpred -= vpdiff;
- else
- valpred += vpdiff;
-
- /* Step 5 - clamp output value */
- if ( valpred > 32767 )
- valpred = 32767;
- else if ( valpred < -32768 )
- valpred = -32768;
-
- /* Step 6 - Update step value */
- step = stepsizeTable[index];
-
- /* Step 6 - Output value */
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16);
- }
- rv = Py_BuildValue("(O(ii))", str, valpred, index);
- Py_DECREF(str);
- return rv;
+ /* Step 6 - Output value */
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16);
+ }
+
+ rv = Py_BuildValue("(O(ii))", str, valpred, index);
+ Py_DECREF(str);
+ return rv;
}
static PyMethodDef audioop_methods[] = {
- { "max", audioop_max, METH_VARARGS },
- { "minmax", audioop_minmax, METH_VARARGS },
- { "avg", audioop_avg, METH_VARARGS },
- { "maxpp", audioop_maxpp, METH_VARARGS },
- { "avgpp", audioop_avgpp, METH_VARARGS },
- { "rms", audioop_rms, METH_VARARGS },
- { "findfit", audioop_findfit, METH_VARARGS },
- { "findmax", audioop_findmax, METH_VARARGS },
- { "findfactor", audioop_findfactor, METH_VARARGS },
- { "cross", audioop_cross, METH_VARARGS },
- { "mul", audioop_mul, METH_VARARGS },
- { "add", audioop_add, METH_VARARGS },
- { "bias", audioop_bias, METH_VARARGS },
- { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS },
- { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS },
- { "alaw2lin", audioop_alaw2lin, METH_VARARGS },
- { "lin2alaw", audioop_lin2alaw, METH_VARARGS },
- { "lin2lin", audioop_lin2lin, METH_VARARGS },
- { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS },
- { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS },
- { "tomono", audioop_tomono, METH_VARARGS },
- { "tostereo", audioop_tostereo, METH_VARARGS },
- { "getsample", audioop_getsample, METH_VARARGS },
- { "reverse", audioop_reverse, METH_VARARGS },
- { "ratecv", audioop_ratecv, METH_VARARGS },
- { 0, 0 }
+ { "max", audioop_max, METH_VARARGS },
+ { "minmax", audioop_minmax, METH_VARARGS },
+ { "avg", audioop_avg, METH_VARARGS },
+ { "maxpp", audioop_maxpp, METH_VARARGS },
+ { "avgpp", audioop_avgpp, METH_VARARGS },
+ { "rms", audioop_rms, METH_VARARGS },
+ { "findfit", audioop_findfit, METH_VARARGS },
+ { "findmax", audioop_findmax, METH_VARARGS },
+ { "findfactor", audioop_findfactor, METH_VARARGS },
+ { "cross", audioop_cross, METH_VARARGS },
+ { "mul", audioop_mul, METH_VARARGS },
+ { "add", audioop_add, METH_VARARGS },
+ { "bias", audioop_bias, METH_VARARGS },
+ { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS },
+ { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS },
+ { "alaw2lin", audioop_alaw2lin, METH_VARARGS },
+ { "lin2alaw", audioop_lin2alaw, METH_VARARGS },
+ { "lin2lin", audioop_lin2lin, METH_VARARGS },
+ { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS },
+ { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS },
+ { "tomono", audioop_tomono, METH_VARARGS },
+ { "tostereo", audioop_tostereo, METH_VARARGS },
+ { "getsample", audioop_getsample, METH_VARARGS },
+ { "reverse", audioop_reverse, METH_VARARGS },
+ { "ratecv", audioop_ratecv, METH_VARARGS },
+ { 0, 0 }
};
static struct PyModuleDef audioopmodule = {
- PyModuleDef_HEAD_INIT,
- "audioop",
- NULL,
- -1,
- audioop_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "audioop",
+ NULL,
+ -1,
+ audioop_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_audioop(void)
{
- PyObject *m, *d;
- m = PyModule_Create(&audioopmodule);
- if (m == NULL)
- return NULL;
- d = PyModule_GetDict(m);
- if (d == NULL)
- return NULL;
- AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
- if (AudioopError != NULL)
- PyDict_SetItemString(d,"error",AudioopError);
- return m;
+ PyObject *m, *d;
+ m = PyModule_Create(&audioopmodule);
+ if (m == NULL)
+ return NULL;
+ d = PyModule_GetDict(m);
+ if (d == NULL)
+ return NULL;
+ AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
+ if (AudioopError != NULL)
+ PyDict_SetItemString(d,"error",AudioopError);
+ return m;
}
diff --git a/Modules/binascii.c b/Modules/binascii.c
index 38d22ab..d21404b 100644
--- a/Modules/binascii.c
+++ b/Modules/binascii.c
@@ -3,40 +3,40 @@
**
** This module currently supports the following encodings:
** uuencode:
-** each line encodes 45 bytes (except possibly the last)
-** First char encodes (binary) length, rest data
-** each char encodes 6 bits, as follows:
-** binary: 01234567 abcdefgh ijklmnop
-** ascii: 012345 67abcd efghij klmnop
-** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc.
-** short binary data is zero-extended (so the bits are always in the
-** right place), this does *not* reflect in the length.
+** each line encodes 45 bytes (except possibly the last)
+** First char encodes (binary) length, rest data
+** each char encodes 6 bits, as follows:
+** binary: 01234567 abcdefgh ijklmnop
+** ascii: 012345 67abcd efghij klmnop
+** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc.
+** short binary data is zero-extended (so the bits are always in the
+** right place), this does *not* reflect in the length.
** base64:
** Line breaks are insignificant, but lines are at most 76 chars
** each char encodes 6 bits, in similar order as uucode/hqx. Encoding
** is done via a table.
** Short binary data is filled (in ASCII) with '='.
** hqx:
-** File starts with introductory text, real data starts and ends
-** with colons.
-** Data consists of three similar parts: info, datafork, resourcefork.
-** Each part is protected (at the end) with a 16-bit crc
-** The binary data is run-length encoded, and then ascii-fied:
-** binary: 01234567 abcdefgh ijklmnop
-** ascii: 012345 67abcd efghij klmnop
-** ASCII encoding is table-driven, see the code.
-** Short binary data results in the runt ascii-byte being output with
-** the bits in the right place.
+** File starts with introductory text, real data starts and ends
+** with colons.
+** Data consists of three similar parts: info, datafork, resourcefork.
+** Each part is protected (at the end) with a 16-bit crc
+** The binary data is run-length encoded, and then ascii-fied:
+** binary: 01234567 abcdefgh ijklmnop
+** ascii: 012345 67abcd efghij klmnop
+** ASCII encoding is table-driven, see the code.
+** Short binary data results in the runt ascii-byte being output with
+** the bits in the right place.
**
** While I was reading dozens of programs that encode or decode the formats
** here (documentation? hihi:-) I have formulated Jansen's Observation:
**
-** Programs that encode binary data in ASCII are written in
-** such a style that they are as unreadable as possible. Devices used
-** include unnecessary global variables, burying important tables
-** in unrelated sourcefiles, putting functions in include files,
-** using seemingly-descriptive variable names for different purposes,
-** calls to empty subroutines and a host of others.
+** Programs that encode binary data in ASCII are written in
+** such a style that they are as unreadable as possible. Devices used
+** include unnecessary global variables, burying important tables
+** in unrelated sourcefiles, putting functions in include files,
+** using seemingly-descriptive variable names for different purposes,
+** calls to empty subroutines and a host of others.
**
** I have attempted to break with this tradition, but I guess that that
** does make the performance sub-optimal. Oh well, too bad...
@@ -75,67 +75,67 @@ static PyObject *Incomplete;
static unsigned char table_a2b_hqx[256] = {
/* ^@ ^A ^B ^C ^D ^E ^F ^G */
-/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
/* \b \t \n ^K ^L \r ^N ^O */
-/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL,
+/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL,
/* ^P ^Q ^R ^S ^T ^U ^V ^W */
-/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
/* ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */
-/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
/* ! " # $ % & ' */
-/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
+/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
/* ( ) * + , - . / */
-/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL,
+/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL,
/* 0 1 2 3 4 5 6 7 */
-/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL,
+/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL,
/* 8 9 : ; < = > ? */
-/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL,
/* @ A B C D E F G */
-/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
+/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
/* H I J K L M N O */
-/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL,
+/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL,
/* P Q R S T U V W */
-/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL,
+/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL,
/* X Y Z [ \ ] ^ _ */
-/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL,
+/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL,
/* ` a b c d e f g */
-/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL,
+/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL,
/* h i j k l m n o */
-/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL,
+/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL,
/* p q r s t u v w */
-/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL,
+/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL,
/* x y z { | } ~ ^? */
-/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
-/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
};
static unsigned char table_b2a_hqx[] =
"!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr";
static char table_a2b_base64[] = {
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */
- -1, 0, 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,-1, -1,-1,-1,-1,
- -1,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,-1, -1,-1,-1,-1
+ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
+ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
+ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
+ 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */
+ -1, 0, 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,-1, -1,-1,-1,-1,
+ -1,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,-1, -1,-1,-1,-1
};
#define BASE64_PAD '='
@@ -149,38 +149,38 @@ static unsigned char table_b2a_base64[] =
static unsigned short crctab_hqx[256] = {
- 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
- 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
- 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
- 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
- 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
- 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
- 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
- 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
- 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
- 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
- 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
- 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
- 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
- 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
- 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
- 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
- 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
- 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
- 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
- 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
- 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
- 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
- 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
- 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
- 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
- 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
- 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
- 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
- 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
- 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
- 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
- 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+ 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+ 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+ 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+ 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+ 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+ 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+ 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+ 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+ 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+ 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+ 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+ 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+ 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+ 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+ 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+ 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+ 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+ 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+ 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+ 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+ 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+ 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
};
PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data");
@@ -188,85 +188,85 @@ PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data");
static PyObject *
binascii_a2b_uu(PyObject *self, PyObject *args)
{
- Py_buffer pascii;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t ascii_len, bin_len;
-
- if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) )
- return NULL;
- ascii_data = pascii.buf;
- ascii_len = pascii.len;
-
- assert(ascii_len >= 0);
-
- /* First byte: binary data length (in bytes) */
- bin_len = (*ascii_data++ - ' ') & 077;
- ascii_len--;
-
- /* Allocate the buffer */
- if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) {
- PyBuffer_Release(&pascii);
- return NULL;
- }
- bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) {
- /* XXX is it really best to add NULs if there's no more data */
- this_ch = (ascii_len > 0) ? *ascii_data : 0;
- if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) {
- /*
- ** Whitespace. Assume some spaces got eaten at
- ** end-of-line. (We check this later)
- */
- this_ch = 0;
- } else {
- /* Check the character for legality
- ** The 64 in stead of the expected 63 is because
- ** there are a few uuencodes out there that use
- ** '`' as zero instead of space.
- */
- if ( this_ch < ' ' || this_ch > (' ' + 64)) {
- PyErr_SetString(Error, "Illegal char");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- this_ch = (this_ch - ' ') & 077;
- }
- /*
- ** Shift it in on the low end, and see if there's
- ** a byte ready for output.
- */
- leftchar = (leftchar << 6) | (this_ch);
- leftbits += 6;
- if ( leftbits >= 8 ) {
- leftbits -= 8;
- *bin_data++ = (leftchar >> leftbits) & 0xff;
- leftchar &= ((1 << leftbits) - 1);
- bin_len--;
- }
- }
- /*
- ** Finally, check that if there's anything left on the line
- ** that it's whitespace only.
- */
- while( ascii_len-- > 0 ) {
- this_ch = *ascii_data++;
- /* Extra '`' may be written as padding in some cases */
- if ( this_ch != ' ' && this_ch != ' '+64 &&
- this_ch != '\n' && this_ch != '\r' ) {
- PyErr_SetString(Error, "Trailing garbage");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- }
- PyBuffer_Release(&pascii);
- return rv;
+ Py_buffer pascii;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t ascii_len, bin_len;
+
+ if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) )
+ return NULL;
+ ascii_data = pascii.buf;
+ ascii_len = pascii.len;
+
+ assert(ascii_len >= 0);
+
+ /* First byte: binary data length (in bytes) */
+ bin_len = (*ascii_data++ - ' ') & 077;
+ ascii_len--;
+
+ /* Allocate the buffer */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) {
+ PyBuffer_Release(&pascii);
+ return NULL;
+ }
+ bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) {
+ /* XXX is it really best to add NULs if there's no more data */
+ this_ch = (ascii_len > 0) ? *ascii_data : 0;
+ if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) {
+ /*
+ ** Whitespace. Assume some spaces got eaten at
+ ** end-of-line. (We check this later)
+ */
+ this_ch = 0;
+ } else {
+ /* Check the character for legality
+ ** The 64 in stead of the expected 63 is because
+ ** there are a few uuencodes out there that use
+ ** '`' as zero instead of space.
+ */
+ if ( this_ch < ' ' || this_ch > (' ' + 64)) {
+ PyErr_SetString(Error, "Illegal char");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ this_ch = (this_ch - ' ') & 077;
+ }
+ /*
+ ** Shift it in on the low end, and see if there's
+ ** a byte ready for output.
+ */
+ leftchar = (leftchar << 6) | (this_ch);
+ leftbits += 6;
+ if ( leftbits >= 8 ) {
+ leftbits -= 8;
+ *bin_data++ = (leftchar >> leftbits) & 0xff;
+ leftchar &= ((1 << leftbits) - 1);
+ bin_len--;
+ }
+ }
+ /*
+ ** Finally, check that if there's anything left on the line
+ ** that it's whitespace only.
+ */
+ while( ascii_len-- > 0 ) {
+ this_ch = *ascii_data++;
+ /* Extra '`' may be written as padding in some cases */
+ if ( this_ch != ' ' && this_ch != ' '+64 &&
+ this_ch != '\n' && this_ch != '\r' ) {
+ PyErr_SetString(Error, "Trailing garbage");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ }
+ PyBuffer_Release(&pascii);
+ return rv;
}
PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
@@ -274,86 +274,86 @@ PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
static PyObject *
binascii_b2a_uu(PyObject *self, PyObject *args)
{
- Py_buffer pbin;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t bin_len;
-
- if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) )
- return NULL;
- bin_data = pbin.buf;
- bin_len = pbin.len;
- if ( bin_len > 45 ) {
- /* The 45 is a limit that appears in all uuencode's */
- PyErr_SetString(Error, "At most 45 bytes at once");
- PyBuffer_Release(&pbin);
- return NULL;
- }
-
- /* We're lazy and allocate to much (fixed up later) */
- if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) {
- PyBuffer_Release(&pbin);
- return NULL;
- }
- ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- /* Store the length */
- *ascii_data++ = ' ' + (bin_len & 077);
-
- for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) {
- /* Shift the data (or padding) into our buffer */
- if ( bin_len > 0 ) /* Data */
- leftchar = (leftchar << 8) | *bin_data;
- else /* Padding */
- leftchar <<= 8;
- leftbits += 8;
-
- /* See if there are 6-bit groups ready */
- while ( leftbits >= 6 ) {
- this_ch = (leftchar >> (leftbits-6)) & 0x3f;
- leftbits -= 6;
- *ascii_data++ = this_ch + ' ';
- }
- }
- *ascii_data++ = '\n'; /* Append a courtesy newline */
-
- if (_PyBytes_Resize(&rv,
- (ascii_data -
- (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbin);
- return rv;
+ Py_buffer pbin;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t bin_len;
+
+ if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) )
+ return NULL;
+ bin_data = pbin.buf;
+ bin_len = pbin.len;
+ if ( bin_len > 45 ) {
+ /* The 45 is a limit that appears in all uuencode's */
+ PyErr_SetString(Error, "At most 45 bytes at once");
+ PyBuffer_Release(&pbin);
+ return NULL;
+ }
+
+ /* We're lazy and allocate to much (fixed up later) */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) {
+ PyBuffer_Release(&pbin);
+ return NULL;
+ }
+ ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ /* Store the length */
+ *ascii_data++ = ' ' + (bin_len & 077);
+
+ for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) {
+ /* Shift the data (or padding) into our buffer */
+ if ( bin_len > 0 ) /* Data */
+ leftchar = (leftchar << 8) | *bin_data;
+ else /* Padding */
+ leftchar <<= 8;
+ leftbits += 8;
+
+ /* See if there are 6-bit groups ready */
+ while ( leftbits >= 6 ) {
+ this_ch = (leftchar >> (leftbits-6)) & 0x3f;
+ leftbits -= 6;
+ *ascii_data++ = this_ch + ' ';
+ }
+ }
+ *ascii_data++ = '\n'; /* Append a courtesy newline */
+
+ if (_PyBytes_Resize(&rv,
+ (ascii_data -
+ (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbin);
+ return rv;
}
static int
binascii_find_valid(unsigned char *s, Py_ssize_t slen, int num)
{
- /* Finds & returns the (num+1)th
- ** valid character for base64, or -1 if none.
- */
-
- int ret = -1;
- unsigned char c, b64val;
-
- while ((slen > 0) && (ret == -1)) {
- c = *s;
- b64val = table_a2b_base64[c & 0x7f];
- if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) {
- if (num == 0)
- ret = *s;
- num--;
- }
-
- s++;
- slen--;
- }
- return ret;
+ /* Finds & returns the (num+1)th
+ ** valid character for base64, or -1 if none.
+ */
+
+ int ret = -1;
+ unsigned char c, b64val;
+
+ while ((slen > 0) && (ret == -1)) {
+ c = *s;
+ b64val = table_a2b_base64[c & 0x7f];
+ if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) {
+ if (num == 0)
+ ret = *s;
+ num--;
+ }
+
+ s++;
+ slen--;
+ }
+ return ret;
}
PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data");
@@ -361,108 +361,108 @@ PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data");
static PyObject *
binascii_a2b_base64(PyObject *self, PyObject *args)
{
- Py_buffer pascii;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t ascii_len, bin_len;
- int quad_pos = 0;
-
- if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) )
- return NULL;
- ascii_data = pascii.buf;
- ascii_len = pascii.len;
-
- assert(ascii_len >= 0);
-
- if (ascii_len > PY_SSIZE_T_MAX - 3) {
- PyBuffer_Release(&pascii);
- return PyErr_NoMemory();
- }
-
- bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
-
- /* Allocate the buffer */
- if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) {
- PyBuffer_Release(&pascii);
- return NULL;
- }
- bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
- bin_len = 0;
-
- for( ; ascii_len > 0; ascii_len--, ascii_data++) {
- this_ch = *ascii_data;
-
- if (this_ch > 0x7f ||
- this_ch == '\r' || this_ch == '\n' || this_ch == ' ')
- continue;
-
- /* Check for pad sequences and ignore
- ** the invalid ones.
- */
- if (this_ch == BASE64_PAD) {
- if ( (quad_pos < 2) ||
- ((quad_pos == 2) &&
- (binascii_find_valid(ascii_data, ascii_len, 1)
- != BASE64_PAD)) )
- {
- continue;
- }
- else {
- /* A pad sequence means no more input.
- ** We've already interpreted the data
- ** from the quad at this point.
- */
- leftbits = 0;
- break;
- }
- }
-
- this_ch = table_a2b_base64[*ascii_data];
- if ( this_ch == (unsigned char) -1 )
- continue;
-
- /*
- ** Shift it in on the low end, and see if there's
- ** a byte ready for output.
- */
- quad_pos = (quad_pos + 1) & 0x03;
- leftchar = (leftchar << 6) | (this_ch);
- leftbits += 6;
-
- if ( leftbits >= 8 ) {
- leftbits -= 8;
- *bin_data++ = (leftchar >> leftbits) & 0xff;
- bin_len++;
- leftchar &= ((1 << leftbits) - 1);
- }
- }
-
- if (leftbits != 0) {
- PyBuffer_Release(&pascii);
- PyErr_SetString(Error, "Incorrect padding");
- Py_DECREF(rv);
- return NULL;
- }
-
- /* And set string size correctly. If the result string is empty
- ** (because the input was all invalid) return the shared empty
- ** string instead; _PyBytes_Resize() won't do this for us.
- */
- if (bin_len > 0) {
- if (_PyBytes_Resize(&rv, bin_len) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- }
- else {
- Py_DECREF(rv);
- rv = PyBytes_FromStringAndSize("", 0);
- }
- PyBuffer_Release(&pascii);
- return rv;
+ Py_buffer pascii;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t ascii_len, bin_len;
+ int quad_pos = 0;
+
+ if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) )
+ return NULL;
+ ascii_data = pascii.buf;
+ ascii_len = pascii.len;
+
+ assert(ascii_len >= 0);
+
+ if (ascii_len > PY_SSIZE_T_MAX - 3) {
+ PyBuffer_Release(&pascii);
+ return PyErr_NoMemory();
+ }
+
+ bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
+
+ /* Allocate the buffer */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) {
+ PyBuffer_Release(&pascii);
+ return NULL;
+ }
+ bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
+ bin_len = 0;
+
+ for( ; ascii_len > 0; ascii_len--, ascii_data++) {
+ this_ch = *ascii_data;
+
+ if (this_ch > 0x7f ||
+ this_ch == '\r' || this_ch == '\n' || this_ch == ' ')
+ continue;
+
+ /* Check for pad sequences and ignore
+ ** the invalid ones.
+ */
+ if (this_ch == BASE64_PAD) {
+ if ( (quad_pos < 2) ||
+ ((quad_pos == 2) &&
+ (binascii_find_valid(ascii_data, ascii_len, 1)
+ != BASE64_PAD)) )
+ {
+ continue;
+ }
+ else {
+ /* A pad sequence means no more input.
+ ** We've already interpreted the data
+ ** from the quad at this point.
+ */
+ leftbits = 0;
+ break;
+ }
+ }
+
+ this_ch = table_a2b_base64[*ascii_data];
+ if ( this_ch == (unsigned char) -1 )
+ continue;
+
+ /*
+ ** Shift it in on the low end, and see if there's
+ ** a byte ready for output.
+ */
+ quad_pos = (quad_pos + 1) & 0x03;
+ leftchar = (leftchar << 6) | (this_ch);
+ leftbits += 6;
+
+ if ( leftbits >= 8 ) {
+ leftbits -= 8;
+ *bin_data++ = (leftchar >> leftbits) & 0xff;
+ bin_len++;
+ leftchar &= ((1 << leftbits) - 1);
+ }
+ }
+
+ if (leftbits != 0) {
+ PyBuffer_Release(&pascii);
+ PyErr_SetString(Error, "Incorrect padding");
+ Py_DECREF(rv);
+ return NULL;
+ }
+
+ /* And set string size correctly. If the result string is empty
+ ** (because the input was all invalid) return the shared empty
+ ** string instead; _PyBytes_Resize() won't do this for us.
+ */
+ if (bin_len > 0) {
+ if (_PyBytes_Resize(&rv, bin_len) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ }
+ else {
+ Py_DECREF(rv);
+ rv = PyBytes_FromStringAndSize("", 0);
+ }
+ PyBuffer_Release(&pascii);
+ return rv;
}
PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
@@ -470,66 +470,66 @@ PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
static PyObject *
binascii_b2a_base64(PyObject *self, PyObject *args)
{
- Py_buffer pbuf;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t bin_len;
-
- if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) )
- return NULL;
- bin_data = pbuf.buf;
- bin_len = pbuf.len;
-
- assert(bin_len >= 0);
-
- if ( bin_len > BASE64_MAXBIN ) {
- PyErr_SetString(Error, "Too much data for base64 line");
- PyBuffer_Release(&pbuf);
- return NULL;
- }
-
- /* We're lazy and allocate too much (fixed up later).
- "+3" leaves room for up to two pad characters and a trailing
- newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */
- if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) {
- PyBuffer_Release(&pbuf);
- return NULL;
- }
- ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- for( ; bin_len > 0 ; bin_len--, bin_data++ ) {
- /* Shift the data into our buffer */
- leftchar = (leftchar << 8) | *bin_data;
- leftbits += 8;
-
- /* See if there are 6-bit groups ready */
- while ( leftbits >= 6 ) {
- this_ch = (leftchar >> (leftbits-6)) & 0x3f;
- leftbits -= 6;
- *ascii_data++ = table_b2a_base64[this_ch];
- }
- }
- if ( leftbits == 2 ) {
- *ascii_data++ = table_b2a_base64[(leftchar&3) << 4];
- *ascii_data++ = BASE64_PAD;
- *ascii_data++ = BASE64_PAD;
- } else if ( leftbits == 4 ) {
- *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2];
- *ascii_data++ = BASE64_PAD;
- }
- *ascii_data++ = '\n'; /* Append a courtesy newline */
-
- if (_PyBytes_Resize(&rv,
- (ascii_data -
- (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbuf);
- return rv;
+ Py_buffer pbuf;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t bin_len;
+
+ if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) )
+ return NULL;
+ bin_data = pbuf.buf;
+ bin_len = pbuf.len;
+
+ assert(bin_len >= 0);
+
+ if ( bin_len > BASE64_MAXBIN ) {
+ PyErr_SetString(Error, "Too much data for base64 line");
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+
+ /* We're lazy and allocate too much (fixed up later).
+ "+3" leaves room for up to two pad characters and a trailing
+ newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) {
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+ ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ for( ; bin_len > 0 ; bin_len--, bin_data++ ) {
+ /* Shift the data into our buffer */
+ leftchar = (leftchar << 8) | *bin_data;
+ leftbits += 8;
+
+ /* See if there are 6-bit groups ready */
+ while ( leftbits >= 6 ) {
+ this_ch = (leftchar >> (leftbits-6)) & 0x3f;
+ leftbits -= 6;
+ *ascii_data++ = table_b2a_base64[this_ch];
+ }
+ }
+ if ( leftbits == 2 ) {
+ *ascii_data++ = table_b2a_base64[(leftchar&3) << 4];
+ *ascii_data++ = BASE64_PAD;
+ *ascii_data++ = BASE64_PAD;
+ } else if ( leftbits == 4 ) {
+ *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2];
+ *ascii_data++ = BASE64_PAD;
+ }
+ *ascii_data++ = '\n'; /* Append a courtesy newline */
+
+ if (_PyBytes_Resize(&rv,
+ (ascii_data -
+ (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbuf);
+ return rv;
}
PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
@@ -537,85 +537,85 @@ PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
static PyObject *
binascii_a2b_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pascii;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t len;
- int done = 0;
-
- if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) )
- return NULL;
- ascii_data = pascii.buf;
- len = pascii.len;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX - 2) {
- PyBuffer_Release(&pascii);
- return PyErr_NoMemory();
- }
-
- /* Allocate a string that is too big (fixed later)
- Add two to the initial length to prevent interning which
- would preclude subsequent resizing. */
- if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) {
- PyBuffer_Release(&pascii);
- return NULL;
- }
- bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- for( ; len > 0 ; len--, ascii_data++ ) {
- /* Get the byte and look it up */
- this_ch = table_a2b_hqx[*ascii_data];
- if ( this_ch == SKIP )
- continue;
- if ( this_ch == FAIL ) {
- PyErr_SetString(Error, "Illegal char");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- if ( this_ch == DONE ) {
- /* The terminating colon */
- done = 1;
- break;
- }
-
- /* Shift it into the buffer and see if any bytes are ready */
- leftchar = (leftchar << 6) | (this_ch);
- leftbits += 6;
- if ( leftbits >= 8 ) {
- leftbits -= 8;
- *bin_data++ = (leftchar >> leftbits) & 0xff;
- leftchar &= ((1 << leftbits) - 1);
- }
- }
-
- if ( leftbits && !done ) {
- PyErr_SetString(Incomplete,
- "String has incomplete number of bytes");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- if (_PyBytes_Resize(&rv,
- (bin_data -
- (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- if (rv) {
- PyObject *rrv = Py_BuildValue("Oi", rv, done);
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return rrv;
- }
-
- PyBuffer_Release(&pascii);
- return NULL;
+ Py_buffer pascii;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t len;
+ int done = 0;
+
+ if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) )
+ return NULL;
+ ascii_data = pascii.buf;
+ len = pascii.len;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX - 2) {
+ PyBuffer_Release(&pascii);
+ return PyErr_NoMemory();
+ }
+
+ /* Allocate a string that is too big (fixed later)
+ Add two to the initial length to prevent interning which
+ would preclude subsequent resizing. */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) {
+ PyBuffer_Release(&pascii);
+ return NULL;
+ }
+ bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ for( ; len > 0 ; len--, ascii_data++ ) {
+ /* Get the byte and look it up */
+ this_ch = table_a2b_hqx[*ascii_data];
+ if ( this_ch == SKIP )
+ continue;
+ if ( this_ch == FAIL ) {
+ PyErr_SetString(Error, "Illegal char");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ if ( this_ch == DONE ) {
+ /* The terminating colon */
+ done = 1;
+ break;
+ }
+
+ /* Shift it into the buffer and see if any bytes are ready */
+ leftchar = (leftchar << 6) | (this_ch);
+ leftbits += 6;
+ if ( leftbits >= 8 ) {
+ leftbits -= 8;
+ *bin_data++ = (leftchar >> leftbits) & 0xff;
+ leftchar &= ((1 << leftbits) - 1);
+ }
+ }
+
+ if ( leftbits && !done ) {
+ PyErr_SetString(Incomplete,
+ "String has incomplete number of bytes");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ if (_PyBytes_Resize(&rv,
+ (bin_data -
+ (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ if (rv) {
+ PyObject *rrv = Py_BuildValue("Oi", rv, done);
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return rrv;
+ }
+
+ PyBuffer_Release(&pascii);
+ return NULL;
}
PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
@@ -623,63 +623,63 @@ PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
static PyObject *
binascii_rlecode_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pbuf;
- unsigned char *in_data, *out_data;
- PyObject *rv;
- unsigned char ch;
- Py_ssize_t in, inend, len;
-
- if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) )
- return NULL;
- in_data = pbuf.buf;
- len = pbuf.len;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX / 2 - 2) {
- PyBuffer_Release(&pbuf);
- return PyErr_NoMemory();
- }
-
- /* Worst case: output is twice as big as input (fixed later) */
- if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) {
- PyBuffer_Release(&pbuf);
- return NULL;
- }
- out_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- for( in=0; in<len; in++) {
- ch = in_data[in];
- if ( ch == RUNCHAR ) {
- /* RUNCHAR. Escape it. */
- *out_data++ = RUNCHAR;
- *out_data++ = 0;
- } else {
- /* Check how many following are the same */
- for(inend=in+1;
- inend<len && in_data[inend] == ch &&
- inend < in+255;
- inend++) ;
- if ( inend - in > 3 ) {
- /* More than 3 in a row. Output RLE. */
- *out_data++ = ch;
- *out_data++ = RUNCHAR;
- *out_data++ = inend-in;
- in = inend-1;
- } else {
- /* Less than 3. Output the byte itself */
- *out_data++ = ch;
- }
- }
- }
- if (_PyBytes_Resize(&rv,
- (out_data -
- (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbuf);
- return rv;
+ Py_buffer pbuf;
+ unsigned char *in_data, *out_data;
+ PyObject *rv;
+ unsigned char ch;
+ Py_ssize_t in, inend, len;
+
+ if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) )
+ return NULL;
+ in_data = pbuf.buf;
+ len = pbuf.len;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX / 2 - 2) {
+ PyBuffer_Release(&pbuf);
+ return PyErr_NoMemory();
+ }
+
+ /* Worst case: output is twice as big as input (fixed later) */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) {
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+ out_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ for( in=0; in<len; in++) {
+ ch = in_data[in];
+ if ( ch == RUNCHAR ) {
+ /* RUNCHAR. Escape it. */
+ *out_data++ = RUNCHAR;
+ *out_data++ = 0;
+ } else {
+ /* Check how many following are the same */
+ for(inend=in+1;
+ inend<len && in_data[inend] == ch &&
+ inend < in+255;
+ inend++) ;
+ if ( inend - in > 3 ) {
+ /* More than 3 in a row. Output RLE. */
+ *out_data++ = ch;
+ *out_data++ = RUNCHAR;
+ *out_data++ = inend-in;
+ in = inend-1;
+ } else {
+ /* Less than 3. Output the byte itself */
+ *out_data++ = ch;
+ }
+ }
+ }
+ if (_PyBytes_Resize(&rv,
+ (out_data -
+ (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbuf);
+ return rv;
}
PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
@@ -687,56 +687,56 @@ PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
static PyObject *
binascii_b2a_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pbin;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t len;
-
- if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) )
- return NULL;
- bin_data = pbin.buf;
- len = pbin.len;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX / 2 - 2) {
- PyBuffer_Release(&pbin);
- return PyErr_NoMemory();
- }
-
- /* Allocate a buffer that is at least large enough */
- if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) {
- PyBuffer_Release(&pbin);
- return NULL;
- }
- ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- for( ; len > 0 ; len--, bin_data++ ) {
- /* Shift into our buffer, and output any 6bits ready */
- leftchar = (leftchar << 8) | *bin_data;
- leftbits += 8;
- while ( leftbits >= 6 ) {
- this_ch = (leftchar >> (leftbits-6)) & 0x3f;
- leftbits -= 6;
- *ascii_data++ = table_b2a_hqx[this_ch];
- }
- }
- /* Output a possible runt byte */
- if ( leftbits ) {
- leftchar <<= (6-leftbits);
- *ascii_data++ = table_b2a_hqx[leftchar & 0x3f];
- }
- if (_PyBytes_Resize(&rv,
- (ascii_data -
- (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbin);
- return rv;
+ Py_buffer pbin;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t len;
+
+ if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) )
+ return NULL;
+ bin_data = pbin.buf;
+ len = pbin.len;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX / 2 - 2) {
+ PyBuffer_Release(&pbin);
+ return PyErr_NoMemory();
+ }
+
+ /* Allocate a buffer that is at least large enough */
+ if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) {
+ PyBuffer_Release(&pbin);
+ return NULL;
+ }
+ ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ for( ; len > 0 ; len--, bin_data++ ) {
+ /* Shift into our buffer, and output any 6bits ready */
+ leftchar = (leftchar << 8) | *bin_data;
+ leftbits += 8;
+ while ( leftbits >= 6 ) {
+ this_ch = (leftchar >> (leftbits-6)) & 0x3f;
+ leftbits -= 6;
+ *ascii_data++ = table_b2a_hqx[this_ch];
+ }
+ }
+ /* Output a possible runt byte */
+ if ( leftbits ) {
+ leftchar <<= (6-leftbits);
+ *ascii_data++ = table_b2a_hqx[leftchar & 0x3f];
+ }
+ if (_PyBytes_Resize(&rv,
+ (ascii_data -
+ (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbin);
+ return rv;
}
PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
@@ -744,116 +744,116 @@ PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
static PyObject *
binascii_rledecode_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pin;
- unsigned char *in_data, *out_data;
- unsigned char in_byte, in_repeat;
- PyObject *rv;
- Py_ssize_t in_len, out_len, out_len_left;
-
- if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) )
- return NULL;
- in_data = pin.buf;
- in_len = pin.len;
-
- assert(in_len >= 0);
-
- /* Empty string is a special case */
- if ( in_len == 0 ) {
- PyBuffer_Release(&pin);
- return PyBytes_FromStringAndSize("", 0);
- }
- else if (in_len > PY_SSIZE_T_MAX / 2) {
- PyBuffer_Release(&pin);
- return PyErr_NoMemory();
- }
-
- /* Allocate a buffer of reasonable size. Resized when needed */
- out_len = in_len*2;
- if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) {
- PyBuffer_Release(&pin);
- return NULL;
- }
- out_len_left = out_len;
- out_data = (unsigned char *)PyBytes_AS_STRING(rv);
-
- /*
- ** We need two macros here to get/put bytes and handle
- ** end-of-buffer for input and output strings.
- */
+ Py_buffer pin;
+ unsigned char *in_data, *out_data;
+ unsigned char in_byte, in_repeat;
+ PyObject *rv;
+ Py_ssize_t in_len, out_len, out_len_left;
+
+ if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) )
+ return NULL;
+ in_data = pin.buf;
+ in_len = pin.len;
+
+ assert(in_len >= 0);
+
+ /* Empty string is a special case */
+ if ( in_len == 0 ) {
+ PyBuffer_Release(&pin);
+ return PyBytes_FromStringAndSize("", 0);
+ }
+ else if (in_len > PY_SSIZE_T_MAX / 2) {
+ PyBuffer_Release(&pin);
+ return PyErr_NoMemory();
+ }
+
+ /* Allocate a buffer of reasonable size. Resized when needed */
+ out_len = in_len*2;
+ if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) {
+ PyBuffer_Release(&pin);
+ return NULL;
+ }
+ out_len_left = out_len;
+ out_data = (unsigned char *)PyBytes_AS_STRING(rv);
+
+ /*
+ ** We need two macros here to get/put bytes and handle
+ ** end-of-buffer for input and output strings.
+ */
#define INBYTE(b) \
- do { \
- if ( --in_len < 0 ) { \
- PyErr_SetString(Incomplete, ""); \
- Py_DECREF(rv); \
- PyBuffer_Release(&pin); \
- return NULL; \
- } \
- b = *in_data++; \
- } while(0)
+ do { \
+ if ( --in_len < 0 ) { \
+ PyErr_SetString(Incomplete, ""); \
+ Py_DECREF(rv); \
+ PyBuffer_Release(&pin); \
+ return NULL; \
+ } \
+ b = *in_data++; \
+ } while(0)
#define OUTBYTE(b) \
- do { \
- if ( --out_len_left < 0 ) { \
- if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \
- if (_PyBytes_Resize(&rv, 2*out_len) < 0) \
- { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \
- out_data = (unsigned char *)PyBytes_AS_STRING(rv) \
- + out_len; \
- out_len_left = out_len-1; \
- out_len = out_len * 2; \
- } \
- *out_data++ = b; \
- } while(0)
-
- /*
- ** Handle first byte separately (since we have to get angry
- ** in case of an orphaned RLE code).
- */
- INBYTE(in_byte);
-
- if (in_byte == RUNCHAR) {
- INBYTE(in_repeat);
- if (in_repeat != 0) {
- /* Note Error, not Incomplete (which is at the end
- ** of the string only). This is a programmer error.
- */
- PyErr_SetString(Error, "Orphaned RLE code at start");
- PyBuffer_Release(&pin);
- Py_DECREF(rv);
- return NULL;
- }
- OUTBYTE(RUNCHAR);
- } else {
- OUTBYTE(in_byte);
- }
-
- while( in_len > 0 ) {
- INBYTE(in_byte);
-
- if (in_byte == RUNCHAR) {
- INBYTE(in_repeat);
- if ( in_repeat == 0 ) {
- /* Just an escaped RUNCHAR value */
- OUTBYTE(RUNCHAR);
- } else {
- /* Pick up value and output a sequence of it */
- in_byte = out_data[-1];
- while ( --in_repeat > 0 )
- OUTBYTE(in_byte);
- }
- } else {
- /* Normal byte */
- OUTBYTE(in_byte);
- }
- }
- if (_PyBytes_Resize(&rv,
- (out_data -
- (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pin);
- return rv;
+ do { \
+ if ( --out_len_left < 0 ) { \
+ if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \
+ if (_PyBytes_Resize(&rv, 2*out_len) < 0) \
+ { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \
+ out_data = (unsigned char *)PyBytes_AS_STRING(rv) \
+ + out_len; \
+ out_len_left = out_len-1; \
+ out_len = out_len * 2; \
+ } \
+ *out_data++ = b; \
+ } while(0)
+
+ /*
+ ** Handle first byte separately (since we have to get angry
+ ** in case of an orphaned RLE code).
+ */
+ INBYTE(in_byte);
+
+ if (in_byte == RUNCHAR) {
+ INBYTE(in_repeat);
+ if (in_repeat != 0) {
+ /* Note Error, not Incomplete (which is at the end
+ ** of the string only). This is a programmer error.
+ */
+ PyErr_SetString(Error, "Orphaned RLE code at start");
+ PyBuffer_Release(&pin);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ OUTBYTE(RUNCHAR);
+ } else {
+ OUTBYTE(in_byte);
+ }
+
+ while( in_len > 0 ) {
+ INBYTE(in_byte);
+
+ if (in_byte == RUNCHAR) {
+ INBYTE(in_repeat);
+ if ( in_repeat == 0 ) {
+ /* Just an escaped RUNCHAR value */
+ OUTBYTE(RUNCHAR);
+ } else {
+ /* Pick up value and output a sequence of it */
+ in_byte = out_data[-1];
+ while ( --in_repeat > 0 )
+ OUTBYTE(in_byte);
+ }
+ } else {
+ /* Normal byte */
+ OUTBYTE(in_byte);
+ }
+ }
+ if (_PyBytes_Resize(&rv,
+ (out_data -
+ (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pin);
+ return rv;
}
PyDoc_STRVAR(doc_crc_hqx,
@@ -862,22 +862,22 @@ PyDoc_STRVAR(doc_crc_hqx,
static PyObject *
binascii_crc_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pin;
- unsigned char *bin_data;
- unsigned int crc;
- Py_ssize_t len;
-
- if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) )
- return NULL;
- bin_data = pin.buf;
- len = pin.len;
-
- while(len-- > 0) {
- crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
- }
-
- PyBuffer_Release(&pin);
- return Py_BuildValue("i", crc);
+ Py_buffer pin;
+ unsigned char *bin_data;
+ unsigned int crc;
+ Py_ssize_t len;
+
+ if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) )
+ return NULL;
+ bin_data = pin.buf;
+ len = pin.len;
+
+ while(len-- > 0) {
+ crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
+ }
+
+ PyBuffer_Release(&pin);
+ return Py_BuildValue("i", crc);
}
PyDoc_STRVAR(doc_crc32,
@@ -895,7 +895,7 @@ binascii_crc32(PyObject *self, PyObject *args)
int signed_val;
if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val))
- return NULL;
+ return NULL;
buf = (Byte*)pbuf.buf;
len = pbuf.len;
signed_val = crc32(crc32val, buf, len);
@@ -1024,26 +1024,26 @@ static unsigned int crc_32_tab[256] = {
static PyObject *
binascii_crc32(PyObject *self, PyObject *args)
{ /* By Jim Ahlstrom; All rights transferred to CNRI */
- Py_buffer pbin;
- unsigned char *bin_data;
- unsigned int crc = 0; /* initial value of CRC */
- Py_ssize_t len;
- unsigned int result;
-
- if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) )
- return NULL;
- bin_data = pbin.buf;
- len = pbin.len;
-
- crc = ~ crc;
- while (len-- > 0) {
- crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8);
- /* Note: (crc >> 8) MUST zero fill on left */
- }
-
- result = (crc ^ 0xFFFFFFFF);
- PyBuffer_Release(&pbin);
- return PyLong_FromUnsignedLong(result & 0xffffffff);
+ Py_buffer pbin;
+ unsigned char *bin_data;
+ unsigned int crc = 0; /* initial value of CRC */
+ Py_ssize_t len;
+ unsigned int result;
+
+ if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) )
+ return NULL;
+ bin_data = pbin.buf;
+ len = pbin.len;
+
+ crc = ~ crc;
+ while (len-- > 0) {
+ crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8);
+ /* Note: (crc >> 8) MUST zero fill on left */
+ }
+
+ result = (crc ^ 0xFFFFFFFF);
+ PyBuffer_Release(&pbin);
+ return PyLong_FromUnsignedLong(result & 0xffffffff);
}
#endif /* USE_ZLIB_CRC32 */
@@ -1051,43 +1051,43 @@ binascii_crc32(PyObject *self, PyObject *args)
static PyObject *
binascii_hexlify(PyObject *self, PyObject *args)
{
- Py_buffer parg;
- char* argbuf;
- Py_ssize_t arglen;
- PyObject *retval;
- char* retbuf;
- Py_ssize_t i, j;
-
- if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg))
- return NULL;
- argbuf = parg.buf;
- arglen = parg.len;
-
- assert(arglen >= 0);
- if (arglen > PY_SSIZE_T_MAX / 2) {
- PyBuffer_Release(&parg);
- return PyErr_NoMemory();
- }
-
- retval = PyBytes_FromStringAndSize(NULL, arglen*2);
- if (!retval) {
- PyBuffer_Release(&parg);
- return NULL;
- }
- retbuf = PyBytes_AS_STRING(retval);
-
- /* make hex version of string, taken from shamodule.c */
- for (i=j=0; i < arglen; i++) {
- char c;
- c = (argbuf[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
- retbuf[j++] = c;
- c = argbuf[i] & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
- retbuf[j++] = c;
- }
- PyBuffer_Release(&parg);
- return retval;
+ Py_buffer parg;
+ char* argbuf;
+ Py_ssize_t arglen;
+ PyObject *retval;
+ char* retbuf;
+ Py_ssize_t i, j;
+
+ if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg))
+ return NULL;
+ argbuf = parg.buf;
+ arglen = parg.len;
+
+ assert(arglen >= 0);
+ if (arglen > PY_SSIZE_T_MAX / 2) {
+ PyBuffer_Release(&parg);
+ return PyErr_NoMemory();
+ }
+
+ retval = PyBytes_FromStringAndSize(NULL, arglen*2);
+ if (!retval) {
+ PyBuffer_Release(&parg);
+ return NULL;
+ }
+ retbuf = PyBytes_AS_STRING(retval);
+
+ /* make hex version of string, taken from shamodule.c */
+ for (i=j=0; i < arglen; i++) {
+ char c;
+ c = (argbuf[i] >> 4) & 0xf;
+ c = (c>9) ? c+'a'-10 : c + '0';
+ retbuf[j++] = c;
+ c = argbuf[i] & 0xf;
+ c = (c>9) ? c+'a'-10 : c + '0';
+ retbuf[j++] = c;
+ }
+ PyBuffer_Release(&parg);
+ return retval;
}
PyDoc_STRVAR(doc_hexlify,
@@ -1099,69 +1099,69 @@ This function is also available as \"hexlify()\".");
static int
to_int(int c)
{
- if (isdigit(c))
- return c - '0';
- else {
- if (isupper(c))
- c = tolower(c);
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- }
- return -1;
+ if (isdigit(c))
+ return c - '0';
+ else {
+ if (isupper(c))
+ c = tolower(c);
+ if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ }
+ return -1;
}
static PyObject *
binascii_unhexlify(PyObject *self, PyObject *args)
{
- Py_buffer parg;
- char* argbuf;
- Py_ssize_t arglen;
- PyObject *retval;
- char* retbuf;
- Py_ssize_t i, j;
-
- if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg))
- return NULL;
- argbuf = parg.buf;
- arglen = parg.len;
-
- assert(arglen >= 0);
-
- /* XXX What should we do about strings with an odd length? Should
- * we add an implicit leading zero, or a trailing zero? For now,
- * raise an exception.
- */
- if (arglen % 2) {
- PyBuffer_Release(&parg);
- PyErr_SetString(Error, "Odd-length string");
- return NULL;
- }
-
- retval = PyBytes_FromStringAndSize(NULL, (arglen/2));
- if (!retval) {
- PyBuffer_Release(&parg);
- return NULL;
- }
- retbuf = PyBytes_AS_STRING(retval);
-
- for (i=j=0; i < arglen; i += 2) {
- int top = to_int(Py_CHARMASK(argbuf[i]));
- int bot = to_int(Py_CHARMASK(argbuf[i+1]));
- if (top == -1 || bot == -1) {
- PyErr_SetString(Error,
- "Non-hexadecimal digit found");
- goto finally;
- }
- retbuf[j++] = (top << 4) + bot;
- }
- PyBuffer_Release(&parg);
- return retval;
+ Py_buffer parg;
+ char* argbuf;
+ Py_ssize_t arglen;
+ PyObject *retval;
+ char* retbuf;
+ Py_ssize_t i, j;
+
+ if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg))
+ return NULL;
+ argbuf = parg.buf;
+ arglen = parg.len;
+
+ assert(arglen >= 0);
+
+ /* XXX What should we do about strings with an odd length? Should
+ * we add an implicit leading zero, or a trailing zero? For now,
+ * raise an exception.
+ */
+ if (arglen % 2) {
+ PyBuffer_Release(&parg);
+ PyErr_SetString(Error, "Odd-length string");
+ return NULL;
+ }
+
+ retval = PyBytes_FromStringAndSize(NULL, (arglen/2));
+ if (!retval) {
+ PyBuffer_Release(&parg);
+ return NULL;
+ }
+ retbuf = PyBytes_AS_STRING(retval);
+
+ for (i=j=0; i < arglen; i += 2) {
+ int top = to_int(Py_CHARMASK(argbuf[i]));
+ int bot = to_int(Py_CHARMASK(argbuf[i+1]));
+ if (top == -1 || bot == -1) {
+ PyErr_SetString(Error,
+ "Non-hexadecimal digit found");
+ goto finally;
+ }
+ retbuf[j++] = (top << 4) + bot;
+ }
+ PyBuffer_Release(&parg);
+ return retval;
finally:
- PyBuffer_Release(&parg);
- Py_DECREF(retval);
- return NULL;
+ PyBuffer_Release(&parg);
+ Py_DECREF(retval);
+ return NULL;
}
PyDoc_STRVAR(doc_unhexlify,
@@ -1190,96 +1190,96 @@ PyDoc_STRVAR(doc_a2b_qp, "Decode a string of qp-encoded data");
static PyObject*
binascii_a2b_qp(PyObject *self, PyObject *args, PyObject *kwargs)
{
- Py_ssize_t in, out;
- char ch;
- Py_buffer pdata;
- unsigned char *data, *odata;
- Py_ssize_t datalen = 0;
- PyObject *rv;
- static char *kwlist[] = {"data", "header", NULL};
- int header = 0;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata,
- &header))
- return NULL;
- data = pdata.buf;
- datalen = pdata.len;
-
- /* We allocate the output same size as input, this is overkill.
- * The previous implementation used calloc() so we'll zero out the
- * memory here too, since PyMem_Malloc() does not guarantee that.
- */
- odata = (unsigned char *) PyMem_Malloc(datalen);
- if (odata == NULL) {
- PyBuffer_Release(&pdata);
- PyErr_NoMemory();
- return NULL;
- }
- memset(odata, 0, datalen);
-
- in = out = 0;
- while (in < datalen) {
- if (data[in] == '=') {
- in++;
- if (in >= datalen) break;
- /* Soft line breaks */
- if ((data[in] == '\n') || (data[in] == '\r')) {
- if (data[in] != '\n') {
- while (in < datalen && data[in] != '\n') in++;
- }
- if (in < datalen) in++;
- }
- else if (data[in] == '=') {
- /* broken case from broken python qp */
- odata[out++] = '=';
- in++;
- }
- else if (((data[in] >= 'A' && data[in] <= 'F') ||
- (data[in] >= 'a' && data[in] <= 'f') ||
- (data[in] >= '0' && data[in] <= '9')) &&
- ((data[in+1] >= 'A' && data[in+1] <= 'F') ||
- (data[in+1] >= 'a' && data[in+1] <= 'f') ||
- (data[in+1] >= '0' && data[in+1] <= '9'))) {
- /* hexval */
- ch = hexval(data[in]) << 4;
- in++;
- ch |= hexval(data[in]);
- in++;
- odata[out++] = ch;
- }
- else {
- odata[out++] = '=';
- }
- }
- else if (header && data[in] == '_') {
- odata[out++] = ' ';
- in++;
- }
- else {
- odata[out] = data[in];
- in++;
- out++;
- }
- }
- if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return NULL;
- }
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return rv;
+ Py_ssize_t in, out;
+ char ch;
+ Py_buffer pdata;
+ unsigned char *data, *odata;
+ Py_ssize_t datalen = 0;
+ PyObject *rv;
+ static char *kwlist[] = {"data", "header", NULL};
+ int header = 0;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata,
+ &header))
+ return NULL;
+ data = pdata.buf;
+ datalen = pdata.len;
+
+ /* We allocate the output same size as input, this is overkill.
+ * The previous implementation used calloc() so we'll zero out the
+ * memory here too, since PyMem_Malloc() does not guarantee that.
+ */
+ odata = (unsigned char *) PyMem_Malloc(datalen);
+ if (odata == NULL) {
+ PyBuffer_Release(&pdata);
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(odata, 0, datalen);
+
+ in = out = 0;
+ while (in < datalen) {
+ if (data[in] == '=') {
+ in++;
+ if (in >= datalen) break;
+ /* Soft line breaks */
+ if ((data[in] == '\n') || (data[in] == '\r')) {
+ if (data[in] != '\n') {
+ while (in < datalen && data[in] != '\n') in++;
+ }
+ if (in < datalen) in++;
+ }
+ else if (data[in] == '=') {
+ /* broken case from broken python qp */
+ odata[out++] = '=';
+ in++;
+ }
+ else if (((data[in] >= 'A' && data[in] <= 'F') ||
+ (data[in] >= 'a' && data[in] <= 'f') ||
+ (data[in] >= '0' && data[in] <= '9')) &&
+ ((data[in+1] >= 'A' && data[in+1] <= 'F') ||
+ (data[in+1] >= 'a' && data[in+1] <= 'f') ||
+ (data[in+1] >= '0' && data[in+1] <= '9'))) {
+ /* hexval */
+ ch = hexval(data[in]) << 4;
+ in++;
+ ch |= hexval(data[in]);
+ in++;
+ odata[out++] = ch;
+ }
+ else {
+ odata[out++] = '=';
+ }
+ }
+ else if (header && data[in] == '_') {
+ odata[out++] = ' ';
+ in++;
+ }
+ else {
+ odata[out] = data[in];
+ in++;
+ out++;
+ }
+ }
+ if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return NULL;
+ }
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return rv;
}
static int
to_hex (unsigned char ch, unsigned char *s)
{
- unsigned int uvalue = ch;
+ unsigned int uvalue = ch;
- s[1] = "0123456789ABCDEF"[uvalue % 16];
- uvalue = (uvalue / 16);
- s[0] = "0123456789ABCDEF"[uvalue % 16];
- return 0;
+ s[1] = "0123456789ABCDEF"[uvalue % 16];
+ uvalue = (uvalue / 16);
+ s[0] = "0123456789ABCDEF"[uvalue % 16];
+ return 0;
}
PyDoc_STRVAR(doc_b2a_qp,
@@ -1296,210 +1296,210 @@ both encoded. When quotetabs is set, space and tabs are encoded.");
static PyObject*
binascii_b2a_qp (PyObject *self, PyObject *args, PyObject *kwargs)
{
- Py_ssize_t in, out;
- Py_buffer pdata;
- unsigned char *data, *odata;
- Py_ssize_t datalen = 0, odatalen = 0;
- PyObject *rv;
- unsigned int linelen = 0;
- static char *kwlist[] = {"data", "quotetabs", "istext",
- "header", NULL};
- int istext = 1;
- int quotetabs = 0;
- int header = 0;
- unsigned char ch;
- int crlf = 0;
- unsigned char *p;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata,
- &quotetabs, &istext, &header))
- return NULL;
- data = pdata.buf;
- datalen = pdata.len;
-
- /* See if this string is using CRLF line ends */
- /* XXX: this function has the side effect of converting all of
- * the end of lines to be the same depending on this detection
- * here */
- p = (unsigned char *) memchr(data, '\n', datalen);
- if ((p != NULL) && (p > data) && (*(p-1) == '\r'))
- crlf = 1;
-
- /* First, scan to see how many characters need to be encoded */
- in = 0;
- while (in < datalen) {
- if ((data[in] > 126) ||
- (data[in] == '=') ||
- (header && data[in] == '_') ||
- ((data[in] == '.') && (linelen == 0) &&
- (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
- (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
- ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
- ((data[in] < 33) &&
- (data[in] != '\r') && (data[in] != '\n') &&
- (quotetabs ||
- (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
- {
- if ((linelen + 3) >= MAXLINESIZE) {
- linelen = 0;
- if (crlf)
- odatalen += 3;
- else
- odatalen += 2;
- }
- linelen += 3;
- odatalen += 3;
- in++;
- }
- else {
- if (istext &&
- ((data[in] == '\n') ||
- ((in+1 < datalen) && (data[in] == '\r') &&
- (data[in+1] == '\n'))))
- {
- linelen = 0;
- /* Protect against whitespace on end of line */
- if (in && ((data[in-1] == ' ') || (data[in-1] == '\t')))
- odatalen += 2;
- if (crlf)
- odatalen += 2;
- else
- odatalen += 1;
- if (data[in] == '\r')
- in += 2;
- else
- in++;
- }
- else {
- if ((in + 1 != datalen) &&
- (data[in+1] != '\n') &&
- (linelen + 1) >= MAXLINESIZE) {
- linelen = 0;
- if (crlf)
- odatalen += 3;
- else
- odatalen += 2;
- }
- linelen++;
- odatalen++;
- in++;
- }
- }
- }
-
- /* We allocate the output same size as input, this is overkill.
- * The previous implementation used calloc() so we'll zero out the
- * memory here too, since PyMem_Malloc() does not guarantee that.
- */
- odata = (unsigned char *) PyMem_Malloc(odatalen);
- if (odata == NULL) {
- PyBuffer_Release(&pdata);
- PyErr_NoMemory();
- return NULL;
- }
- memset(odata, 0, odatalen);
-
- in = out = linelen = 0;
- while (in < datalen) {
- if ((data[in] > 126) ||
- (data[in] == '=') ||
- (header && data[in] == '_') ||
- ((data[in] == '.') && (linelen == 0) &&
- (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
- (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
- ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
- ((data[in] < 33) &&
- (data[in] != '\r') && (data[in] != '\n') &&
- (quotetabs ||
- (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
- {
- if ((linelen + 3 )>= MAXLINESIZE) {
- odata[out++] = '=';
- if (crlf) odata[out++] = '\r';
- odata[out++] = '\n';
- linelen = 0;
- }
- odata[out++] = '=';
- to_hex(data[in], &odata[out]);
- out += 2;
- in++;
- linelen += 3;
- }
- else {
- if (istext &&
- ((data[in] == '\n') ||
- ((in+1 < datalen) && (data[in] == '\r') &&
- (data[in+1] == '\n'))))
- {
- linelen = 0;
- /* Protect against whitespace on end of line */
- if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) {
- ch = odata[out-1];
- odata[out-1] = '=';
- to_hex(ch, &odata[out]);
- out += 2;
- }
-
- if (crlf) odata[out++] = '\r';
- odata[out++] = '\n';
- if (data[in] == '\r')
- in += 2;
- else
- in++;
- }
- else {
- if ((in + 1 != datalen) &&
- (data[in+1] != '\n') &&
- (linelen + 1) >= MAXLINESIZE) {
- odata[out++] = '=';
- if (crlf) odata[out++] = '\r';
- odata[out++] = '\n';
- linelen = 0;
- }
- linelen++;
- if (header && data[in] == ' ') {
- odata[out++] = '_';
- in++;
- }
- else {
- odata[out++] = data[in++];
- }
- }
- }
- }
- if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return NULL;
- }
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return rv;
+ Py_ssize_t in, out;
+ Py_buffer pdata;
+ unsigned char *data, *odata;
+ Py_ssize_t datalen = 0, odatalen = 0;
+ PyObject *rv;
+ unsigned int linelen = 0;
+ static char *kwlist[] = {"data", "quotetabs", "istext",
+ "header", NULL};
+ int istext = 1;
+ int quotetabs = 0;
+ int header = 0;
+ unsigned char ch;
+ int crlf = 0;
+ unsigned char *p;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata,
+ &quotetabs, &istext, &header))
+ return NULL;
+ data = pdata.buf;
+ datalen = pdata.len;
+
+ /* See if this string is using CRLF line ends */
+ /* XXX: this function has the side effect of converting all of
+ * the end of lines to be the same depending on this detection
+ * here */
+ p = (unsigned char *) memchr(data, '\n', datalen);
+ if ((p != NULL) && (p > data) && (*(p-1) == '\r'))
+ crlf = 1;
+
+ /* First, scan to see how many characters need to be encoded */
+ in = 0;
+ while (in < datalen) {
+ if ((data[in] > 126) ||
+ (data[in] == '=') ||
+ (header && data[in] == '_') ||
+ ((data[in] == '.') && (linelen == 0) &&
+ (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
+ (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
+ ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
+ ((data[in] < 33) &&
+ (data[in] != '\r') && (data[in] != '\n') &&
+ (quotetabs ||
+ (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
+ {
+ if ((linelen + 3) >= MAXLINESIZE) {
+ linelen = 0;
+ if (crlf)
+ odatalen += 3;
+ else
+ odatalen += 2;
+ }
+ linelen += 3;
+ odatalen += 3;
+ in++;
+ }
+ else {
+ if (istext &&
+ ((data[in] == '\n') ||
+ ((in+1 < datalen) && (data[in] == '\r') &&
+ (data[in+1] == '\n'))))
+ {
+ linelen = 0;
+ /* Protect against whitespace on end of line */
+ if (in && ((data[in-1] == ' ') || (data[in-1] == '\t')))
+ odatalen += 2;
+ if (crlf)
+ odatalen += 2;
+ else
+ odatalen += 1;
+ if (data[in] == '\r')
+ in += 2;
+ else
+ in++;
+ }
+ else {
+ if ((in + 1 != datalen) &&
+ (data[in+1] != '\n') &&
+ (linelen + 1) >= MAXLINESIZE) {
+ linelen = 0;
+ if (crlf)
+ odatalen += 3;
+ else
+ odatalen += 2;
+ }
+ linelen++;
+ odatalen++;
+ in++;
+ }
+ }
+ }
+
+ /* We allocate the output same size as input, this is overkill.
+ * The previous implementation used calloc() so we'll zero out the
+ * memory here too, since PyMem_Malloc() does not guarantee that.
+ */
+ odata = (unsigned char *) PyMem_Malloc(odatalen);
+ if (odata == NULL) {
+ PyBuffer_Release(&pdata);
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(odata, 0, odatalen);
+
+ in = out = linelen = 0;
+ while (in < datalen) {
+ if ((data[in] > 126) ||
+ (data[in] == '=') ||
+ (header && data[in] == '_') ||
+ ((data[in] == '.') && (linelen == 0) &&
+ (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
+ (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
+ ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
+ ((data[in] < 33) &&
+ (data[in] != '\r') && (data[in] != '\n') &&
+ (quotetabs ||
+ (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
+ {
+ if ((linelen + 3 )>= MAXLINESIZE) {
+ odata[out++] = '=';
+ if (crlf) odata[out++] = '\r';
+ odata[out++] = '\n';
+ linelen = 0;
+ }
+ odata[out++] = '=';
+ to_hex(data[in], &odata[out]);
+ out += 2;
+ in++;
+ linelen += 3;
+ }
+ else {
+ if (istext &&
+ ((data[in] == '\n') ||
+ ((in+1 < datalen) && (data[in] == '\r') &&
+ (data[in+1] == '\n'))))
+ {
+ linelen = 0;
+ /* Protect against whitespace on end of line */
+ if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) {
+ ch = odata[out-1];
+ odata[out-1] = '=';
+ to_hex(ch, &odata[out]);
+ out += 2;
+ }
+
+ if (crlf) odata[out++] = '\r';
+ odata[out++] = '\n';
+ if (data[in] == '\r')
+ in += 2;
+ else
+ in++;
+ }
+ else {
+ if ((in + 1 != datalen) &&
+ (data[in+1] != '\n') &&
+ (linelen + 1) >= MAXLINESIZE) {
+ odata[out++] = '=';
+ if (crlf) odata[out++] = '\r';
+ odata[out++] = '\n';
+ linelen = 0;
+ }
+ linelen++;
+ if (header && data[in] == ' ') {
+ odata[out++] = '_';
+ in++;
+ }
+ else {
+ odata[out++] = data[in++];
+ }
+ }
+ }
+ }
+ if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return NULL;
+ }
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return rv;
}
/* List of functions defined in the module */
static struct PyMethodDef binascii_module_methods[] = {
- {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu},
- {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu},
- {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64},
- {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64},
- {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx},
- {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx},
- {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify},
- {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
- {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify},
- {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
- {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx},
- {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS,
- doc_rledecode_hqx},
- {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx},
- {"crc32", binascii_crc32, METH_VARARGS, doc_crc32},
- {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS,
- doc_a2b_qp},
- {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS,
- doc_b2a_qp},
- {NULL, NULL} /* sentinel */
+ {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu},
+ {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu},
+ {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64},
+ {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64},
+ {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx},
+ {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx},
+ {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify},
+ {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
+ {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify},
+ {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
+ {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx},
+ {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS,
+ doc_rledecode_hqx},
+ {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx},
+ {"crc32", binascii_crc32, METH_VARARGS, doc_crc32},
+ {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS,
+ doc_a2b_qp},
+ {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS,
+ doc_b2a_qp},
+ {NULL, NULL} /* sentinel */
};
@@ -1508,36 +1508,36 @@ PyDoc_STRVAR(doc_binascii, "Conversion between binary data and ASCII");
static struct PyModuleDef binasciimodule = {
- PyModuleDef_HEAD_INIT,
- "binascii",
- doc_binascii,
- -1,
- binascii_module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "binascii",
+ doc_binascii,
+ -1,
+ binascii_module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_binascii(void)
{
- PyObject *m, *d;
-
- /* Create the module and add the functions */
- m = PyModule_Create(&binasciimodule);
- if (m == NULL)
- return NULL;
-
- d = PyModule_GetDict(m);
-
- Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL);
- PyDict_SetItemString(d, "Error", Error);
- Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
- PyDict_SetItemString(d, "Incomplete", Incomplete);
- if (PyErr_Occurred()) {
- Py_DECREF(m);
- m = NULL;
- }
- return m;
+ PyObject *m, *d;
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&binasciimodule);
+ if (m == NULL)
+ return NULL;
+
+ d = PyModule_GetDict(m);
+
+ Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL);
+ PyDict_SetItemString(d, "Error", Error);
+ Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
+ PyDict_SetItemString(d, "Incomplete", Incomplete);
+ if (PyErr_Occurred()) {
+ Py_DECREF(m);
+ m = NULL;
+ }
+ return m;
}
diff --git a/Modules/bz2module.c b/Modules/bz2module.c
index f0ddf5c..29f8592 100644
--- a/Modules/bz2module.c
+++ b/Modules/bz2module.c
@@ -41,20 +41,20 @@ typedef fpos_t Py_off_t;
#define MODE_READ_EOF 2
#define MODE_WRITE 3
-#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type)
+#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type)
#ifdef BZ_CONFIG_ERROR
#if SIZEOF_LONG >= 8
#define BZS_TOTAL_OUT(bzs) \
- (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
+ (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
#elif SIZEOF_LONG_LONG >= 8
#define BZS_TOTAL_OUT(bzs) \
- (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
+ (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
#else
#define BZS_TOTAL_OUT(bzs) \
- bzs->total_out_lo32
+ bzs->total_out_lo32
#endif
#else /* ! BZ_CONFIG_ERROR */
@@ -79,11 +79,11 @@ typedef fpos_t Py_off_t;
#ifdef WITH_THREAD
#define ACQUIRE_LOCK(obj) do { \
- if (!PyThread_acquire_lock(obj->lock, 0)) { \
- Py_BEGIN_ALLOW_THREADS \
- PyThread_acquire_lock(obj->lock, 1); \
- Py_END_ALLOW_THREADS \
- } } while(0)
+ if (!PyThread_acquire_lock(obj->lock, 0)) { \
+ Py_BEGIN_ALLOW_THREADS \
+ PyThread_acquire_lock(obj->lock, 1); \
+ Py_END_ALLOW_THREADS \
+ } } while(0)
#define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock)
#else
#define ACQUIRE_LOCK(obj)
@@ -91,47 +91,47 @@ typedef fpos_t Py_off_t;
#endif
/* Bits in f_newlinetypes */
-#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
-#define NEWLINE_CR 1 /* \r newline seen */
-#define NEWLINE_LF 2 /* \n newline seen */
-#define NEWLINE_CRLF 4 /* \r\n newline seen */
+#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
+#define NEWLINE_CR 1 /* \r newline seen */
+#define NEWLINE_LF 2 /* \n newline seen */
+#define NEWLINE_CRLF 4 /* \r\n newline seen */
/* ===================================================================== */
/* Structure definitions. */
typedef struct {
- PyObject_HEAD
- FILE *rawfp;
+ PyObject_HEAD
+ FILE *rawfp;
- char* f_buf; /* Allocated readahead buffer */
- char* f_bufend; /* Points after last occupied position */
- char* f_bufptr; /* Current buffer position */
+ char* f_buf; /* Allocated readahead buffer */
+ char* f_bufend; /* Points after last occupied position */
+ char* f_bufptr; /* Current buffer position */
- BZFILE *fp;
- int mode;
- Py_off_t pos;
- Py_off_t size;
+ BZFILE *fp;
+ int mode;
+ Py_off_t pos;
+ Py_off_t size;
#ifdef WITH_THREAD
- PyThread_type_lock lock;
+ PyThread_type_lock lock;
#endif
} BZ2FileObject;
typedef struct {
- PyObject_HEAD
- bz_stream bzs;
- int running;
+ PyObject_HEAD
+ bz_stream bzs;
+ int running;
#ifdef WITH_THREAD
- PyThread_type_lock lock;
+ PyThread_type_lock lock;
#endif
} BZ2CompObject;
typedef struct {
- PyObject_HEAD
- bz_stream bzs;
- int running;
- PyObject *unused_data;
+ PyObject_HEAD
+ bz_stream bzs;
+ int running;
+ PyObject *unused_data;
#ifdef WITH_THREAD
- PyThread_type_lock lock;
+ PyThread_type_lock lock;
#endif
} BZ2DecompObject;
@@ -141,59 +141,59 @@ typedef struct {
static int
Util_CatchBZ2Error(int bzerror)
{
- int ret = 0;
- switch(bzerror) {
- case BZ_OK:
- case BZ_STREAM_END:
- break;
+ int ret = 0;
+ switch(bzerror) {
+ case BZ_OK:
+ case BZ_STREAM_END:
+ break;
#ifdef BZ_CONFIG_ERROR
- case BZ_CONFIG_ERROR:
- PyErr_SetString(PyExc_SystemError,
- "the bz2 library was not compiled "
- "correctly");
- ret = 1;
- break;
+ case BZ_CONFIG_ERROR:
+ PyErr_SetString(PyExc_SystemError,
+ "the bz2 library was not compiled "
+ "correctly");
+ ret = 1;
+ break;
#endif
- case BZ_PARAM_ERROR:
- PyErr_SetString(PyExc_ValueError,
- "the bz2 library has received wrong "
- "parameters");
- ret = 1;
- break;
-
- case BZ_MEM_ERROR:
- PyErr_NoMemory();
- ret = 1;
- break;
-
- case BZ_DATA_ERROR:
- case BZ_DATA_ERROR_MAGIC:
- PyErr_SetString(PyExc_IOError, "invalid data stream");
- ret = 1;
- break;
-
- case BZ_IO_ERROR:
- PyErr_SetString(PyExc_IOError, "unknown IO error");
- ret = 1;
- break;
-
- case BZ_UNEXPECTED_EOF:
- PyErr_SetString(PyExc_EOFError,
- "compressed file ended before the "
- "logical end-of-stream was detected");
- ret = 1;
- break;
-
- case BZ_SEQUENCE_ERROR:
- PyErr_SetString(PyExc_RuntimeError,
- "wrong sequence of bz2 library "
- "commands used");
- ret = 1;
- break;
- }
- return ret;
+ case BZ_PARAM_ERROR:
+ PyErr_SetString(PyExc_ValueError,
+ "the bz2 library has received wrong "
+ "parameters");
+ ret = 1;
+ break;
+
+ case BZ_MEM_ERROR:
+ PyErr_NoMemory();
+ ret = 1;
+ break;
+
+ case BZ_DATA_ERROR:
+ case BZ_DATA_ERROR_MAGIC:
+ PyErr_SetString(PyExc_IOError, "invalid data stream");
+ ret = 1;
+ break;
+
+ case BZ_IO_ERROR:
+ PyErr_SetString(PyExc_IOError, "unknown IO error");
+ ret = 1;
+ break;
+
+ case BZ_UNEXPECTED_EOF:
+ PyErr_SetString(PyExc_EOFError,
+ "compressed file ended before the "
+ "logical end-of-stream was detected");
+ ret = 1;
+ break;
+
+ case BZ_SEQUENCE_ERROR:
+ PyErr_SetString(PyExc_RuntimeError,
+ "wrong sequence of bz2 library "
+ "commands used");
+ ret = 1;
+ break;
+ }
+ return ret;
}
#if BUFSIZ < 8192
@@ -212,134 +212,134 @@ Util_CatchBZ2Error(int bzerror)
static size_t
Util_NewBufferSize(size_t currentsize)
{
- if (currentsize > SMALLCHUNK) {
- /* Keep doubling until we reach BIGCHUNK;
- then keep adding BIGCHUNK. */
- if (currentsize <= BIGCHUNK)
- return currentsize + currentsize;
- else
- return currentsize + BIGCHUNK;
- }
- return currentsize + SMALLCHUNK;
+ if (currentsize > SMALLCHUNK) {
+ /* Keep doubling until we reach BIGCHUNK;
+ then keep adding BIGCHUNK. */
+ if (currentsize <= BIGCHUNK)
+ return currentsize + currentsize;
+ else
+ return currentsize + BIGCHUNK;
+ }
+ return currentsize + SMALLCHUNK;
}
/* This is a hacked version of Python's fileobject.c:get_line(). */
static PyObject *
Util_GetLine(BZ2FileObject *f, int n)
{
- char c;
- char *buf, *end;
- size_t total_v_size; /* total # of slots in buffer */
- size_t used_v_size; /* # used slots in buffer */
- size_t increment; /* amount to increment the buffer */
- PyObject *v;
- int bzerror;
- int bytes_read;
-
- total_v_size = n > 0 ? n : 100;
- v = PyBytes_FromStringAndSize((char *)NULL, total_v_size);
- if (v == NULL)
- return NULL;
-
- buf = BUF(v);
- end = buf + total_v_size;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- do {
- bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
- f->pos++;
- if (bytes_read == 0)
- break;
- *buf++ = c;
- } while (bzerror == BZ_OK && c != '\n' && buf != end);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- f->size = f->pos;
- f->mode = MODE_READ_EOF;
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_DECREF(v);
- return NULL;
- }
- if (c == '\n')
- break;
- /* Must be because buf == end */
- if (n > 0)
- break;
- used_v_size = total_v_size;
- increment = total_v_size >> 2; /* mild exponential growth */
- total_v_size += increment;
- if (total_v_size > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- Py_DECREF(v);
- return NULL;
- }
- if (_PyBytes_Resize(&v, total_v_size) < 0) {
- return NULL;
- }
- buf = BUF(v) + used_v_size;
- end = BUF(v) + total_v_size;
- }
-
- used_v_size = buf - BUF(v);
- if (used_v_size != total_v_size) {
- if (_PyBytes_Resize(&v, used_v_size) < 0) {
- v = NULL;
- }
- }
- return v;
+ char c;
+ char *buf, *end;
+ size_t total_v_size; /* total # of slots in buffer */
+ size_t used_v_size; /* # used slots in buffer */
+ size_t increment; /* amount to increment the buffer */
+ PyObject *v;
+ int bzerror;
+ int bytes_read;
+
+ total_v_size = n > 0 ? n : 100;
+ v = PyBytes_FromStringAndSize((char *)NULL, total_v_size);
+ if (v == NULL)
+ return NULL;
+
+ buf = BUF(v);
+ end = buf + total_v_size;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ do {
+ bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
+ f->pos++;
+ if (bytes_read == 0)
+ break;
+ *buf++ = c;
+ } while (bzerror == BZ_OK && c != '\n' && buf != end);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ f->size = f->pos;
+ f->mode = MODE_READ_EOF;
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (c == '\n')
+ break;
+ /* Must be because buf == end */
+ if (n > 0)
+ break;
+ used_v_size = total_v_size;
+ increment = total_v_size >> 2; /* mild exponential growth */
+ total_v_size += increment;
+ if (total_v_size > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (_PyBytes_Resize(&v, total_v_size) < 0) {
+ return NULL;
+ }
+ buf = BUF(v) + used_v_size;
+ end = BUF(v) + total_v_size;
+ }
+
+ used_v_size = buf - BUF(v);
+ if (used_v_size != total_v_size) {
+ if (_PyBytes_Resize(&v, used_v_size) < 0) {
+ v = NULL;
+ }
+ }
+ return v;
}
/* This is a hacked version of Python's fileobject.c:drop_readahead(). */
static void
Util_DropReadAhead(BZ2FileObject *f)
{
- if (f->f_buf != NULL) {
- PyMem_Free(f->f_buf);
- f->f_buf = NULL;
- }
+ if (f->f_buf != NULL) {
+ PyMem_Free(f->f_buf);
+ f->f_buf = NULL;
+ }
}
/* This is a hacked version of Python's fileobject.c:readahead(). */
static int
Util_ReadAhead(BZ2FileObject *f, int bufsize)
{
- int chunksize;
- int bzerror;
-
- if (f->f_buf != NULL) {
- if((f->f_bufend - f->f_bufptr) >= 1)
- return 0;
- else
- Util_DropReadAhead(f);
- }
- if (f->mode == MODE_READ_EOF) {
- f->f_bufptr = f->f_buf;
- f->f_bufend = f->f_buf;
- return 0;
- }
- if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- Py_BEGIN_ALLOW_THREADS
- chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize);
- Py_END_ALLOW_THREADS
- f->pos += chunksize;
- if (bzerror == BZ_STREAM_END) {
- f->size = f->pos;
- f->mode = MODE_READ_EOF;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Util_DropReadAhead(f);
- return -1;
- }
- f->f_bufptr = f->f_buf;
- f->f_bufend = f->f_buf + chunksize;
- return 0;
+ int chunksize;
+ int bzerror;
+
+ if (f->f_buf != NULL) {
+ if((f->f_bufend - f->f_bufptr) >= 1)
+ return 0;
+ else
+ Util_DropReadAhead(f);
+ }
+ if (f->mode == MODE_READ_EOF) {
+ f->f_bufptr = f->f_buf;
+ f->f_bufend = f->f_buf;
+ return 0;
+ }
+ if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize);
+ Py_END_ALLOW_THREADS
+ f->pos += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ f->size = f->pos;
+ f->mode = MODE_READ_EOF;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Util_DropReadAhead(f);
+ return -1;
+ }
+ f->f_bufptr = f->f_buf;
+ f->f_bufend = f->f_buf + chunksize;
+ return 0;
}
/* This is a hacked version of Python's
@@ -347,45 +347,45 @@ Util_ReadAhead(BZ2FileObject *f, int bufsize)
static PyBytesObject *
Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize)
{
- PyBytesObject* s;
- char *bufptr;
- char *buf;
- int len;
-
- if (f->f_buf == NULL)
- if (Util_ReadAhead(f, bufsize) < 0)
- return NULL;
-
- len = f->f_bufend - f->f_bufptr;
- if (len == 0)
- return (PyBytesObject *)
- PyBytes_FromStringAndSize(NULL, skip);
- bufptr = memchr(f->f_bufptr, '\n', len);
- if (bufptr != NULL) {
- bufptr++; /* Count the '\n' */
- len = bufptr - f->f_bufptr;
- s = (PyBytesObject *)
- PyBytes_FromStringAndSize(NULL, skip+len);
- if (s == NULL)
- return NULL;
- memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len);
- f->f_bufptr = bufptr;
- if (bufptr == f->f_bufend)
- Util_DropReadAhead(f);
- } else {
- bufptr = f->f_bufptr;
- buf = f->f_buf;
- f->f_buf = NULL; /* Force new readahead buffer */
- s = Util_ReadAheadGetLineSkip(f, skip+len,
- bufsize + (bufsize>>2));
- if (s == NULL) {
- PyMem_Free(buf);
- return NULL;
- }
- memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len);
- PyMem_Free(buf);
- }
- return s;
+ PyBytesObject* s;
+ char *bufptr;
+ char *buf;
+ int len;
+
+ if (f->f_buf == NULL)
+ if (Util_ReadAhead(f, bufsize) < 0)
+ return NULL;
+
+ len = f->f_bufend - f->f_bufptr;
+ if (len == 0)
+ return (PyBytesObject *)
+ PyBytes_FromStringAndSize(NULL, skip);
+ bufptr = memchr(f->f_bufptr, '\n', len);
+ if (bufptr != NULL) {
+ bufptr++; /* Count the '\n' */
+ len = bufptr - f->f_bufptr;
+ s = (PyBytesObject *)
+ PyBytes_FromStringAndSize(NULL, skip+len);
+ if (s == NULL)
+ return NULL;
+ memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len);
+ f->f_bufptr = bufptr;
+ if (bufptr == f->f_bufend)
+ Util_DropReadAhead(f);
+ } else {
+ bufptr = f->f_bufptr;
+ buf = f->f_buf;
+ f->f_buf = NULL; /* Force new readahead buffer */
+ s = Util_ReadAheadGetLineSkip(f, skip+len,
+ bufsize + (bufsize>>2));
+ if (s == NULL) {
+ PyMem_Free(buf);
+ return NULL;
+ }
+ memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len);
+ PyMem_Free(buf);
+ }
+ return s;
}
/* ===================================================================== */
@@ -402,83 +402,83 @@ argument is negative or omitted, read until EOF is reached.\n\
static PyObject *
BZ2File_read(BZ2FileObject *self, PyObject *args)
{
- long bytesrequested = -1;
- size_t bytesread, buffersize, chunksize;
- int bzerror;
- PyObject *ret = NULL;
-
- if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
- return NULL;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- break;
- case MODE_READ_EOF:
- ret = PyBytes_FromStringAndSize("", 0);
- goto cleanup;
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for reading");
- goto cleanup;
- }
-
- if (bytesrequested < 0)
- buffersize = Util_NewBufferSize((size_t)0);
- else
- buffersize = bytesrequested;
- if (buffersize > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "requested number of bytes is "
- "more than a Python string can hold");
- goto cleanup;
- }
- ret = PyBytes_FromStringAndSize((char *)NULL, buffersize);
- if (ret == NULL || buffersize == 0)
- goto cleanup;
- bytesread = 0;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- chunksize = BZ2_bzRead(&bzerror, self->fp,
- BUF(ret)+bytesread,
- buffersize-bytesread);
- self->pos += chunksize;
- Py_END_ALLOW_THREADS
- bytesread += chunksize;
- if (bzerror == BZ_STREAM_END) {
- self->size = self->pos;
- self->mode = MODE_READ_EOF;
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_DECREF(ret);
- ret = NULL;
- goto cleanup;
- }
- if (bytesrequested < 0) {
- buffersize = Util_NewBufferSize(buffersize);
- if (_PyBytes_Resize(&ret, buffersize) < 0) {
- ret = NULL;
- goto cleanup;
- }
- } else {
- break;
- }
- }
- if (bytesread != buffersize) {
- if (_PyBytes_Resize(&ret, bytesread) < 0) {
- ret = NULL;
- }
- }
+ long bytesrequested = -1;
+ size_t bytesread, buffersize, chunksize;
+ int bzerror;
+ PyObject *ret = NULL;
+
+ if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ break;
+ case MODE_READ_EOF:
+ ret = PyBytes_FromStringAndSize("", 0);
+ goto cleanup;
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for reading");
+ goto cleanup;
+ }
+
+ if (bytesrequested < 0)
+ buffersize = Util_NewBufferSize((size_t)0);
+ else
+ buffersize = bytesrequested;
+ if (buffersize > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "requested number of bytes is "
+ "more than a Python string can hold");
+ goto cleanup;
+ }
+ ret = PyBytes_FromStringAndSize((char *)NULL, buffersize);
+ if (ret == NULL || buffersize == 0)
+ goto cleanup;
+ bytesread = 0;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = BZ2_bzRead(&bzerror, self->fp,
+ BUF(ret)+bytesread,
+ buffersize-bytesread);
+ self->pos += chunksize;
+ Py_END_ALLOW_THREADS
+ bytesread += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ self->size = self->pos;
+ self->mode = MODE_READ_EOF;
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_DECREF(ret);
+ ret = NULL;
+ goto cleanup;
+ }
+ if (bytesrequested < 0) {
+ buffersize = Util_NewBufferSize(buffersize);
+ if (_PyBytes_Resize(&ret, buffersize) < 0) {
+ ret = NULL;
+ goto cleanup;
+ }
+ } else {
+ break;
+ }
+ }
+ if (bytesread != buffersize) {
+ if (_PyBytes_Resize(&ret, bytesread) < 0) {
+ ret = NULL;
+ }
+ }
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_readline__doc__,
@@ -493,37 +493,37 @@ string at EOF.\n\
static PyObject *
BZ2File_readline(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = NULL;
- int sizehint = -1;
-
- if (!PyArg_ParseTuple(args, "|i:readline", &sizehint))
- return NULL;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- break;
- case MODE_READ_EOF:
- ret = PyBytes_FromStringAndSize("", 0);
- goto cleanup;
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for reading");
- goto cleanup;
- }
-
- if (sizehint == 0)
- ret = PyBytes_FromStringAndSize("", 0);
- else
- ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint);
+ PyObject *ret = NULL;
+ int sizehint = -1;
+
+ if (!PyArg_ParseTuple(args, "|i:readline", &sizehint))
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ break;
+ case MODE_READ_EOF:
+ ret = PyBytes_FromStringAndSize("", 0);
+ goto cleanup;
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for reading");
+ goto cleanup;
+ }
+
+ if (sizehint == 0)
+ ret = PyBytes_FromStringAndSize("", 0);
+ else
+ ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint);
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_readlines__doc__,
@@ -538,150 +538,150 @@ total number of bytes in the lines returned.\n\
static PyObject *
BZ2File_readlines(BZ2FileObject *self, PyObject *args)
{
- long sizehint = 0;
- PyObject *list = NULL;
- PyObject *line;
- char small_buffer[SMALLCHUNK];
- char *buffer = small_buffer;
- size_t buffersize = SMALLCHUNK;
- PyObject *big_buffer = NULL;
- size_t nfilled = 0;
- size_t nread;
- size_t totalread = 0;
- char *p, *q, *end;
- int err;
- int shortread = 0;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
- return NULL;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- break;
- case MODE_READ_EOF:
- list = PyList_New(0);
- goto cleanup;
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for reading");
- goto cleanup;
- }
-
- if ((list = PyList_New(0)) == NULL)
- goto cleanup;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- nread = BZ2_bzRead(&bzerror, self->fp,
- buffer+nfilled, buffersize-nfilled);
- self->pos += nread;
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- self->size = self->pos;
- self->mode = MODE_READ_EOF;
- if (nread == 0) {
- sizehint = 0;
- break;
- }
- shortread = 1;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- error:
- Py_DECREF(list);
- list = NULL;
- goto cleanup;
- }
- totalread += nread;
- p = memchr(buffer+nfilled, '\n', nread);
- if (!shortread && p == NULL) {
- /* Need a larger buffer to fit this line */
- nfilled += nread;
- buffersize *= 2;
- if (buffersize > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- goto error;
- }
- if (big_buffer == NULL) {
- /* Create the big buffer */
- big_buffer = PyBytes_FromStringAndSize(
- NULL, buffersize);
- if (big_buffer == NULL)
- goto error;
- buffer = PyBytes_AS_STRING(big_buffer);
- memcpy(buffer, small_buffer, nfilled);
- }
- else {
- /* Grow the big buffer */
- if (_PyBytes_Resize(&big_buffer, buffersize) < 0){
- big_buffer = NULL;
- goto error;
- }
- buffer = PyBytes_AS_STRING(big_buffer);
- }
- continue;
- }
- end = buffer+nfilled+nread;
- q = buffer;
- while (p != NULL) {
- /* Process complete lines */
- p++;
- line = PyBytes_FromStringAndSize(q, p-q);
- if (line == NULL)
- goto error;
- err = PyList_Append(list, line);
- Py_DECREF(line);
- if (err != 0)
- goto error;
- q = p;
- p = memchr(q, '\n', end-q);
- }
- /* Move the remaining incomplete line to the start */
- nfilled = end-q;
- memmove(buffer, q, nfilled);
- if (sizehint > 0)
- if (totalread >= (size_t)sizehint)
- break;
- if (shortread) {
- sizehint = 0;
- break;
- }
- }
- if (nfilled != 0) {
- /* Partial last line */
- line = PyBytes_FromStringAndSize(buffer, nfilled);
- if (line == NULL)
- goto error;
- if (sizehint > 0) {
- /* Need to complete the last line */
- PyObject *rest = Util_GetLine(self, 0);
- if (rest == NULL) {
- Py_DECREF(line);
- goto error;
- }
- PyBytes_Concat(&line, rest);
- Py_DECREF(rest);
- if (line == NULL)
- goto error;
- }
- err = PyList_Append(list, line);
- Py_DECREF(line);
- if (err != 0)
- goto error;
- }
+ long sizehint = 0;
+ PyObject *list = NULL;
+ PyObject *line;
+ char small_buffer[SMALLCHUNK];
+ char *buffer = small_buffer;
+ size_t buffersize = SMALLCHUNK;
+ PyObject *big_buffer = NULL;
+ size_t nfilled = 0;
+ size_t nread;
+ size_t totalread = 0;
+ char *p, *q, *end;
+ int err;
+ int shortread = 0;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ break;
+ case MODE_READ_EOF:
+ list = PyList_New(0);
+ goto cleanup;
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for reading");
+ goto cleanup;
+ }
+
+ if ((list = PyList_New(0)) == NULL)
+ goto cleanup;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ nread = BZ2_bzRead(&bzerror, self->fp,
+ buffer+nfilled, buffersize-nfilled);
+ self->pos += nread;
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ self->size = self->pos;
+ self->mode = MODE_READ_EOF;
+ if (nread == 0) {
+ sizehint = 0;
+ break;
+ }
+ shortread = 1;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ error:
+ Py_DECREF(list);
+ list = NULL;
+ goto cleanup;
+ }
+ totalread += nread;
+ p = memchr(buffer+nfilled, '\n', nread);
+ if (!shortread && p == NULL) {
+ /* Need a larger buffer to fit this line */
+ nfilled += nread;
+ buffersize *= 2;
+ if (buffersize > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ goto error;
+ }
+ if (big_buffer == NULL) {
+ /* Create the big buffer */
+ big_buffer = PyBytes_FromStringAndSize(
+ NULL, buffersize);
+ if (big_buffer == NULL)
+ goto error;
+ buffer = PyBytes_AS_STRING(big_buffer);
+ memcpy(buffer, small_buffer, nfilled);
+ }
+ else {
+ /* Grow the big buffer */
+ if (_PyBytes_Resize(&big_buffer, buffersize) < 0){
+ big_buffer = NULL;
+ goto error;
+ }
+ buffer = PyBytes_AS_STRING(big_buffer);
+ }
+ continue;
+ }
+ end = buffer+nfilled+nread;
+ q = buffer;
+ while (p != NULL) {
+ /* Process complete lines */
+ p++;
+ line = PyBytes_FromStringAndSize(q, p-q);
+ if (line == NULL)
+ goto error;
+ err = PyList_Append(list, line);
+ Py_DECREF(line);
+ if (err != 0)
+ goto error;
+ q = p;
+ p = memchr(q, '\n', end-q);
+ }
+ /* Move the remaining incomplete line to the start */
+ nfilled = end-q;
+ memmove(buffer, q, nfilled);
+ if (sizehint > 0)
+ if (totalread >= (size_t)sizehint)
+ break;
+ if (shortread) {
+ sizehint = 0;
+ break;
+ }
+ }
+ if (nfilled != 0) {
+ /* Partial last line */
+ line = PyBytes_FromStringAndSize(buffer, nfilled);
+ if (line == NULL)
+ goto error;
+ if (sizehint > 0) {
+ /* Need to complete the last line */
+ PyObject *rest = Util_GetLine(self, 0);
+ if (rest == NULL) {
+ Py_DECREF(line);
+ goto error;
+ }
+ PyBytes_Concat(&line, rest);
+ Py_DECREF(rest);
+ if (line == NULL)
+ goto error;
+ }
+ err = PyList_Append(list, line);
+ Py_DECREF(line);
+ if (err != 0)
+ goto error;
+ }
cleanup:
- RELEASE_LOCK(self);
- if (big_buffer) {
- Py_DECREF(big_buffer);
- }
- return list;
+ RELEASE_LOCK(self);
+ if (big_buffer) {
+ Py_DECREF(big_buffer);
+ }
+ return list;
}
PyDoc_STRVAR(BZ2File_write__doc__,
@@ -695,50 +695,50 @@ be needed before the file on disk reflects the data written.\n\
static PyObject *
BZ2File_write(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = NULL;
- Py_buffer pbuf;
- char *buf;
- int len;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "y*:write", &pbuf))
- return NULL;
- buf = pbuf.buf;
- len = pbuf.len;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_WRITE:
- break;
-
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
-
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for writing");
- goto cleanup;
- }
-
- Py_BEGIN_ALLOW_THREADS
- BZ2_bzWrite (&bzerror, self->fp, buf, len);
- self->pos += len;
- Py_END_ALLOW_THREADS
-
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
-
- Py_INCREF(Py_None);
- ret = Py_None;
+ PyObject *ret = NULL;
+ Py_buffer pbuf;
+ char *buf;
+ int len;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "y*:write", &pbuf))
+ return NULL;
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_WRITE:
+ break;
+
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for writing");
+ goto cleanup;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ BZ2_bzWrite (&bzerror, self->fp, buf, len);
+ self->pos += len;
+ Py_END_ALLOW_THREADS
+
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+
+ Py_INCREF(Py_None);
+ ret = Py_None;
cleanup:
- PyBuffer_Release(&pbuf);
- RELEASE_LOCK(self);
- return ret;
+ PyBuffer_Release(&pbuf);
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_writelines__doc__,
@@ -754,122 +754,122 @@ static PyObject *
BZ2File_writelines(BZ2FileObject *self, PyObject *seq)
{
#define CHUNKSIZE 1000
- PyObject *list = NULL;
- PyObject *iter = NULL;
- PyObject *ret = NULL;
- PyObject *line;
- int i, j, index, len, islist;
- int bzerror;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_WRITE:
- break;
-
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto error;
-
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for writing");
- goto error;
- }
-
- islist = PyList_Check(seq);
- if (!islist) {
- iter = PyObject_GetIter(seq);
- if (iter == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "writelines() requires an iterable argument");
- goto error;
- }
- list = PyList_New(CHUNKSIZE);
- if (list == NULL)
- goto error;
- }
-
- /* Strategy: slurp CHUNKSIZE lines into a private list,
- checking that they are all strings, then write that list
- without holding the interpreter lock, then come back for more. */
- for (index = 0; ; index += CHUNKSIZE) {
- if (islist) {
- Py_XDECREF(list);
- list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
- if (list == NULL)
- goto error;
- j = PyList_GET_SIZE(list);
- }
- else {
- for (j = 0; j < CHUNKSIZE; j++) {
- line = PyIter_Next(iter);
- if (line == NULL) {
- if (PyErr_Occurred())
- goto error;
- break;
- }
- PyList_SetItem(list, j, line);
- }
- }
- if (j == 0)
- break;
-
- /* Check that all entries are indeed byte strings. If not,
- apply the same rules as for file.write() and
- convert the rets to strings. This is slow, but
- seems to be the only way since all conversion APIs
- could potentially execute Python code. */
- for (i = 0; i < j; i++) {
- PyObject *v = PyList_GET_ITEM(list, i);
- if (!PyBytes_Check(v)) {
- const char *buffer;
- Py_ssize_t len;
- if (PyObject_AsCharBuffer(v, &buffer, &len)) {
- PyErr_SetString(PyExc_TypeError,
- "writelines() "
- "argument must be "
- "a sequence of "
- "bytes objects");
- goto error;
- }
- line = PyBytes_FromStringAndSize(buffer,
- len);
- if (line == NULL)
- goto error;
- Py_DECREF(v);
- PyList_SET_ITEM(list, i, line);
- }
- }
-
- /* Since we are releasing the global lock, the
- following code may *not* execute Python code. */
- Py_BEGIN_ALLOW_THREADS
- for (i = 0; i < j; i++) {
- line = PyList_GET_ITEM(list, i);
- len = PyBytes_GET_SIZE(line);
- BZ2_bzWrite (&bzerror, self->fp,
- PyBytes_AS_STRING(line), len);
- if (bzerror != BZ_OK) {
- Py_BLOCK_THREADS
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- }
- Py_END_ALLOW_THREADS
-
- if (j < CHUNKSIZE)
- break;
- }
-
- Py_INCREF(Py_None);
- ret = Py_None;
+ PyObject *list = NULL;
+ PyObject *iter = NULL;
+ PyObject *ret = NULL;
+ PyObject *line;
+ int i, j, index, len, islist;
+ int bzerror;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_WRITE:
+ break;
+
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto error;
+
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for writing");
+ goto error;
+ }
+
+ islist = PyList_Check(seq);
+ if (!islist) {
+ iter = PyObject_GetIter(seq);
+ if (iter == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "writelines() requires an iterable argument");
+ goto error;
+ }
+ list = PyList_New(CHUNKSIZE);
+ if (list == NULL)
+ goto error;
+ }
+
+ /* Strategy: slurp CHUNKSIZE lines into a private list,
+ checking that they are all strings, then write that list
+ without holding the interpreter lock, then come back for more. */
+ for (index = 0; ; index += CHUNKSIZE) {
+ if (islist) {
+ Py_XDECREF(list);
+ list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
+ if (list == NULL)
+ goto error;
+ j = PyList_GET_SIZE(list);
+ }
+ else {
+ for (j = 0; j < CHUNKSIZE; j++) {
+ line = PyIter_Next(iter);
+ if (line == NULL) {
+ if (PyErr_Occurred())
+ goto error;
+ break;
+ }
+ PyList_SetItem(list, j, line);
+ }
+ }
+ if (j == 0)
+ break;
+
+ /* Check that all entries are indeed byte strings. If not,
+ apply the same rules as for file.write() and
+ convert the rets to strings. This is slow, but
+ seems to be the only way since all conversion APIs
+ could potentially execute Python code. */
+ for (i = 0; i < j; i++) {
+ PyObject *v = PyList_GET_ITEM(list, i);
+ if (!PyBytes_Check(v)) {
+ const char *buffer;
+ Py_ssize_t len;
+ if (PyObject_AsCharBuffer(v, &buffer, &len)) {
+ PyErr_SetString(PyExc_TypeError,
+ "writelines() "
+ "argument must be "
+ "a sequence of "
+ "bytes objects");
+ goto error;
+ }
+ line = PyBytes_FromStringAndSize(buffer,
+ len);
+ if (line == NULL)
+ goto error;
+ Py_DECREF(v);
+ PyList_SET_ITEM(list, i, line);
+ }
+ }
+
+ /* Since we are releasing the global lock, the
+ following code may *not* execute Python code. */
+ Py_BEGIN_ALLOW_THREADS
+ for (i = 0; i < j; i++) {
+ line = PyList_GET_ITEM(list, i);
+ len = PyBytes_GET_SIZE(line);
+ BZ2_bzWrite (&bzerror, self->fp,
+ PyBytes_AS_STRING(line), len);
+ if (bzerror != BZ_OK) {
+ Py_BLOCK_THREADS
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ }
+ Py_END_ALLOW_THREADS
+
+ if (j < CHUNKSIZE)
+ break;
+ }
+
+ Py_INCREF(Py_None);
+ ret = Py_None;
error:
- RELEASE_LOCK(self);
- Py_XDECREF(list);
- Py_XDECREF(iter);
- return ret;
+ RELEASE_LOCK(self);
+ Py_XDECREF(list);
+ Py_XDECREF(iter);
+ return ret;
#undef CHUNKSIZE
}
@@ -889,135 +889,135 @@ the operation may be extremely slow.\n\
static PyObject *
BZ2File_seek(BZ2FileObject *self, PyObject *args)
{
- int where = 0;
- PyObject *offobj;
- Py_off_t offset;
- char small_buffer[SMALLCHUNK];
- char *buffer = small_buffer;
- size_t buffersize = SMALLCHUNK;
- Py_off_t bytesread = 0;
- size_t readsize;
- int chunksize;
- int bzerror;
- PyObject *ret = NULL;
-
- if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where))
- return NULL;
+ int where = 0;
+ PyObject *offobj;
+ Py_off_t offset;
+ char small_buffer[SMALLCHUNK];
+ char *buffer = small_buffer;
+ size_t buffersize = SMALLCHUNK;
+ Py_off_t bytesread = 0;
+ size_t readsize;
+ int chunksize;
+ int bzerror;
+ PyObject *ret = NULL;
+
+ if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where))
+ return NULL;
#if !defined(HAVE_LARGEFILE_SUPPORT)
- offset = PyLong_AsLong(offobj);
+ offset = PyLong_AsLong(offobj);
#else
- offset = PyLong_Check(offobj) ?
- PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj);
+ offset = PyLong_Check(offobj) ?
+ PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj);
#endif
- if (PyErr_Occurred())
- return NULL;
-
- ACQUIRE_LOCK(self);
- Util_DropReadAhead(self);
- switch (self->mode) {
- case MODE_READ:
- case MODE_READ_EOF:
- break;
-
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
-
- default:
- PyErr_SetString(PyExc_IOError,
- "seek works only while reading");
- goto cleanup;
- }
-
- if (where == 2) {
- if (self->size == -1) {
- assert(self->mode != MODE_READ_EOF);
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- chunksize = BZ2_bzRead(&bzerror, self->fp,
- buffer, buffersize);
- self->pos += chunksize;
- Py_END_ALLOW_THREADS
-
- bytesread += chunksize;
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- }
- self->mode = MODE_READ_EOF;
- self->size = self->pos;
- bytesread = 0;
- }
- offset = self->size + offset;
- } else if (where == 1) {
- offset = self->pos + offset;
- }
-
- /* Before getting here, offset must be the absolute position the file
- * pointer should be set to. */
-
- if (offset >= self->pos) {
- /* we can move forward */
- offset -= self->pos;
- } else {
- /* we cannot move back, so rewind the stream */
- BZ2_bzReadClose(&bzerror, self->fp);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- rewind(self->rawfp);
- self->pos = 0;
- self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp,
- 0, 0, NULL, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- self->mode = MODE_READ;
- }
-
- if (offset <= 0 || self->mode == MODE_READ_EOF)
- goto exit;
-
- /* Before getting here, offset must be set to the number of bytes
- * to walk forward. */
- for (;;) {
- if (offset-bytesread > buffersize)
- readsize = buffersize;
- else
- /* offset might be wider that readsize, but the result
- * of the subtraction is bound by buffersize (see the
- * condition above). buffersize is 8192. */
- readsize = (size_t)(offset-bytesread);
- Py_BEGIN_ALLOW_THREADS
- chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize);
- self->pos += chunksize;
- Py_END_ALLOW_THREADS
- bytesread += chunksize;
- if (bzerror == BZ_STREAM_END) {
- self->size = self->pos;
- self->mode = MODE_READ_EOF;
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- if (bytesread == offset)
- break;
- }
+ if (PyErr_Occurred())
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ Util_DropReadAhead(self);
+ switch (self->mode) {
+ case MODE_READ:
+ case MODE_READ_EOF:
+ break;
+
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "seek works only while reading");
+ goto cleanup;
+ }
+
+ if (where == 2) {
+ if (self->size == -1) {
+ assert(self->mode != MODE_READ_EOF);
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = BZ2_bzRead(&bzerror, self->fp,
+ buffer, buffersize);
+ self->pos += chunksize;
+ Py_END_ALLOW_THREADS
+
+ bytesread += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ }
+ self->mode = MODE_READ_EOF;
+ self->size = self->pos;
+ bytesread = 0;
+ }
+ offset = self->size + offset;
+ } else if (where == 1) {
+ offset = self->pos + offset;
+ }
+
+ /* Before getting here, offset must be the absolute position the file
+ * pointer should be set to. */
+
+ if (offset >= self->pos) {
+ /* we can move forward */
+ offset -= self->pos;
+ } else {
+ /* we cannot move back, so rewind the stream */
+ BZ2_bzReadClose(&bzerror, self->fp);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ rewind(self->rawfp);
+ self->pos = 0;
+ self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp,
+ 0, 0, NULL, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ self->mode = MODE_READ;
+ }
+
+ if (offset <= 0 || self->mode == MODE_READ_EOF)
+ goto exit;
+
+ /* Before getting here, offset must be set to the number of bytes
+ * to walk forward. */
+ for (;;) {
+ if (offset-bytesread > buffersize)
+ readsize = buffersize;
+ else
+ /* offset might be wider that readsize, but the result
+ * of the subtraction is bound by buffersize (see the
+ * condition above). buffersize is 8192. */
+ readsize = (size_t)(offset-bytesread);
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize);
+ self->pos += chunksize;
+ Py_END_ALLOW_THREADS
+ bytesread += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ self->size = self->pos;
+ self->mode = MODE_READ_EOF;
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ if (bytesread == offset)
+ break;
+ }
exit:
- Py_INCREF(Py_None);
- ret = Py_None;
+ Py_INCREF(Py_None);
+ ret = Py_None;
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_tell__doc__,
@@ -1029,22 +1029,22 @@ Return the current file position, an integer (may be a long integer).\n\
static PyObject *
BZ2File_tell(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = NULL;
+ PyObject *ret = NULL;
- if (self->mode == MODE_CLOSED) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- }
+ if (self->mode == MODE_CLOSED) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ }
#if !defined(HAVE_LARGEFILE_SUPPORT)
- ret = PyLong_FromLong(self->pos);
+ ret = PyLong_FromLong(self->pos);
#else
- ret = PyLong_FromLongLong(self->pos);
+ ret = PyLong_FromLongLong(self->pos);
#endif
cleanup:
- return ret;
+ return ret;
}
PyDoc_STRVAR(BZ2File_close__doc__,
@@ -1058,37 +1058,37 @@ than once without error.\n\
static PyObject *
BZ2File_close(BZ2FileObject *self)
{
- PyObject *ret = NULL;
- int bzerror = BZ_OK;
-
- if (self->mode == MODE_CLOSED) {
- Py_RETURN_NONE;
- }
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- case MODE_READ_EOF:
- BZ2_bzReadClose(&bzerror, self->fp);
- break;
- case MODE_WRITE:
- BZ2_bzWriteClose(&bzerror, self->fp,
- 0, NULL, NULL);
- break;
- }
- self->mode = MODE_CLOSED;
- fclose(self->rawfp);
- self->rawfp = NULL;
- if (bzerror == BZ_OK) {
- Py_INCREF(Py_None);
- ret = Py_None;
- }
- else {
- Util_CatchBZ2Error(bzerror);
- }
-
- RELEASE_LOCK(self);
- return ret;
+ PyObject *ret = NULL;
+ int bzerror = BZ_OK;
+
+ if (self->mode == MODE_CLOSED) {
+ Py_RETURN_NONE;
+ }
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ case MODE_READ_EOF:
+ BZ2_bzReadClose(&bzerror, self->fp);
+ break;
+ case MODE_WRITE:
+ BZ2_bzWriteClose(&bzerror, self->fp,
+ 0, NULL, NULL);
+ break;
+ }
+ self->mode = MODE_CLOSED;
+ fclose(self->rawfp);
+ self->rawfp = NULL;
+ if (bzerror == BZ_OK) {
+ Py_INCREF(Py_None);
+ ret = Py_None;
+ }
+ else {
+ Util_CatchBZ2Error(bzerror);
+ }
+
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_enter_doc,
@@ -1097,13 +1097,13 @@ PyDoc_STRVAR(BZ2File_enter_doc,
static PyObject *
BZ2File_enter(BZ2FileObject *self)
{
- if (self->mode == MODE_CLOSED) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return NULL;
- }
- Py_INCREF(self);
- return (PyObject *) self;
+ if (self->mode == MODE_CLOSED) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return NULL;
+ }
+ Py_INCREF(self);
+ return (PyObject *) self;
}
PyDoc_STRVAR(BZ2File_exit_doc,
@@ -1112,29 +1112,29 @@ PyDoc_STRVAR(BZ2File_exit_doc,
static PyObject *
BZ2File_exit(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL);
- if (!ret)
- /* If error occurred, pass through */
- return NULL;
- Py_DECREF(ret);
- Py_RETURN_NONE;
+ PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL);
+ if (!ret)
+ /* If error occurred, pass through */
+ return NULL;
+ Py_DECREF(ret);
+ Py_RETURN_NONE;
}
static PyObject *BZ2File_getiter(BZ2FileObject *self);
static PyMethodDef BZ2File_methods[] = {
- {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__},
- {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__},
- {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__},
- {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__},
- {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__},
- {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__},
- {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__},
- {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__},
- {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc},
- {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc},
- {NULL, NULL} /* sentinel */
+ {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__},
+ {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__},
+ {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__},
+ {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__},
+ {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__},
+ {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__},
+ {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__},
+ {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__},
+ {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc},
+ {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1144,13 +1144,13 @@ static PyMethodDef BZ2File_methods[] = {
static PyObject *
BZ2File_get_closed(BZ2FileObject *self, void *closure)
{
- return PyLong_FromLong(self->mode == MODE_CLOSED);
+ return PyLong_FromLong(self->mode == MODE_CLOSED);
}
static PyGetSetDef BZ2File_getset[] = {
- {"closed", (getter)BZ2File_get_closed, NULL,
- "True if the file is closed"},
- {NULL} /* Sentinel */
+ {"closed", (getter)BZ2File_get_closed, NULL,
+ "True if the file is closed"},
+ {NULL} /* Sentinel */
};
@@ -1160,148 +1160,148 @@ static PyGetSetDef BZ2File_getset[] = {
static int
BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs)
{
- static char *kwlist[] = {"filename", "mode", "buffering",
- "compresslevel", 0};
- PyObject *name_obj = NULL;
- char *name;
- char *mode = "r";
- int buffering = -1;
- int compresslevel = 9;
- int bzerror;
- int mode_char = 0;
-
- self->size = -1;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File",
- kwlist, PyUnicode_FSConverter, &name_obj,
- &mode, &buffering,
- &compresslevel))
- return -1;
-
- name = PyBytes_AsString(name_obj);
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- Py_DECREF(name_obj);
- return -1;
- }
-
- for (;;) {
- int error = 0;
- switch (*mode) {
- case 'r':
- case 'w':
- if (mode_char)
- error = 1;
- mode_char = *mode;
- break;
-
- case 'b':
- break;
-
- default:
- error = 1;
- break;
- }
- if (error) {
- PyErr_Format(PyExc_ValueError,
- "invalid mode char %c", *mode);
- Py_DECREF(name_obj);
- return -1;
- }
- mode++;
- if (*mode == '\0')
- break;
- }
-
- if (mode_char == 0) {
- mode_char = 'r';
- }
-
- mode = (mode_char == 'r') ? "rb" : "wb";
-
- self->rawfp = fopen(name, mode);
- Py_DECREF(name_obj);
- if (self->rawfp == NULL) {
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- /* XXX Ignore buffering */
-
- /* From now on, we have stuff to dealloc, so jump to error label
- * instead of returning */
+ static char *kwlist[] = {"filename", "mode", "buffering",
+ "compresslevel", 0};
+ PyObject *name_obj = NULL;
+ char *name;
+ char *mode = "r";
+ int buffering = -1;
+ int compresslevel = 9;
+ int bzerror;
+ int mode_char = 0;
+
+ self->size = -1;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File",
+ kwlist, PyUnicode_FSConverter, &name_obj,
+ &mode, &buffering,
+ &compresslevel))
+ return -1;
+
+ name = PyBytes_AsString(name_obj);
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ Py_DECREF(name_obj);
+ return -1;
+ }
+
+ for (;;) {
+ int error = 0;
+ switch (*mode) {
+ case 'r':
+ case 'w':
+ if (mode_char)
+ error = 1;
+ mode_char = *mode;
+ break;
+
+ case 'b':
+ break;
+
+ default:
+ error = 1;
+ break;
+ }
+ if (error) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid mode char %c", *mode);
+ Py_DECREF(name_obj);
+ return -1;
+ }
+ mode++;
+ if (*mode == '\0')
+ break;
+ }
+
+ if (mode_char == 0) {
+ mode_char = 'r';
+ }
+
+ mode = (mode_char == 'r') ? "rb" : "wb";
+
+ self->rawfp = fopen(name, mode);
+ Py_DECREF(name_obj);
+ if (self->rawfp == NULL) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ /* XXX Ignore buffering */
+
+ /* From now on, we have stuff to dealloc, so jump to error label
+ * instead of returning */
#ifdef WITH_THREAD
- self->lock = PyThread_allocate_lock();
- if (!self->lock) {
- PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
- goto error;
- }
+ self->lock = PyThread_allocate_lock();
+ if (!self->lock) {
+ PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
+ goto error;
+ }
#endif
- if (mode_char == 'r')
- self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp,
- 0, 0, NULL, 0);
- else
- self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp,
- compresslevel, 0, 0);
+ if (mode_char == 'r')
+ self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp,
+ 0, 0, NULL, 0);
+ else
+ self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp,
+ compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
- self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;
+ self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;
- return 0;
+ return 0;
error:
- fclose(self->rawfp);
- self->rawfp = NULL;
+ fclose(self->rawfp);
+ self->rawfp = NULL;
#ifdef WITH_THREAD
- if (self->lock) {
- PyThread_free_lock(self->lock);
- self->lock = NULL;
- }
+ if (self->lock) {
+ PyThread_free_lock(self->lock);
+ self->lock = NULL;
+ }
#endif
- return -1;
+ return -1;
}
static void
BZ2File_dealloc(BZ2FileObject *self)
{
- int bzerror;
+ int bzerror;
#ifdef WITH_THREAD
- if (self->lock)
- PyThread_free_lock(self->lock);
+ if (self->lock)
+ PyThread_free_lock(self->lock);
#endif
- switch (self->mode) {
- case MODE_READ:
- case MODE_READ_EOF:
- BZ2_bzReadClose(&bzerror, self->fp);
- break;
- case MODE_WRITE:
- BZ2_bzWriteClose(&bzerror, self->fp,
- 0, NULL, NULL);
- break;
- }
- Util_DropReadAhead(self);
- if (self->rawfp != NULL)
- fclose(self->rawfp);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ switch (self->mode) {
+ case MODE_READ:
+ case MODE_READ_EOF:
+ BZ2_bzReadClose(&bzerror, self->fp);
+ break;
+ case MODE_WRITE:
+ BZ2_bzWriteClose(&bzerror, self->fp,
+ 0, NULL, NULL);
+ break;
+ }
+ Util_DropReadAhead(self);
+ if (self->rawfp != NULL)
+ fclose(self->rawfp);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
/* This is a hacked version of Python's fileobject.c:file_getiter(). */
static PyObject *
BZ2File_getiter(BZ2FileObject *self)
{
- if (self->mode == MODE_CLOSED) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return NULL;
- }
- Py_INCREF((PyObject*)self);
- return (PyObject *)self;
+ if (self->mode == MODE_CLOSED) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return NULL;
+ }
+ Py_INCREF((PyObject*)self);
+ return (PyObject *)self;
}
/* This is a hacked version of Python's fileobject.c:file_iternext(). */
@@ -1309,21 +1309,21 @@ BZ2File_getiter(BZ2FileObject *self)
static PyObject *
BZ2File_iternext(BZ2FileObject *self)
{
- PyBytesObject* ret;
- ACQUIRE_LOCK(self);
- if (self->mode == MODE_CLOSED) {
- RELEASE_LOCK(self);
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return NULL;
- }
- ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE);
- RELEASE_LOCK(self);
- if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) {
- Py_XDECREF(ret);
- return NULL;
- }
- return (PyObject *)ret;
+ PyBytesObject* ret;
+ ACQUIRE_LOCK(self);
+ if (self->mode == MODE_CLOSED) {
+ RELEASE_LOCK(self);
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return NULL;
+ }
+ ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE);
+ RELEASE_LOCK(self);
+ if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) {
+ Py_XDECREF(ret);
+ return NULL;
+ }
+ return (PyObject *)ret;
}
/* ===================================================================== */
@@ -1342,46 +1342,46 @@ Data read is always returned in bytes; data written ought to be bytes.\n\
");
static PyTypeObject BZ2File_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bz2.BZ2File", /*tp_name*/
- sizeof(BZ2FileObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BZ2File_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr,/*tp_getattro*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
- BZ2File__doc__, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- (getiterfunc)BZ2File_getiter, /*tp_iter*/
- (iternextfunc)BZ2File_iternext, /*tp_iternext*/
- BZ2File_methods, /*tp_methods*/
- 0, /*tp_members*/
- BZ2File_getset, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- (initproc)BZ2File_init, /*tp_init*/
- PyType_GenericAlloc, /*tp_alloc*/
- PyType_GenericNew, /*tp_new*/
- PyObject_Free, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "bz2.BZ2File", /*tp_name*/
+ sizeof(BZ2FileObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BZ2File_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr,/*tp_getattro*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ BZ2File__doc__, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ (getiterfunc)BZ2File_getiter, /*tp_iter*/
+ (iternextfunc)BZ2File_iternext, /*tp_iternext*/
+ BZ2File_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ BZ2File_getset, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ (initproc)BZ2File_init, /*tp_init*/
+ PyType_GenericAlloc, /*tp_alloc*/
+ PyType_GenericNew, /*tp_new*/
+ PyObject_Free, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1400,78 +1400,78 @@ and return what is left in the internal buffers.\n\
static PyObject *
BZ2Comp_compress(BZ2CompObject *self, PyObject *args)
{
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize = SMALLCHUNK;
- PY_LONG_LONG totalout;
- PyObject *ret = NULL;
- bz_stream *bzs = &self->bzs;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "y*:compress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (datasize == 0) {
- PyBuffer_Release(&pdata);
- return PyBytes_FromStringAndSize("", 0);
- }
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_ValueError,
- "this object was already flushed");
- goto error;
- }
-
- ret = PyBytes_FromStringAndSize(NULL, bufsize);
- if (!ret)
- goto error;
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- totalout = BZS_TOTAL_OUT(bzs);
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzCompress(bzs, BZ_RUN);
- Py_END_ALLOW_THREADS
- if (bzerror != BZ_RUN_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- if (bzs->avail_in == 0)
- break; /* no more input data */
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyBytes_Resize(&ret, bufsize) < 0) {
- BZ2_bzCompressEnd(bzs);
- goto error;
- }
- bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
- - totalout);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (_PyBytes_Resize(&ret,
- (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
- goto error;
-
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- return ret;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize = SMALLCHUNK;
+ PY_LONG_LONG totalout;
+ PyObject *ret = NULL;
+ bz_stream *bzs = &self->bzs;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "y*:compress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (datasize == 0) {
+ PyBuffer_Release(&pdata);
+ return PyBytes_FromStringAndSize("", 0);
+ }
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_ValueError,
+ "this object was already flushed");
+ goto error;
+ }
+
+ ret = PyBytes_FromStringAndSize(NULL, bufsize);
+ if (!ret)
+ goto error;
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ totalout = BZS_TOTAL_OUT(bzs);
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzCompress(bzs, BZ_RUN);
+ Py_END_ALLOW_THREADS
+ if (bzerror != BZ_RUN_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ if (bzs->avail_in == 0)
+ break; /* no more input data */
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyBytes_Resize(&ret, bufsize) < 0) {
+ BZ2_bzCompressEnd(bzs);
+ goto error;
+ }
+ bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
+ - totalout);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (_PyBytes_Resize(&ret,
+ (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
+ goto error;
+
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ return ret;
error:
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- Py_XDECREF(ret);
- return NULL;
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ Py_XDECREF(ret);
+ return NULL;
}
PyDoc_STRVAR(BZ2Comp_flush__doc__,
@@ -1484,71 +1484,71 @@ You must not use the compressor object after calling this method.\n\
static PyObject *
BZ2Comp_flush(BZ2CompObject *self)
{
- int bufsize = SMALLCHUNK;
- PyObject *ret = NULL;
- bz_stream *bzs = &self->bzs;
- PY_LONG_LONG totalout;
- int bzerror;
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_ValueError, "object was already "
- "flushed");
- goto error;
- }
- self->running = 0;
-
- ret = PyBytes_FromStringAndSize(NULL, bufsize);
- if (!ret)
- goto error;
-
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- totalout = BZS_TOTAL_OUT(bzs);
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_FINISH_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyBytes_Resize(&ret, bufsize) < 0)
- goto error;
- bzs->next_out = BUF(ret);
- bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
- - totalout);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0) {
- if (_PyBytes_Resize(&ret,
- (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
- goto error;
- }
-
- RELEASE_LOCK(self);
- return ret;
+ int bufsize = SMALLCHUNK;
+ PyObject *ret = NULL;
+ bz_stream *bzs = &self->bzs;
+ PY_LONG_LONG totalout;
+ int bzerror;
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_ValueError, "object was already "
+ "flushed");
+ goto error;
+ }
+ self->running = 0;
+
+ ret = PyBytes_FromStringAndSize(NULL, bufsize);
+ if (!ret)
+ goto error;
+
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ totalout = BZS_TOTAL_OUT(bzs);
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_FINISH_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyBytes_Resize(&ret, bufsize) < 0)
+ goto error;
+ bzs->next_out = BUF(ret);
+ bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
+ - totalout);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0) {
+ if (_PyBytes_Resize(&ret,
+ (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
+ goto error;
+ }
+
+ RELEASE_LOCK(self);
+ return ret;
error:
- RELEASE_LOCK(self);
- Py_XDECREF(ret);
- return NULL;
+ RELEASE_LOCK(self);
+ Py_XDECREF(ret);
+ return NULL;
}
static PyMethodDef BZ2Comp_methods[] = {
- {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS,
- BZ2Comp_compress__doc__},
- {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS,
- BZ2Comp_flush__doc__},
- {NULL, NULL} /* sentinel */
+ {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS,
+ BZ2Comp_compress__doc__},
+ {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS,
+ BZ2Comp_flush__doc__},
+ {NULL, NULL} /* sentinel */
};
@@ -1558,57 +1558,57 @@ static PyMethodDef BZ2Comp_methods[] = {
static int
BZ2Comp_init(BZ2CompObject *self, PyObject *args, PyObject *kwargs)
{
- int compresslevel = 9;
- int bzerror;
- static char *kwlist[] = {"compresslevel", 0};
+ int compresslevel = 9;
+ int bzerror;
+ static char *kwlist[] = {"compresslevel", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor",
- kwlist, &compresslevel))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor",
+ kwlist, &compresslevel))
+ return -1;
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- goto error;
- }
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ goto error;
+ }
#ifdef WITH_THREAD
- self->lock = PyThread_allocate_lock();
- if (!self->lock) {
- PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
- goto error;
- }
+ self->lock = PyThread_allocate_lock();
+ if (!self->lock) {
+ PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
+ goto error;
+ }
#endif
- memset(&self->bzs, 0, sizeof(bz_stream));
- bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
+ memset(&self->bzs, 0, sizeof(bz_stream));
+ bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
- self->running = 1;
+ self->running = 1;
- return 0;
+ return 0;
error:
#ifdef WITH_THREAD
- if (self->lock) {
- PyThread_free_lock(self->lock);
- self->lock = NULL;
- }
+ if (self->lock) {
+ PyThread_free_lock(self->lock);
+ self->lock = NULL;
+ }
#endif
- return -1;
+ return -1;
}
static void
BZ2Comp_dealloc(BZ2CompObject *self)
{
#ifdef WITH_THREAD
- if (self->lock)
- PyThread_free_lock(self->lock);
+ if (self->lock)
+ PyThread_free_lock(self->lock);
#endif
- BZ2_bzCompressEnd(&self->bzs);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ BZ2_bzCompressEnd(&self->bzs);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
@@ -1625,46 +1625,46 @@ must be a number between 1 and 9.\n\
");
static PyTypeObject BZ2Comp_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bz2.BZ2Compressor", /*tp_name*/
- sizeof(BZ2CompObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BZ2Comp_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr,/*tp_getattro*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
- BZ2Comp__doc__, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- BZ2Comp_methods, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- (initproc)BZ2Comp_init, /*tp_init*/
- PyType_GenericAlloc, /*tp_alloc*/
- PyType_GenericNew, /*tp_new*/
- PyObject_Free, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "bz2.BZ2Compressor", /*tp_name*/
+ sizeof(BZ2CompObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BZ2Comp_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr,/*tp_getattro*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ BZ2Comp__doc__, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ BZ2Comp_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ (initproc)BZ2Comp_init, /*tp_init*/
+ PyType_GenericAlloc, /*tp_alloc*/
+ PyType_GenericNew, /*tp_new*/
+ PyObject_Free, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1675,8 +1675,8 @@ static PyTypeObject BZ2Comp_Type = {
#define OFF(x) offsetof(BZ2DecompObject, x)
static PyMemberDef BZ2Decomp_members[] = {
- {"unused_data", T_OBJECT, OFF(unused_data), READONLY},
- {NULL} /* Sentinel */
+ {"unused_data", T_OBJECT, OFF(unused_data), READONLY},
+ {NULL} /* Sentinel */
};
@@ -1696,91 +1696,91 @@ unused_data attribute.\n\
static PyObject *
BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args)
{
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize = SMALLCHUNK;
- PY_LONG_LONG totalout;
- PyObject *ret = NULL;
- bz_stream *bzs = &self->bzs;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_EOFError, "end of stream was "
- "already found");
- goto error;
- }
-
- ret = PyBytes_FromStringAndSize(NULL, bufsize);
- if (!ret)
- goto error;
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- totalout = BZS_TOTAL_OUT(bzs);
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzDecompress(bzs);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- if (bzs->avail_in != 0) {
- Py_DECREF(self->unused_data);
- self->unused_data =
- PyBytes_FromStringAndSize(bzs->next_in,
- bzs->avail_in);
- }
- self->running = 0;
- break;
- }
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- if (bzs->avail_in == 0)
- break; /* no more input data */
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyBytes_Resize(&ret, bufsize) < 0) {
- BZ2_bzDecompressEnd(bzs);
- goto error;
- }
- bzs->next_out = BUF(ret);
- bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
- - totalout);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0) {
- if (_PyBytes_Resize(&ret,
- (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
- goto error;
- }
-
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- return ret;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize = SMALLCHUNK;
+ PY_LONG_LONG totalout;
+ PyObject *ret = NULL;
+ bz_stream *bzs = &self->bzs;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_EOFError, "end of stream was "
+ "already found");
+ goto error;
+ }
+
+ ret = PyBytes_FromStringAndSize(NULL, bufsize);
+ if (!ret)
+ goto error;
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ totalout = BZS_TOTAL_OUT(bzs);
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzDecompress(bzs);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ if (bzs->avail_in != 0) {
+ Py_DECREF(self->unused_data);
+ self->unused_data =
+ PyBytes_FromStringAndSize(bzs->next_in,
+ bzs->avail_in);
+ }
+ self->running = 0;
+ break;
+ }
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ if (bzs->avail_in == 0)
+ break; /* no more input data */
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyBytes_Resize(&ret, bufsize) < 0) {
+ BZ2_bzDecompressEnd(bzs);
+ goto error;
+ }
+ bzs->next_out = BUF(ret);
+ bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
+ - totalout);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0) {
+ if (_PyBytes_Resize(&ret,
+ (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
+ goto error;
+ }
+
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ return ret;
error:
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- Py_XDECREF(ret);
- return NULL;
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ Py_XDECREF(ret);
+ return NULL;
}
static PyMethodDef BZ2Decomp_methods[] = {
- {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__},
- {NULL, NULL} /* sentinel */
+ {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__},
+ {NULL, NULL} /* sentinel */
};
@@ -1790,55 +1790,55 @@ static PyMethodDef BZ2Decomp_methods[] = {
static int
BZ2Decomp_init(BZ2DecompObject *self, PyObject *args, PyObject *kwargs)
{
- int bzerror;
+ int bzerror;
- if (!PyArg_ParseTuple(args, ":BZ2Decompressor"))
- return -1;
+ if (!PyArg_ParseTuple(args, ":BZ2Decompressor"))
+ return -1;
#ifdef WITH_THREAD
- self->lock = PyThread_allocate_lock();
- if (!self->lock) {
- PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
- goto error;
- }
+ self->lock = PyThread_allocate_lock();
+ if (!self->lock) {
+ PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
+ goto error;
+ }
#endif
- self->unused_data = PyBytes_FromStringAndSize("", 0);
- if (!self->unused_data)
- goto error;
+ self->unused_data = PyBytes_FromStringAndSize("", 0);
+ if (!self->unused_data)
+ goto error;
- memset(&self->bzs, 0, sizeof(bz_stream));
- bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
+ memset(&self->bzs, 0, sizeof(bz_stream));
+ bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
- self->running = 1;
+ self->running = 1;
- return 0;
+ return 0;
error:
#ifdef WITH_THREAD
- if (self->lock) {
- PyThread_free_lock(self->lock);
- self->lock = NULL;
- }
+ if (self->lock) {
+ PyThread_free_lock(self->lock);
+ self->lock = NULL;
+ }
#endif
- Py_CLEAR(self->unused_data);
- return -1;
+ Py_CLEAR(self->unused_data);
+ return -1;
}
static void
BZ2Decomp_dealloc(BZ2DecompObject *self)
{
#ifdef WITH_THREAD
- if (self->lock)
- PyThread_free_lock(self->lock);
+ if (self->lock)
+ PyThread_free_lock(self->lock);
#endif
- Py_XDECREF(self->unused_data);
- BZ2_bzDecompressEnd(&self->bzs);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_XDECREF(self->unused_data);
+ BZ2_bzDecompressEnd(&self->bzs);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
@@ -1854,46 +1854,46 @@ decompress() function instead.\n\
");
static PyTypeObject BZ2Decomp_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bz2.BZ2Decompressor", /*tp_name*/
- sizeof(BZ2DecompObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BZ2Decomp_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr,/*tp_getattro*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
- BZ2Decomp__doc__, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- BZ2Decomp_methods, /*tp_methods*/
- BZ2Decomp_members, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- (initproc)BZ2Decomp_init, /*tp_init*/
- PyType_GenericAlloc, /*tp_alloc*/
- PyType_GenericNew, /*tp_new*/
- PyObject_Free, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "bz2.BZ2Decompressor", /*tp_name*/
+ sizeof(BZ2DecompObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BZ2Decomp_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr,/*tp_getattro*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ BZ2Decomp__doc__, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ BZ2Decomp_methods, /*tp_methods*/
+ BZ2Decomp_members, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ (initproc)BZ2Decomp_init, /*tp_init*/
+ PyType_GenericAlloc, /*tp_alloc*/
+ PyType_GenericNew, /*tp_new*/
+ PyObject_Free, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1911,90 +1911,90 @@ given, must be a number between 1 and 9.\n\
static PyObject *
bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs)
{
- int compresslevel=9;
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize;
- PyObject *ret = NULL;
- bz_stream _bzs;
- bz_stream *bzs = &_bzs;
- int bzerror;
- static char *kwlist[] = {"data", "compresslevel", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i",
- kwlist, &pdata,
- &compresslevel))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- /* Conforming to bz2 manual, this is large enough to fit compressed
- * data in one shot. We will check it later anyway. */
- bufsize = datasize + (datasize/100+1) + 600;
-
- ret = PyBytes_FromStringAndSize(NULL, bufsize);
- if (!ret) {
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- memset(bzs, 0, sizeof(bz_stream));
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_FINISH_OK) {
- BZ2_bzCompressEnd(bzs);
- Util_CatchBZ2Error(bzerror);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyBytes_Resize(&ret, bufsize) < 0) {
- BZ2_bzCompressEnd(bzs);
- PyBuffer_Release(&pdata);
- return NULL;
- }
- bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0) {
- if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
- ret = NULL;
- }
- }
- BZ2_bzCompressEnd(bzs);
-
- PyBuffer_Release(&pdata);
- return ret;
+ int compresslevel=9;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize;
+ PyObject *ret = NULL;
+ bz_stream _bzs;
+ bz_stream *bzs = &_bzs;
+ int bzerror;
+ static char *kwlist[] = {"data", "compresslevel", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i",
+ kwlist, &pdata,
+ &compresslevel))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ /* Conforming to bz2 manual, this is large enough to fit compressed
+ * data in one shot. We will check it later anyway. */
+ bufsize = datasize + (datasize/100+1) + 600;
+
+ ret = PyBytes_FromStringAndSize(NULL, bufsize);
+ if (!ret) {
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ memset(bzs, 0, sizeof(bz_stream));
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_FINISH_OK) {
+ BZ2_bzCompressEnd(bzs);
+ Util_CatchBZ2Error(bzerror);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyBytes_Resize(&ret, bufsize) < 0) {
+ BZ2_bzCompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+ bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0) {
+ if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
+ ret = NULL;
+ }
+ }
+ BZ2_bzCompressEnd(bzs);
+
+ PyBuffer_Release(&pdata);
+ return ret;
}
PyDoc_STRVAR(bz2_decompress__doc__,
@@ -2007,96 +2007,96 @@ use an instance of BZ2Decompressor instead.\n\
static PyObject *
bz2_decompress(PyObject *self, PyObject *args)
{
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize = SMALLCHUNK;
- PyObject *ret;
- bz_stream _bzs;
- bz_stream *bzs = &_bzs;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (datasize == 0) {
- PyBuffer_Release(&pdata);
- return PyBytes_FromStringAndSize("", 0);
- }
-
- ret = PyBytes_FromStringAndSize(NULL, bufsize);
- if (!ret) {
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- memset(bzs, 0, sizeof(bz_stream));
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- bzerror = BZ2_bzDecompressInit(bzs, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_DECREF(ret);
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzDecompress(bzs);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_OK) {
- BZ2_bzDecompressEnd(bzs);
- Util_CatchBZ2Error(bzerror);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- if (bzs->avail_in == 0) {
- BZ2_bzDecompressEnd(bzs);
- PyErr_SetString(PyExc_ValueError,
- "couldn't find end of stream");
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyBytes_Resize(&ret, bufsize) < 0) {
- BZ2_bzDecompressEnd(bzs);
- PyBuffer_Release(&pdata);
- return NULL;
- }
- bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0) {
- if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
- ret = NULL;
- }
- }
- BZ2_bzDecompressEnd(bzs);
- PyBuffer_Release(&pdata);
-
- return ret;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize = SMALLCHUNK;
+ PyObject *ret;
+ bz_stream _bzs;
+ bz_stream *bzs = &_bzs;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (datasize == 0) {
+ PyBuffer_Release(&pdata);
+ return PyBytes_FromStringAndSize("", 0);
+ }
+
+ ret = PyBytes_FromStringAndSize(NULL, bufsize);
+ if (!ret) {
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ memset(bzs, 0, sizeof(bz_stream));
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ bzerror = BZ2_bzDecompressInit(bzs, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_DECREF(ret);
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzDecompress(bzs);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_OK) {
+ BZ2_bzDecompressEnd(bzs);
+ Util_CatchBZ2Error(bzerror);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (bzs->avail_in == 0) {
+ BZ2_bzDecompressEnd(bzs);
+ PyErr_SetString(PyExc_ValueError,
+ "couldn't find end of stream");
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyBytes_Resize(&ret, bufsize) < 0) {
+ BZ2_bzDecompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+ bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0) {
+ if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
+ ret = NULL;
+ }
+ }
+ BZ2_bzDecompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+
+ return ret;
}
static PyMethodDef bz2_methods[] = {
- {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS,
- bz2_compress__doc__},
- {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS,
- bz2_decompress__doc__},
- {NULL, NULL} /* sentinel */
+ {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS,
+ bz2_compress__doc__},
+ {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS,
+ bz2_decompress__doc__},
+ {NULL, NULL} /* sentinel */
};
/* ===================================================================== */
@@ -2111,39 +2111,39 @@ sequential (de)compression.\n\
static struct PyModuleDef bz2module = {
- PyModuleDef_HEAD_INIT,
- "bz2",
- bz2__doc__,
- -1,
- bz2_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "bz2",
+ bz2__doc__,
+ -1,
+ bz2_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_bz2(void)
{
- PyObject *m;
+ PyObject *m;
- Py_TYPE(&BZ2File_Type) = &PyType_Type;
- Py_TYPE(&BZ2Comp_Type) = &PyType_Type;
- Py_TYPE(&BZ2Decomp_Type) = &PyType_Type;
+ Py_TYPE(&BZ2File_Type) = &PyType_Type;
+ Py_TYPE(&BZ2Comp_Type) = &PyType_Type;
+ Py_TYPE(&BZ2Decomp_Type) = &PyType_Type;
- m = PyModule_Create(&bz2module);
- if (m == NULL)
- return NULL;
+ m = PyModule_Create(&bz2module);
+ if (m == NULL)
+ return NULL;
- PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__));
+ PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__));
- Py_INCREF(&BZ2File_Type);
- PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type);
+ Py_INCREF(&BZ2File_Type);
+ PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type);
- Py_INCREF(&BZ2Comp_Type);
- PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type);
+ Py_INCREF(&BZ2Comp_Type);
+ PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type);
- Py_INCREF(&BZ2Decomp_Type);
- PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type);
- return m;
+ Py_INCREF(&BZ2Decomp_Type);
+ PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type);
+ return m;
}
diff --git a/Modules/cjkcodecs/_codecs_cn.c b/Modules/cjkcodecs/_codecs_cn.c
index 4542ce6..ab4e659 100644
--- a/Modules/cjkcodecs/_codecs_cn.c
+++ b/Modules/cjkcodecs/_codecs_cn.c
@@ -17,24 +17,24 @@
/* GBK and GB2312 map differently in few codepoints that are listed below:
*
- * gb2312 gbk
- * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT
- * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH
- * A844 undefined U+2015 HORIZONTAL BAR
+ * gb2312 gbk
+ * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT
+ * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH
+ * A844 undefined U+2015 HORIZONTAL BAR
*/
#define GBK_DECODE(dc1, dc2, assi) \
- if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \
- else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \
- else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \
- else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \
- else TRYMAP_DEC(gbkext, assi, dc1, dc2);
+ if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \
+ else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \
+ else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \
+ else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \
+ else TRYMAP_DEC(gbkext, assi, dc1, dc2);
#define GBK_ENCODE(code, assi) \
- if ((code) == 0x2014) (assi) = 0xa1aa; \
- else if ((code) == 0x2015) (assi) = 0xa844; \
- else if ((code) == 0x00b7) (assi) = 0xa1a4; \
- else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code));
+ if ((code) == 0x2014) (assi) = 0xa1aa; \
+ else if ((code) == 0x2015) (assi) = 0xa844; \
+ else if ((code) == 0x00b7) (assi) = 0xa1a4; \
+ else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code));
/*
* GB2312 codec
@@ -42,53 +42,53 @@
ENCODER(gb2312)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(gbcommon, code, c);
- else return 1;
-
- if (code & 0x8000) /* MSB set: GBK */
- return 1;
-
- OUT1((code >> 8) | 0x80)
- OUT2((code & 0xFF) | 0x80)
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(gbcommon, code, c);
+ else return 1;
+
+ if (code & 0x8000) /* MSB set: GBK */
+ return 1;
+
+ OUT1((code >> 8) | 0x80)
+ OUT2((code & 0xFF) | 0x80)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(gb2312)
{
- while (inleft > 0) {
- unsigned char c = **inbuf;
+ while (inleft > 0) {
+ unsigned char c = **inbuf;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
- TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
- NEXT(2, 1)
- }
- else return 2;
- }
+ REQUIRE_INBUF(2)
+ TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
+ NEXT(2, 1)
+ }
+ else return 2;
+ }
- return 0;
+ return 0;
}
@@ -98,55 +98,55 @@ DECODER(gb2312)
ENCODER(gbk)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
-
- GBK_ENCODE(c, code)
- else return 1;
-
- OUT1((code >> 8) | 0x80)
- if (code & 0x8000)
- OUT2((code & 0xFF)) /* MSB set: GBK */
- else
- OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+
+ GBK_ENCODE(c, code)
+ else return 1;
+
+ OUT1((code >> 8) | 0x80)
+ if (code & 0x8000)
+ OUT2((code & 0xFF)) /* MSB set: GBK */
+ else
+ OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(gbk)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
+ REQUIRE_INBUF(2)
- GBK_DECODE(c, IN2, **outbuf)
- else return 2;
+ GBK_DECODE(c, IN2, **outbuf)
+ else return 2;
- NEXT(2, 1)
- }
+ NEXT(2, 1)
+ }
- return 0;
+ return 0;
}
@@ -156,153 +156,153 @@ DECODER(gbk)
ENCODER(gb18030)
{
- while (inleft > 0) {
- ucs4_t c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1(c)
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- if (c > 0x10FFFF)
+ while (inleft > 0) {
+ ucs4_t c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ if (c > 0x10FFFF)
#if Py_UNICODE_SIZE == 2
- return 2; /* surrogates pair */
+ return 2; /* surrogates pair */
#else
- return 1;
+ return 1;
#endif
- else if (c >= 0x10000) {
- ucs4_t tc = c - 0x10000;
+ else if (c >= 0x10000) {
+ ucs4_t tc = c - 0x10000;
- REQUIRE_OUTBUF(4)
+ REQUIRE_OUTBUF(4)
- OUT4((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT3((unsigned char)(tc % 126) + 0x81)
- tc /= 126;
- OUT2((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT1((unsigned char)(tc + 0x90))
+ OUT4((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT3((unsigned char)(tc % 126) + 0x81)
+ tc /= 126;
+ OUT2((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT1((unsigned char)(tc + 0x90))
#if Py_UNICODE_SIZE == 2
- NEXT(2, 4) /* surrogates pair */
+ NEXT(2, 4) /* surrogates pair */
#else
- NEXT(1, 4)
+ NEXT(1, 4)
#endif
- continue;
- }
-
- REQUIRE_OUTBUF(2)
-
- GBK_ENCODE(c, code)
- else TRYMAP_ENC(gb18030ext, code, c);
- else {
- const struct _gb18030_to_unibmp_ranges *utrrange;
-
- REQUIRE_OUTBUF(4)
-
- for (utrrange = gb18030_to_unibmp_ranges;
- utrrange->first != 0;
- utrrange++)
- if (utrrange->first <= c &&
- c <= utrrange->last) {
- Py_UNICODE tc;
-
- tc = c - utrrange->first +
- utrrange->base;
-
- OUT4((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT3((unsigned char)(tc % 126) + 0x81)
- tc /= 126;
- OUT2((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT1((unsigned char)tc + 0x81)
-
- NEXT(1, 4)
- break;
- }
-
- if (utrrange->first == 0)
- return 1;
- continue;
- }
-
- OUT1((code >> 8) | 0x80)
- if (code & 0x8000)
- OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */
- else
- OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
-
- NEXT(1, 2)
- }
-
- return 0;
+ continue;
+ }
+
+ REQUIRE_OUTBUF(2)
+
+ GBK_ENCODE(c, code)
+ else TRYMAP_ENC(gb18030ext, code, c);
+ else {
+ const struct _gb18030_to_unibmp_ranges *utrrange;
+
+ REQUIRE_OUTBUF(4)
+
+ for (utrrange = gb18030_to_unibmp_ranges;
+ utrrange->first != 0;
+ utrrange++)
+ if (utrrange->first <= c &&
+ c <= utrrange->last) {
+ Py_UNICODE tc;
+
+ tc = c - utrrange->first +
+ utrrange->base;
+
+ OUT4((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT3((unsigned char)(tc % 126) + 0x81)
+ tc /= 126;
+ OUT2((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT1((unsigned char)tc + 0x81)
+
+ NEXT(1, 4)
+ break;
+ }
+
+ if (utrrange->first == 0)
+ return 1;
+ continue;
+ }
+
+ OUT1((code >> 8) | 0x80)
+ if (code & 0x8000)
+ OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */
+ else
+ OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
+
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(gb18030)
{
- while (inleft > 0) {
- unsigned char c = IN1, c2;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
-
- c2 = IN2;
- if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */
- const struct _gb18030_to_unibmp_ranges *utr;
- unsigned char c3, c4;
- ucs4_t lseq;
-
- REQUIRE_INBUF(4)
- c3 = IN3;
- c4 = IN4;
- if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39)
- return 4;
- c -= 0x81; c2 -= 0x30;
- c3 -= 0x81; c4 -= 0x30;
-
- if (c < 4) { /* U+0080 - U+FFFF */
- lseq = ((ucs4_t)c * 10 + c2) * 1260 +
- (ucs4_t)c3 * 10 + c4;
- if (lseq < 39420) {
- for (utr = gb18030_to_unibmp_ranges;
- lseq >= (utr + 1)->base;
- utr++) ;
- OUT1(utr->first - utr->base + lseq)
- NEXT(4, 1)
- continue;
- }
- }
- else if (c >= 15) { /* U+10000 - U+10FFFF */
- lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2)
- * 1260 + (ucs4_t)c3 * 10 + c4;
- if (lseq <= 0x10FFFF) {
- WRITEUCS4(lseq);
- NEXT_IN(4)
- continue;
- }
- }
- return 4;
- }
-
- GBK_DECODE(c, c2, **outbuf)
- else TRYMAP_DEC(gb18030ext, **outbuf, c, c2);
- else return 2;
-
- NEXT(2, 1)
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1, c2;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+
+ c2 = IN2;
+ if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */
+ const struct _gb18030_to_unibmp_ranges *utr;
+ unsigned char c3, c4;
+ ucs4_t lseq;
+
+ REQUIRE_INBUF(4)
+ c3 = IN3;
+ c4 = IN4;
+ if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39)
+ return 4;
+ c -= 0x81; c2 -= 0x30;
+ c3 -= 0x81; c4 -= 0x30;
+
+ if (c < 4) { /* U+0080 - U+FFFF */
+ lseq = ((ucs4_t)c * 10 + c2) * 1260 +
+ (ucs4_t)c3 * 10 + c4;
+ if (lseq < 39420) {
+ for (utr = gb18030_to_unibmp_ranges;
+ lseq >= (utr + 1)->base;
+ utr++) ;
+ OUT1(utr->first - utr->base + lseq)
+ NEXT(4, 1)
+ continue;
+ }
+ }
+ else if (c >= 15) { /* U+10000 - U+10FFFF */
+ lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2)
+ * 1260 + (ucs4_t)c3 * 10 + c4;
+ if (lseq <= 0x10FFFF) {
+ WRITEUCS4(lseq);
+ NEXT_IN(4)
+ continue;
+ }
+ }
+ return 4;
+ }
+
+ GBK_DECODE(c, c2, **outbuf)
+ else TRYMAP_DEC(gb18030ext, **outbuf, c, c2);
+ else return 2;
+
+ NEXT(2, 1)
+ }
+
+ return 0;
}
@@ -312,118 +312,118 @@ DECODER(gb18030)
ENCODER_INIT(hz)
{
- state->i = 0;
- return 0;
+ state->i = 0;
+ return 0;
}
ENCODER_RESET(hz)
{
- if (state->i != 0) {
- WRITE2('~', '}')
- state->i = 0;
- NEXT_OUT(2)
- }
- return 0;
+ if (state->i != 0) {
+ WRITE2('~', '}')
+ state->i = 0;
+ NEXT_OUT(2)
+ }
+ return 0;
}
ENCODER(hz)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- if (state->i == 0) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- }
- else {
- WRITE3('~', '}', (unsigned char)c)
- NEXT(1, 3)
- state->i = 0;
- }
- continue;
- }
-
- UCS4INVALID(c)
-
- TRYMAP_ENC(gbcommon, code, c);
- else return 1;
-
- if (code & 0x8000) /* MSB set: GBK */
- return 1;
-
- if (state->i == 0) {
- WRITE4('~', '{', code >> 8, code & 0xff)
- NEXT(1, 4)
- state->i = 1;
- }
- else {
- WRITE2(code >> 8, code & 0xff)
- NEXT(1, 2)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ if (state->i == 0) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ }
+ else {
+ WRITE3('~', '}', (unsigned char)c)
+ NEXT(1, 3)
+ state->i = 0;
+ }
+ continue;
+ }
+
+ UCS4INVALID(c)
+
+ TRYMAP_ENC(gbcommon, code, c);
+ else return 1;
+
+ if (code & 0x8000) /* MSB set: GBK */
+ return 1;
+
+ if (state->i == 0) {
+ WRITE4('~', '{', code >> 8, code & 0xff)
+ NEXT(1, 4)
+ state->i = 1;
+ }
+ else {
+ WRITE2(code >> 8, code & 0xff)
+ NEXT(1, 2)
+ }
+ }
+
+ return 0;
}
DECODER_INIT(hz)
{
- state->i = 0;
- return 0;
+ state->i = 0;
+ return 0;
}
DECODER_RESET(hz)
{
- state->i = 0;
- return 0;
+ state->i = 0;
+ return 0;
}
DECODER(hz)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- if (c == '~') {
- unsigned char c2 = IN2;
-
- REQUIRE_INBUF(2)
- if (c2 == '~') {
- WRITE1('~')
- NEXT(2, 1)
- continue;
- }
- else if (c2 == '{' && state->i == 0)
- state->i = 1; /* set GB */
- else if (c2 == '}' && state->i == 1)
- state->i = 0; /* set ASCII */
- else if (c2 == '\n')
- ; /* line-continuation */
- else
- return 2;
- NEXT(2, 0);
- continue;
- }
-
- if (c & 0x80)
- return 1;
-
- if (state->i == 0) { /* ASCII mode */
- WRITE1(c)
- NEXT(1, 1)
- }
- else { /* GB mode */
- REQUIRE_INBUF(2)
- REQUIRE_OUTBUF(1)
- TRYMAP_DEC(gb2312, **outbuf, c, IN2) {
- NEXT(2, 1)
- }
- else
- return 2;
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ if (c == '~') {
+ unsigned char c2 = IN2;
+
+ REQUIRE_INBUF(2)
+ if (c2 == '~') {
+ WRITE1('~')
+ NEXT(2, 1)
+ continue;
+ }
+ else if (c2 == '{' && state->i == 0)
+ state->i = 1; /* set GB */
+ else if (c2 == '}' && state->i == 1)
+ state->i = 0; /* set ASCII */
+ else if (c2 == '\n')
+ ; /* line-continuation */
+ else
+ return 2;
+ NEXT(2, 0);
+ continue;
+ }
+
+ if (c & 0x80)
+ return 1;
+
+ if (state->i == 0) { /* ASCII mode */
+ WRITE1(c)
+ NEXT(1, 1)
+ }
+ else { /* GB mode */
+ REQUIRE_INBUF(2)
+ REQUIRE_OUTBUF(1)
+ TRYMAP_DEC(gb2312, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+ }
+
+ return 0;
}
diff --git a/Modules/cjkcodecs/_codecs_hk.c b/Modules/cjkcodecs/_codecs_hk.c
index 4bbd622..aaf103d 100644
--- a/Modules/cjkcodecs/_codecs_hk.c
+++ b/Modules/cjkcodecs/_codecs_hk.c
@@ -18,12 +18,12 @@ static const decode_map *big5_decmap = NULL;
CODEC_INIT(big5hkscs)
{
- static int initialized = 0;
+ static int initialized = 0;
- if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap))
- return -1;
- initialized = 1;
- return 0;
+ if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap))
+ return -1;
+ initialized = 1;
+ return 0;
}
/*
@@ -38,135 +38,135 @@ static const DBCHAR big5hkscs_pairenc_table[4] = {0x8862, 0x8864, 0x88a3, 0x88a5
ENCODER(big5hkscs)
{
- while (inleft > 0) {
- ucs4_t c = **inbuf;
- DBCHAR code;
- Py_ssize_t insize;
-
- if (c < 0x80) {
- REQUIRE_OUTBUF(1)
- **outbuf = (unsigned char)c;
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- insize = GET_INSIZE(c);
-
- REQUIRE_OUTBUF(2)
-
- if (c < 0x10000) {
- TRYMAP_ENC(big5hkscs_bmp, code, c) {
- if (code == MULTIC) {
- if (inleft >= 2 &&
- ((c & 0xffdf) == 0x00ca) &&
- (((*inbuf)[1] & 0xfff7) == 0x0304)) {
- code = big5hkscs_pairenc_table[
- ((c >> 4) |
- ((*inbuf)[1] >> 3)) & 3];
- insize = 2;
- }
- else if (inleft < 2 &&
- !(flags & MBENC_FLUSH))
- return MBERR_TOOFEW;
- else {
- if (c == 0xca)
- code = 0x8866;
- else /* c == 0xea */
- code = 0x88a7;
- }
- }
- }
- else TRYMAP_ENC(big5, code, c);
- else return 1;
- }
- else if (c < 0x20000)
- return insize;
- else if (c < 0x30000) {
- TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff);
- else return insize;
- }
- else
- return insize;
-
- OUT1(code >> 8)
- OUT2(code & 0xFF)
- NEXT(insize, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ ucs4_t c = **inbuf;
+ DBCHAR code;
+ Py_ssize_t insize;
+
+ if (c < 0x80) {
+ REQUIRE_OUTBUF(1)
+ **outbuf = (unsigned char)c;
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ insize = GET_INSIZE(c);
+
+ REQUIRE_OUTBUF(2)
+
+ if (c < 0x10000) {
+ TRYMAP_ENC(big5hkscs_bmp, code, c) {
+ if (code == MULTIC) {
+ if (inleft >= 2 &&
+ ((c & 0xffdf) == 0x00ca) &&
+ (((*inbuf)[1] & 0xfff7) == 0x0304)) {
+ code = big5hkscs_pairenc_table[
+ ((c >> 4) |
+ ((*inbuf)[1] >> 3)) & 3];
+ insize = 2;
+ }
+ else if (inleft < 2 &&
+ !(flags & MBENC_FLUSH))
+ return MBERR_TOOFEW;
+ else {
+ if (c == 0xca)
+ code = 0x8866;
+ else /* c == 0xea */
+ code = 0x88a7;
+ }
+ }
+ }
+ else TRYMAP_ENC(big5, code, c);
+ else return 1;
+ }
+ else if (c < 0x20000)
+ return insize;
+ else if (c < 0x30000) {
+ TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff);
+ else return insize;
+ }
+ else
+ return insize;
+
+ OUT1(code >> 8)
+ OUT2(code & 0xFF)
+ NEXT(insize, 2)
+ }
+
+ return 0;
}
#define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40))
DECODER(big5hkscs)
{
- while (inleft > 0) {
- unsigned char c = IN1;
- ucs4_t decoded;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
-
- if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
- goto hkscsdec;
-
- TRYMAP_DEC(big5, **outbuf, c, IN2) {
- NEXT(2, 1)
- }
- else
-hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
- int s = BH2S(c, IN2);
- const unsigned char *hintbase;
-
- assert(0x87 <= c && c <= 0xfe);
- assert(0x40 <= IN2 && IN2 <= 0xfe);
-
- if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
- hintbase = big5hkscs_phint_0;
- s -= BH2S(0x87, 0x40);
- }
- else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
- hintbase = big5hkscs_phint_12130;
- s -= BH2S(0xc6, 0xa1);
- }
- else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
- hintbase = big5hkscs_phint_21924;
- s -= BH2S(0xf9, 0xd6);
- }
- else
- return MBERR_INTERNAL;
-
- if (hintbase[s >> 3] & (1 << (s & 7))) {
- WRITEUCS4(decoded | 0x20000)
- NEXT_IN(2)
- }
- else {
- OUT1(decoded)
- NEXT(2, 1)
- }
- }
- else {
- switch ((c << 8) | IN2) {
- case 0x8862: WRITE2(0x00ca, 0x0304); break;
- case 0x8864: WRITE2(0x00ca, 0x030c); break;
- case 0x88a3: WRITE2(0x00ea, 0x0304); break;
- case 0x88a5: WRITE2(0x00ea, 0x030c); break;
- default: return 2;
- }
-
- NEXT(2, 2) /* all decoded codepoints are pairs, above. */
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+ ucs4_t decoded;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+
+ if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
+ goto hkscsdec;
+
+ TRYMAP_DEC(big5, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ }
+ else
+hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
+ int s = BH2S(c, IN2);
+ const unsigned char *hintbase;
+
+ assert(0x87 <= c && c <= 0xfe);
+ assert(0x40 <= IN2 && IN2 <= 0xfe);
+
+ if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
+ hintbase = big5hkscs_phint_0;
+ s -= BH2S(0x87, 0x40);
+ }
+ else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
+ hintbase = big5hkscs_phint_12130;
+ s -= BH2S(0xc6, 0xa1);
+ }
+ else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
+ hintbase = big5hkscs_phint_21924;
+ s -= BH2S(0xf9, 0xd6);
+ }
+ else
+ return MBERR_INTERNAL;
+
+ if (hintbase[s >> 3] & (1 << (s & 7))) {
+ WRITEUCS4(decoded | 0x20000)
+ NEXT_IN(2)
+ }
+ else {
+ OUT1(decoded)
+ NEXT(2, 1)
+ }
+ }
+ else {
+ switch ((c << 8) | IN2) {
+ case 0x8862: WRITE2(0x00ca, 0x0304); break;
+ case 0x8864: WRITE2(0x00ca, 0x030c); break;
+ case 0x88a3: WRITE2(0x00ea, 0x0304); break;
+ case 0x88a5: WRITE2(0x00ea, 0x030c); break;
+ default: return 2;
+ }
+
+ NEXT(2, 2) /* all decoded codepoints are pairs, above. */
+ }
+ }
+
+ return 0;
}
diff --git a/Modules/cjkcodecs/_codecs_iso2022.c b/Modules/cjkcodecs/_codecs_iso2022.c
index 9ce7b75..25c1a36 100644
--- a/Modules/cjkcodecs/_codecs_iso2022.c
+++ b/Modules/cjkcodecs/_codecs_iso2022.c
@@ -19,85 +19,85 @@
state->c[0-3]
- 00000000
- ||^^^^^|
- |+-----+---- G0-3 Character Set
- +----------- Is G0-3 double byte?
+ 00000000
+ ||^^^^^|
+ |+-----+---- G0-3 Character Set
+ +----------- Is G0-3 double byte?
state->c[4]
- 00000000
- ||
- |+---- Locked-Shift?
- +----- ESC Throughout
+ 00000000
+ ||
+ |+---- Locked-Shift?
+ +----- ESC Throughout
*/
-#define ESC 0x1B
-#define SO 0x0E
-#define SI 0x0F
-#define LF 0x0A
-
-#define MAX_ESCSEQLEN 16
-
-#define CHARSET_ISO8859_1 'A'
-#define CHARSET_ASCII 'B'
-#define CHARSET_ISO8859_7 'F'
-#define CHARSET_JISX0201_K 'I'
-#define CHARSET_JISX0201_R 'J'
-
-#define CHARSET_GB2312 ('A'|CHARSET_DBCS)
-#define CHARSET_JISX0208 ('B'|CHARSET_DBCS)
-#define CHARSET_KSX1001 ('C'|CHARSET_DBCS)
-#define CHARSET_JISX0212 ('D'|CHARSET_DBCS)
-#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS)
-#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS)
-#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS)
-#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS)
-#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS)
-#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS)
-#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS)
-
-#define CHARSET_DBCS 0x80
-#define ESCMARK(mark) ((mark) & 0x7f)
-
-#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@')
+#define ESC 0x1B
+#define SO 0x0E
+#define SI 0x0F
+#define LF 0x0A
+
+#define MAX_ESCSEQLEN 16
+
+#define CHARSET_ISO8859_1 'A'
+#define CHARSET_ASCII 'B'
+#define CHARSET_ISO8859_7 'F'
+#define CHARSET_JISX0201_K 'I'
+#define CHARSET_JISX0201_R 'J'
+
+#define CHARSET_GB2312 ('A'|CHARSET_DBCS)
+#define CHARSET_JISX0208 ('B'|CHARSET_DBCS)
+#define CHARSET_KSX1001 ('C'|CHARSET_DBCS)
+#define CHARSET_JISX0212 ('D'|CHARSET_DBCS)
+#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS)
+#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS)
+#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS)
+#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS)
+#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS)
+#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS)
+#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS)
+
+#define CHARSET_DBCS 0x80
+#define ESCMARK(mark) ((mark) & 0x7f)
+
+#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@')
#define IS_ISO2022ESC(c2) \
- ((c2) == '(' || (c2) == ')' || (c2) == '$' || \
- (c2) == '.' || (c2) == '&')
- /* this is not a complete list of ISO-2022 escape sequence headers.
- * but, it's enough to implement CJK instances of iso-2022. */
-
-#define MAP_UNMAPPABLE 0xFFFF
-#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */
-
-#define F_SHIFTED 0x01
-#define F_ESCTHROUGHOUT 0x02
-
-#define STATE_SETG(dn, v) ((state)->c[dn]) = (v);
-#define STATE_GETG(dn) ((state)->c[dn])
-
-#define STATE_G0 STATE_GETG(0)
-#define STATE_G1 STATE_GETG(1)
-#define STATE_G2 STATE_GETG(2)
-#define STATE_G3 STATE_GETG(3)
-#define STATE_SETG0(v) STATE_SETG(0, v)
-#define STATE_SETG1(v) STATE_SETG(1, v)
-#define STATE_SETG2(v) STATE_SETG(2, v)
-#define STATE_SETG3(v) STATE_SETG(3, v)
-
-#define STATE_SETFLAG(f) ((state)->c[4]) |= (f);
-#define STATE_GETFLAG(f) ((state)->c[4] & (f))
-#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f);
-#define STATE_CLEARFLAGS() ((state)->c[4]) = 0;
-
-#define ISO2022_CONFIG ((const struct iso2022_config *)config)
-#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag))
-#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations)
+ ((c2) == '(' || (c2) == ')' || (c2) == '$' || \
+ (c2) == '.' || (c2) == '&')
+ /* this is not a complete list of ISO-2022 escape sequence headers.
+ * but, it's enough to implement CJK instances of iso-2022. */
+
+#define MAP_UNMAPPABLE 0xFFFF
+#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */
+
+#define F_SHIFTED 0x01
+#define F_ESCTHROUGHOUT 0x02
+
+#define STATE_SETG(dn, v) ((state)->c[dn]) = (v);
+#define STATE_GETG(dn) ((state)->c[dn])
+
+#define STATE_G0 STATE_GETG(0)
+#define STATE_G1 STATE_GETG(1)
+#define STATE_G2 STATE_GETG(2)
+#define STATE_G3 STATE_GETG(3)
+#define STATE_SETG0(v) STATE_SETG(0, v)
+#define STATE_SETG1(v) STATE_SETG(1, v)
+#define STATE_SETG2(v) STATE_SETG(2, v)
+#define STATE_SETG3(v) STATE_SETG(3, v)
+
+#define STATE_SETFLAG(f) ((state)->c[4]) |= (f);
+#define STATE_GETFLAG(f) ((state)->c[4] & (f))
+#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f);
+#define STATE_CLEARFLAGS() ((state)->c[4]) = 0;
+
+#define ISO2022_CONFIG ((const struct iso2022_config *)config)
+#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag))
+#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations)
/* iso2022_config.flags */
-#define NO_SHIFT 0x01
-#define USE_G2 0x02
-#define USE_JISX0208_EXT 0x04
+#define NO_SHIFT 0x01
+#define USE_G2 0x02
+#define USE_JISX0208_EXT 0x04
/*-*- internal data structures -*-*/
@@ -106,434 +106,434 @@ typedef ucs4_t (*iso2022_decode_func)(const unsigned char *data);
typedef DBCHAR (*iso2022_encode_func)(const ucs4_t *data, Py_ssize_t *length);
struct iso2022_designation {
- unsigned char mark;
- unsigned char plane;
- unsigned char width;
- iso2022_init_func initializer;
- iso2022_decode_func decoder;
- iso2022_encode_func encoder;
+ unsigned char mark;
+ unsigned char plane;
+ unsigned char width;
+ iso2022_init_func initializer;
+ iso2022_decode_func decoder;
+ iso2022_encode_func encoder;
};
struct iso2022_config {
- int flags;
- const struct iso2022_designation *designations; /* non-ascii desigs */
+ int flags;
+ const struct iso2022_designation *designations; /* non-ascii desigs */
};
/*-*- iso-2022 codec implementation -*-*/
CODEC_INIT(iso2022)
{
- const struct iso2022_designation *desig = CONFIG_DESIGNATIONS;
- for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++)
- if (desig->initializer != NULL && desig->initializer() != 0)
- return -1;
- return 0;
+ const struct iso2022_designation *desig = CONFIG_DESIGNATIONS;
+ for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++)
+ if (desig->initializer != NULL && desig->initializer() != 0)
+ return -1;
+ return 0;
}
ENCODER_INIT(iso2022)
{
- STATE_CLEARFLAGS()
- STATE_SETG0(CHARSET_ASCII)
- STATE_SETG1(CHARSET_ASCII)
- return 0;
+ STATE_CLEARFLAGS()
+ STATE_SETG0(CHARSET_ASCII)
+ STATE_SETG1(CHARSET_ASCII)
+ return 0;
}
ENCODER_RESET(iso2022)
{
- if (STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SI)
- NEXT_OUT(1)
- STATE_CLEARFLAG(F_SHIFTED)
- }
- if (STATE_G0 != CHARSET_ASCII) {
- WRITE3(ESC, '(', 'B')
- NEXT_OUT(3)
- STATE_SETG0(CHARSET_ASCII)
- }
- return 0;
+ if (STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SI)
+ NEXT_OUT(1)
+ STATE_CLEARFLAG(F_SHIFTED)
+ }
+ if (STATE_G0 != CHARSET_ASCII) {
+ WRITE3(ESC, '(', 'B')
+ NEXT_OUT(3)
+ STATE_SETG0(CHARSET_ASCII)
+ }
+ return 0;
}
ENCODER(iso2022)
{
- while (inleft > 0) {
- const struct iso2022_designation *dsg;
- DBCHAR encoded;
- ucs4_t c = **inbuf;
- Py_ssize_t insize;
-
- if (c < 0x80) {
- if (STATE_G0 != CHARSET_ASCII) {
- WRITE3(ESC, '(', 'B')
- STATE_SETG0(CHARSET_ASCII)
- NEXT_OUT(3)
- }
- if (STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SI)
- STATE_CLEARFLAG(F_SHIFTED)
- NEXT_OUT(1)
- }
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- insize = GET_INSIZE(c);
-
- encoded = MAP_UNMAPPABLE;
- for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) {
- Py_ssize_t length = 1;
- encoded = dsg->encoder(&c, &length);
- if (encoded == MAP_MULTIPLE_AVAIL) {
- /* this implementation won't work for pair
- * of non-bmp characters. */
- if (inleft < 2) {
- if (!(flags & MBENC_FLUSH))
- return MBERR_TOOFEW;
- length = -1;
- }
- else
- length = 2;
+ while (inleft > 0) {
+ const struct iso2022_designation *dsg;
+ DBCHAR encoded;
+ ucs4_t c = **inbuf;
+ Py_ssize_t insize;
+
+ if (c < 0x80) {
+ if (STATE_G0 != CHARSET_ASCII) {
+ WRITE3(ESC, '(', 'B')
+ STATE_SETG0(CHARSET_ASCII)
+ NEXT_OUT(3)
+ }
+ if (STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SI)
+ STATE_CLEARFLAG(F_SHIFTED)
+ NEXT_OUT(1)
+ }
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ insize = GET_INSIZE(c);
+
+ encoded = MAP_UNMAPPABLE;
+ for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) {
+ Py_ssize_t length = 1;
+ encoded = dsg->encoder(&c, &length);
+ if (encoded == MAP_MULTIPLE_AVAIL) {
+ /* this implementation won't work for pair
+ * of non-bmp characters. */
+ if (inleft < 2) {
+ if (!(flags & MBENC_FLUSH))
+ return MBERR_TOOFEW;
+ length = -1;
+ }
+ else
+ length = 2;
#if Py_UNICODE_SIZE == 2
- if (length == 2) {
- ucs4_t u4in[2];
- u4in[0] = (ucs4_t)IN1;
- u4in[1] = (ucs4_t)IN2;
- encoded = dsg->encoder(u4in, &length);
- } else
- encoded = dsg->encoder(&c, &length);
+ if (length == 2) {
+ ucs4_t u4in[2];
+ u4in[0] = (ucs4_t)IN1;
+ u4in[1] = (ucs4_t)IN2;
+ encoded = dsg->encoder(u4in, &length);
+ } else
+ encoded = dsg->encoder(&c, &length);
#else
- encoded = dsg->encoder(&c, &length);
+ encoded = dsg->encoder(&c, &length);
#endif
- if (encoded != MAP_UNMAPPABLE) {
- insize = length;
- break;
- }
- }
- else if (encoded != MAP_UNMAPPABLE)
- break;
- }
-
- if (!dsg->mark)
- return 1;
- assert(dsg->width == 1 || dsg->width == 2);
-
- switch (dsg->plane) {
- case 0: /* G0 */
- if (STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SI)
- STATE_CLEARFLAG(F_SHIFTED)
- NEXT_OUT(1)
- }
- if (STATE_G0 != dsg->mark) {
- if (dsg->width == 1) {
- WRITE3(ESC, '(', ESCMARK(dsg->mark))
- STATE_SETG0(dsg->mark)
- NEXT_OUT(3)
- }
- else if (dsg->mark == CHARSET_JISX0208) {
- WRITE3(ESC, '$', ESCMARK(dsg->mark))
- STATE_SETG0(dsg->mark)
- NEXT_OUT(3)
- }
- else {
- WRITE4(ESC, '$', '(',
- ESCMARK(dsg->mark))
- STATE_SETG0(dsg->mark)
- NEXT_OUT(4)
- }
- }
- break;
- case 1: /* G1 */
- if (STATE_G1 != dsg->mark) {
- if (dsg->width == 1) {
- WRITE3(ESC, ')', ESCMARK(dsg->mark))
- STATE_SETG1(dsg->mark)
- NEXT_OUT(3)
- }
- else {
- WRITE4(ESC, '$', ')',
- ESCMARK(dsg->mark))
- STATE_SETG1(dsg->mark)
- NEXT_OUT(4)
- }
- }
- if (!STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SO)
- STATE_SETFLAG(F_SHIFTED)
- NEXT_OUT(1)
- }
- break;
- default: /* G2 and G3 is not supported: no encoding in
- * CJKCodecs are using them yet */
- return MBERR_INTERNAL;
- }
-
- if (dsg->width == 1) {
- WRITE1((unsigned char)encoded)
- NEXT_OUT(1)
- }
- else {
- WRITE2(encoded >> 8, encoded & 0xff)
- NEXT_OUT(2)
- }
- NEXT_IN(insize)
- }
-
- return 0;
+ if (encoded != MAP_UNMAPPABLE) {
+ insize = length;
+ break;
+ }
+ }
+ else if (encoded != MAP_UNMAPPABLE)
+ break;
+ }
+
+ if (!dsg->mark)
+ return 1;
+ assert(dsg->width == 1 || dsg->width == 2);
+
+ switch (dsg->plane) {
+ case 0: /* G0 */
+ if (STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SI)
+ STATE_CLEARFLAG(F_SHIFTED)
+ NEXT_OUT(1)
+ }
+ if (STATE_G0 != dsg->mark) {
+ if (dsg->width == 1) {
+ WRITE3(ESC, '(', ESCMARK(dsg->mark))
+ STATE_SETG0(dsg->mark)
+ NEXT_OUT(3)
+ }
+ else if (dsg->mark == CHARSET_JISX0208) {
+ WRITE3(ESC, '$', ESCMARK(dsg->mark))
+ STATE_SETG0(dsg->mark)
+ NEXT_OUT(3)
+ }
+ else {
+ WRITE4(ESC, '$', '(',
+ ESCMARK(dsg->mark))
+ STATE_SETG0(dsg->mark)
+ NEXT_OUT(4)
+ }
+ }
+ break;
+ case 1: /* G1 */
+ if (STATE_G1 != dsg->mark) {
+ if (dsg->width == 1) {
+ WRITE3(ESC, ')', ESCMARK(dsg->mark))
+ STATE_SETG1(dsg->mark)
+ NEXT_OUT(3)
+ }
+ else {
+ WRITE4(ESC, '$', ')',
+ ESCMARK(dsg->mark))
+ STATE_SETG1(dsg->mark)
+ NEXT_OUT(4)
+ }
+ }
+ if (!STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SO)
+ STATE_SETFLAG(F_SHIFTED)
+ NEXT_OUT(1)
+ }
+ break;
+ default: /* G2 and G3 is not supported: no encoding in
+ * CJKCodecs are using them yet */
+ return MBERR_INTERNAL;
+ }
+
+ if (dsg->width == 1) {
+ WRITE1((unsigned char)encoded)
+ NEXT_OUT(1)
+ }
+ else {
+ WRITE2(encoded >> 8, encoded & 0xff)
+ NEXT_OUT(2)
+ }
+ NEXT_IN(insize)
+ }
+
+ return 0;
}
DECODER_INIT(iso2022)
{
- STATE_CLEARFLAGS()
- STATE_SETG0(CHARSET_ASCII)
- STATE_SETG1(CHARSET_ASCII)
- STATE_SETG2(CHARSET_ASCII)
- return 0;
+ STATE_CLEARFLAGS()
+ STATE_SETG0(CHARSET_ASCII)
+ STATE_SETG1(CHARSET_ASCII)
+ STATE_SETG2(CHARSET_ASCII)
+ return 0;
}
DECODER_RESET(iso2022)
{
- STATE_SETG0(CHARSET_ASCII)
- STATE_CLEARFLAG(F_SHIFTED)
- return 0;
+ STATE_SETG0(CHARSET_ASCII)
+ STATE_CLEARFLAG(F_SHIFTED)
+ return 0;
}
static Py_ssize_t
iso2022processesc(const void *config, MultibyteCodec_State *state,
- const unsigned char **inbuf, Py_ssize_t *inleft)
+ const unsigned char **inbuf, Py_ssize_t *inleft)
{
- unsigned char charset, designation;
- Py_ssize_t i, esclen;
-
- for (i = 1;i < MAX_ESCSEQLEN;i++) {
- if (i >= *inleft)
- return MBERR_TOOFEW;
- if (IS_ESCEND((*inbuf)[i])) {
- esclen = i + 1;
- break;
- }
- else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft &&
- (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@')
- i += 2;
- }
-
- if (i >= MAX_ESCSEQLEN)
- return 1; /* unterminated escape sequence */
-
- switch (esclen) {
- case 3:
- if (IN2 == '$') {
- charset = IN3 | CHARSET_DBCS;
- designation = 0;
- }
- else {
- charset = IN3;
- if (IN2 == '(') designation = 0;
- else if (IN2 == ')') designation = 1;
- else if (CONFIG_ISSET(USE_G2) && IN2 == '.')
- designation = 2;
- else return 3;
- }
- break;
- case 4:
- if (IN2 != '$')
- return 4;
-
- charset = IN4 | CHARSET_DBCS;
- if (IN3 == '(') designation = 0;
- else if (IN3 == ')') designation = 1;
- else return 4;
- break;
- case 6: /* designation with prefix */
- if (CONFIG_ISSET(USE_JISX0208_EXT) &&
- (*inbuf)[3] == ESC && (*inbuf)[4] == '$' &&
- (*inbuf)[5] == 'B') {
- charset = 'B' | CHARSET_DBCS;
- designation = 0;
- }
- else
- return 6;
- break;
- default:
- return esclen;
- }
-
- /* raise error when the charset is not designated for this encoding */
- if (charset != CHARSET_ASCII) {
- const struct iso2022_designation *dsg;
-
- for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++)
- if (dsg->mark == charset)
- break;
- if (!dsg->mark)
- return esclen;
- }
-
- STATE_SETG(designation, charset)
- *inleft -= esclen;
- (*inbuf) += esclen;
- return 0;
+ unsigned char charset, designation;
+ Py_ssize_t i, esclen;
+
+ for (i = 1;i < MAX_ESCSEQLEN;i++) {
+ if (i >= *inleft)
+ return MBERR_TOOFEW;
+ if (IS_ESCEND((*inbuf)[i])) {
+ esclen = i + 1;
+ break;
+ }
+ else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft &&
+ (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@')
+ i += 2;
+ }
+
+ if (i >= MAX_ESCSEQLEN)
+ return 1; /* unterminated escape sequence */
+
+ switch (esclen) {
+ case 3:
+ if (IN2 == '$') {
+ charset = IN3 | CHARSET_DBCS;
+ designation = 0;
+ }
+ else {
+ charset = IN3;
+ if (IN2 == '(') designation = 0;
+ else if (IN2 == ')') designation = 1;
+ else if (CONFIG_ISSET(USE_G2) && IN2 == '.')
+ designation = 2;
+ else return 3;
+ }
+ break;
+ case 4:
+ if (IN2 != '$')
+ return 4;
+
+ charset = IN4 | CHARSET_DBCS;
+ if (IN3 == '(') designation = 0;
+ else if (IN3 == ')') designation = 1;
+ else return 4;
+ break;
+ case 6: /* designation with prefix */
+ if (CONFIG_ISSET(USE_JISX0208_EXT) &&
+ (*inbuf)[3] == ESC && (*inbuf)[4] == '$' &&
+ (*inbuf)[5] == 'B') {
+ charset = 'B' | CHARSET_DBCS;
+ designation = 0;
+ }
+ else
+ return 6;
+ break;
+ default:
+ return esclen;
+ }
+
+ /* raise error when the charset is not designated for this encoding */
+ if (charset != CHARSET_ASCII) {
+ const struct iso2022_designation *dsg;
+
+ for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++)
+ if (dsg->mark == charset)
+ break;
+ if (!dsg->mark)
+ return esclen;
+ }
+
+ STATE_SETG(designation, charset)
+ *inleft -= esclen;
+ (*inbuf) += esclen;
+ return 0;
}
-#define ISO8859_7_DECODE(c, assi) \
- if ((c) < 0xa0) (assi) = (c); \
- else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \
- (assi) = (c); \
- else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \
- (0xbffffd77L & (1L << ((c)-0xb4))))) \
- (assi) = 0x02d0 + (c); \
- else if ((c) == 0xa1) (assi) = 0x2018; \
- else if ((c) == 0xa2) (assi) = 0x2019; \
- else if ((c) == 0xaf) (assi) = 0x2015;
+#define ISO8859_7_DECODE(c, assi) \
+ if ((c) < 0xa0) (assi) = (c); \
+ else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \
+ (assi) = (c); \
+ else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \
+ (0xbffffd77L & (1L << ((c)-0xb4))))) \
+ (assi) = 0x02d0 + (c); \
+ else if ((c) == 0xa1) (assi) = 0x2018; \
+ else if ((c) == 0xa2) (assi) = 0x2019; \
+ else if ((c) == 0xaf) (assi) = 0x2015;
static Py_ssize_t
iso2022processg2(const void *config, MultibyteCodec_State *state,
- const unsigned char **inbuf, Py_ssize_t *inleft,
- Py_UNICODE **outbuf, Py_ssize_t *outleft)
+ const unsigned char **inbuf, Py_ssize_t *inleft,
+ Py_UNICODE **outbuf, Py_ssize_t *outleft)
{
- /* not written to use encoder, decoder functions because only few
- * encodings use G2 designations in CJKCodecs */
- if (STATE_G2 == CHARSET_ISO8859_1) {
- if (IN3 < 0x80)
- OUT1(IN3 + 0x80)
- else
- return 3;
- }
- else if (STATE_G2 == CHARSET_ISO8859_7) {
- ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf)
- else return 3;
- }
- else if (STATE_G2 == CHARSET_ASCII) {
- if (IN3 & 0x80) return 3;
- else **outbuf = IN3;
- }
- else
- return MBERR_INTERNAL;
-
- (*inbuf) += 3;
- *inleft -= 3;
- (*outbuf) += 1;
- *outleft -= 1;
- return 0;
+ /* not written to use encoder, decoder functions because only few
+ * encodings use G2 designations in CJKCodecs */
+ if (STATE_G2 == CHARSET_ISO8859_1) {
+ if (IN3 < 0x80)
+ OUT1(IN3 + 0x80)
+ else
+ return 3;
+ }
+ else if (STATE_G2 == CHARSET_ISO8859_7) {
+ ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf)
+ else return 3;
+ }
+ else if (STATE_G2 == CHARSET_ASCII) {
+ if (IN3 & 0x80) return 3;
+ else **outbuf = IN3;
+ }
+ else
+ return MBERR_INTERNAL;
+
+ (*inbuf) += 3;
+ *inleft -= 3;
+ (*outbuf) += 1;
+ *outleft -= 1;
+ return 0;
}
DECODER(iso2022)
{
- const struct iso2022_designation *dsgcache = NULL;
-
- while (inleft > 0) {
- unsigned char c = IN1;
- Py_ssize_t err;
-
- if (STATE_GETFLAG(F_ESCTHROUGHOUT)) {
- /* ESC throughout mode:
- * for non-iso2022 escape sequences */
- WRITE1(c) /* assume as ISO-8859-1 */
- NEXT(1, 1)
- if (IS_ESCEND(c)) {
- STATE_CLEARFLAG(F_ESCTHROUGHOUT)
- }
- continue;
- }
-
- switch (c) {
- case ESC:
- REQUIRE_INBUF(2)
- if (IS_ISO2022ESC(IN2)) {
- err = iso2022processesc(config, state,
- inbuf, &inleft);
- if (err != 0)
- return err;
- }
- else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */
- REQUIRE_INBUF(3)
- err = iso2022processg2(config, state,
- inbuf, &inleft, outbuf, &outleft);
- if (err != 0)
- return err;
- }
- else {
- WRITE1(ESC)
- STATE_SETFLAG(F_ESCTHROUGHOUT)
- NEXT(1, 1)
- }
- break;
- case SI:
- if (CONFIG_ISSET(NO_SHIFT))
- goto bypass;
- STATE_CLEARFLAG(F_SHIFTED)
- NEXT_IN(1)
- break;
- case SO:
- if (CONFIG_ISSET(NO_SHIFT))
- goto bypass;
- STATE_SETFLAG(F_SHIFTED)
- NEXT_IN(1)
- break;
- case LF:
- STATE_CLEARFLAG(F_SHIFTED)
- WRITE1(LF)
- NEXT(1, 1)
- break;
- default:
- if (c < 0x20) /* C0 */
- goto bypass;
- else if (c >= 0x80)
- return 1;
- else {
- const struct iso2022_designation *dsg;
- unsigned char charset;
- ucs4_t decoded;
-
- if (STATE_GETFLAG(F_SHIFTED))
- charset = STATE_G1;
- else
- charset = STATE_G0;
-
- if (charset == CHARSET_ASCII) {
-bypass: WRITE1(c)
- NEXT(1, 1)
- break;
- }
-
- if (dsgcache != NULL &&
- dsgcache->mark == charset)
- dsg = dsgcache;
- else {
- for (dsg = CONFIG_DESIGNATIONS;
- dsg->mark != charset
+ const struct iso2022_designation *dsgcache = NULL;
+
+ while (inleft > 0) {
+ unsigned char c = IN1;
+ Py_ssize_t err;
+
+ if (STATE_GETFLAG(F_ESCTHROUGHOUT)) {
+ /* ESC throughout mode:
+ * for non-iso2022 escape sequences */
+ WRITE1(c) /* assume as ISO-8859-1 */
+ NEXT(1, 1)
+ if (IS_ESCEND(c)) {
+ STATE_CLEARFLAG(F_ESCTHROUGHOUT)
+ }
+ continue;
+ }
+
+ switch (c) {
+ case ESC:
+ REQUIRE_INBUF(2)
+ if (IS_ISO2022ESC(IN2)) {
+ err = iso2022processesc(config, state,
+ inbuf, &inleft);
+ if (err != 0)
+ return err;
+ }
+ else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */
+ REQUIRE_INBUF(3)
+ err = iso2022processg2(config, state,
+ inbuf, &inleft, outbuf, &outleft);
+ if (err != 0)
+ return err;
+ }
+ else {
+ WRITE1(ESC)
+ STATE_SETFLAG(F_ESCTHROUGHOUT)
+ NEXT(1, 1)
+ }
+ break;
+ case SI:
+ if (CONFIG_ISSET(NO_SHIFT))
+ goto bypass;
+ STATE_CLEARFLAG(F_SHIFTED)
+ NEXT_IN(1)
+ break;
+ case SO:
+ if (CONFIG_ISSET(NO_SHIFT))
+ goto bypass;
+ STATE_SETFLAG(F_SHIFTED)
+ NEXT_IN(1)
+ break;
+ case LF:
+ STATE_CLEARFLAG(F_SHIFTED)
+ WRITE1(LF)
+ NEXT(1, 1)
+ break;
+ default:
+ if (c < 0x20) /* C0 */
+ goto bypass;
+ else if (c >= 0x80)
+ return 1;
+ else {
+ const struct iso2022_designation *dsg;
+ unsigned char charset;
+ ucs4_t decoded;
+
+ if (STATE_GETFLAG(F_SHIFTED))
+ charset = STATE_G1;
+ else
+ charset = STATE_G0;
+
+ if (charset == CHARSET_ASCII) {
+bypass: WRITE1(c)
+ NEXT(1, 1)
+ break;
+ }
+
+ if (dsgcache != NULL &&
+ dsgcache->mark == charset)
+ dsg = dsgcache;
+ else {
+ for (dsg = CONFIG_DESIGNATIONS;
+ dsg->mark != charset
#ifdef Py_DEBUG
- && dsg->mark != '\0'
+ && dsg->mark != '\0'
#endif
- ;dsg++)
- /* noop */;
- assert(dsg->mark != '\0');
- dsgcache = dsg;
- }
-
- REQUIRE_INBUF(dsg->width)
- decoded = dsg->decoder(*inbuf);
- if (decoded == MAP_UNMAPPABLE)
- return dsg->width;
-
- if (decoded < 0x10000) {
- WRITE1(decoded)
- NEXT_OUT(1)
- }
- else if (decoded < 0x30000) {
- WRITEUCS4(decoded)
- }
- else { /* JIS X 0213 pairs */
- WRITE2(decoded >> 16, decoded & 0xffff)
- NEXT_OUT(2)
- }
- NEXT_IN(dsg->width)
- }
- break;
- }
- }
- return 0;
+ ;dsg++)
+ /* noop */;
+ assert(dsg->mark != '\0');
+ dsgcache = dsg;
+ }
+
+ REQUIRE_INBUF(dsg->width)
+ decoded = dsg->decoder(*inbuf);
+ if (decoded == MAP_UNMAPPABLE)
+ return dsg->width;
+
+ if (decoded < 0x10000) {
+ WRITE1(decoded)
+ NEXT_OUT(1)
+ }
+ else if (decoded < 0x30000) {
+ WRITEUCS4(decoded)
+ }
+ else { /* JIS X 0213 pairs */
+ WRITE2(decoded >> 16, decoded & 0xffff)
+ NEXT_OUT(2)
+ }
+ NEXT_IN(dsg->width)
+ }
+ break;
+ }
+ }
+ return 0;
}
/*-*- mapping table holders -*-*/
@@ -567,542 +567,542 @@ DECMAP(gb2312)
static int
ksx1001_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) ||
- IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) ||
+ IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
ksx1001_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(ksx1001, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ TRYMAP_DEC(ksx1001, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
ksx1001_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- TRYMAP_ENC(cp949, coded, *data)
- if (!(coded & 0x8000))
- return coded;
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ TRYMAP_ENC(cp949, coded, *data)
+ if (!(coded & 0x8000))
+ return coded;
+ }
+ return MAP_UNMAPPABLE;
}
static int
jisx0208_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
jisx0208_decoder(const unsigned char *data)
{
- ucs4_t u;
- if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
- return 0xff3c;
- else TRYMAP_DEC(jisx0208, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
+ return 0xff3c;
+ else TRYMAP_DEC(jisx0208, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
jisx0208_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */
- return 0x2140;
- else TRYMAP_ENC(jisxcommon, coded, *data) {
- if (!(coded & 0x8000))
- return coded;
- }
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */
+ return 0x2140;
+ else TRYMAP_ENC(jisxcommon, coded, *data) {
+ if (!(coded & 0x8000))
+ return coded;
+ }
+ }
+ return MAP_UNMAPPABLE;
}
static int
jisx0212_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
jisx0212_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(jisx0212, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ TRYMAP_DEC(jisx0212, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
jisx0212_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- TRYMAP_ENC(jisxcommon, coded, *data) {
- if (coded & 0x8000)
- return coded & 0x7fff;
- }
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ TRYMAP_ENC(jisxcommon, coded, *data) {
+ if (coded & 0x8000)
+ return coded & 0x7fff;
+ }
+ }
+ return MAP_UNMAPPABLE;
}
static int
jisx0213_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- jisx0208_init() ||
- IMPORT_MAP(jp, jisx0213_bmp,
- &jisx0213_bmp_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0213_1_bmp,
- NULL, &jisx0213_1_bmp_decmap) ||
- IMPORT_MAP(jp, jisx0213_2_bmp,
- NULL, &jisx0213_2_bmp_decmap) ||
- IMPORT_MAP(jp, jisx0213_emp,
- &jisx0213_emp_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0213_1_emp,
- NULL, &jisx0213_1_emp_decmap) ||
- IMPORT_MAP(jp, jisx0213_2_emp,
- NULL, &jisx0213_2_emp_decmap) ||
- IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap,
- &jisx0213_pair_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ jisx0208_init() ||
+ IMPORT_MAP(jp, jisx0213_bmp,
+ &jisx0213_bmp_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0213_1_bmp,
+ NULL, &jisx0213_1_bmp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_2_bmp,
+ NULL, &jisx0213_2_bmp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_emp,
+ &jisx0213_emp_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0213_1_emp,
+ NULL, &jisx0213_1_emp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_2_emp,
+ NULL, &jisx0213_2_emp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap,
+ &jisx0213_pair_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
#define config ((void *)2000)
static ucs4_t
jisx0213_2000_1_decoder(const unsigned char *data)
{
- ucs4_t u;
- EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1])
- else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
- return 0xff3c;
- else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
- u |= 0x20000;
- else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1])
+ else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
+ return 0xff3c;
+ else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
static ucs4_t
jisx0213_2000_2_decoder(const unsigned char *data)
{
- ucs4_t u;
- EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1])
- TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
- u |= 0x20000;
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1])
+ TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
#undef config
static ucs4_t
jisx0213_2004_1_decoder(const unsigned char *data)
{
- ucs4_t u;
- if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
- return 0xff3c;
- else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
- u |= 0x20000;
- else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
+ return 0xff3c;
+ else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
static ucs4_t
jisx0213_2004_2_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
- u |= 0x20000;
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
static DBCHAR
jisx0213_encoder(const ucs4_t *data, Py_ssize_t *length, void *config)
{
- DBCHAR coded;
-
- switch (*length) {
- case 1: /* first character */
- if (*data >= 0x10000) {
- if ((*data) >> 16 == 0x20000 >> 16) {
- EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data)
- else TRYMAP_ENC(jisx0213_emp, coded,
- (*data) & 0xffff)
- return coded;
- }
- return MAP_UNMAPPABLE;
- }
-
- EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data)
- else TRYMAP_ENC(jisx0213_bmp, coded, *data) {
- if (coded == MULTIC)
- return MAP_MULTIPLE_AVAIL;
- }
- else TRYMAP_ENC(jisxcommon, coded, *data) {
- if (coded & 0x8000)
- return MAP_UNMAPPABLE;
- }
- else
- return MAP_UNMAPPABLE;
- return coded;
- case 2: /* second character of unicode pair */
- coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1],
- jisx0213_pair_encmap, JISX0213_ENCPAIRS);
- if (coded == DBCINV) {
- *length = 1;
- coded = find_pairencmap((ucs2_t)data[0], 0,
- jisx0213_pair_encmap, JISX0213_ENCPAIRS);
- if (coded == DBCINV)
- return MAP_UNMAPPABLE;
- }
- else
- return coded;
- case -1: /* flush unterminated */
- *length = 1;
- coded = find_pairencmap((ucs2_t)data[0], 0,
- jisx0213_pair_encmap, JISX0213_ENCPAIRS);
- if (coded == DBCINV)
- return MAP_UNMAPPABLE;
- else
- return coded;
- default:
- return MAP_UNMAPPABLE;
- }
+ DBCHAR coded;
+
+ switch (*length) {
+ case 1: /* first character */
+ if (*data >= 0x10000) {
+ if ((*data) >> 16 == 0x20000 >> 16) {
+ EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data)
+ else TRYMAP_ENC(jisx0213_emp, coded,
+ (*data) & 0xffff)
+ return coded;
+ }
+ return MAP_UNMAPPABLE;
+ }
+
+ EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data)
+ else TRYMAP_ENC(jisx0213_bmp, coded, *data) {
+ if (coded == MULTIC)
+ return MAP_MULTIPLE_AVAIL;
+ }
+ else TRYMAP_ENC(jisxcommon, coded, *data) {
+ if (coded & 0x8000)
+ return MAP_UNMAPPABLE;
+ }
+ else
+ return MAP_UNMAPPABLE;
+ return coded;
+ case 2: /* second character of unicode pair */
+ coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1],
+ jisx0213_pair_encmap, JISX0213_ENCPAIRS);
+ if (coded == DBCINV) {
+ *length = 1;
+ coded = find_pairencmap((ucs2_t)data[0], 0,
+ jisx0213_pair_encmap, JISX0213_ENCPAIRS);
+ if (coded == DBCINV)
+ return MAP_UNMAPPABLE;
+ }
+ else
+ return coded;
+ case -1: /* flush unterminated */
+ *length = 1;
+ coded = find_pairencmap((ucs2_t)data[0], 0,
+ jisx0213_pair_encmap, JISX0213_ENCPAIRS);
+ if (coded == DBCINV)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
+ default:
+ return MAP_UNMAPPABLE;
+ }
}
static DBCHAR
jisx0213_2000_1_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return MAP_UNMAPPABLE;
- else
- return coded;
+ DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
}
static DBCHAR
jisx0213_2000_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- Py_ssize_t ilength = *length;
-
- coded = jisx0213_encoder(data, length, (void *)2000);
- switch (ilength) {
- case 1:
- if (coded == MAP_MULTIPLE_AVAIL)
- return MAP_MULTIPLE_AVAIL;
- else
- return MAP_UNMAPPABLE;
- case 2:
- if (*length != 2)
- return MAP_UNMAPPABLE;
- else
- return coded;
- default:
- return MAP_UNMAPPABLE;
- }
+ DBCHAR coded;
+ Py_ssize_t ilength = *length;
+
+ coded = jisx0213_encoder(data, length, (void *)2000);
+ switch (ilength) {
+ case 1:
+ if (coded == MAP_MULTIPLE_AVAIL)
+ return MAP_MULTIPLE_AVAIL;
+ else
+ return MAP_UNMAPPABLE;
+ case 2:
+ if (*length != 2)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
+ default:
+ return MAP_UNMAPPABLE;
+ }
}
static DBCHAR
jisx0213_2000_2_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return coded & 0x7fff;
- else
- return MAP_UNMAPPABLE;
+ DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return coded & 0x7fff;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
jisx0213_2004_1_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, NULL);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return MAP_UNMAPPABLE;
- else
- return coded;
+ DBCHAR coded = jisx0213_encoder(data, length, NULL);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
}
static DBCHAR
jisx0213_2004_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- Py_ssize_t ilength = *length;
-
- coded = jisx0213_encoder(data, length, NULL);
- switch (ilength) {
- case 1:
- if (coded == MAP_MULTIPLE_AVAIL)
- return MAP_MULTIPLE_AVAIL;
- else
- return MAP_UNMAPPABLE;
- case 2:
- if (*length != 2)
- return MAP_UNMAPPABLE;
- else
- return coded;
- default:
- return MAP_UNMAPPABLE;
- }
+ DBCHAR coded;
+ Py_ssize_t ilength = *length;
+
+ coded = jisx0213_encoder(data, length, NULL);
+ switch (ilength) {
+ case 1:
+ if (coded == MAP_MULTIPLE_AVAIL)
+ return MAP_MULTIPLE_AVAIL;
+ else
+ return MAP_UNMAPPABLE;
+ case 2:
+ if (*length != 2)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
+ default:
+ return MAP_UNMAPPABLE;
+ }
}
static DBCHAR
jisx0213_2004_2_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, NULL);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return coded & 0x7fff;
- else
- return MAP_UNMAPPABLE;
+ DBCHAR coded = jisx0213_encoder(data, length, NULL);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return coded & 0x7fff;
+ else
+ return MAP_UNMAPPABLE;
}
static ucs4_t
jisx0201_r_decoder(const unsigned char *data)
{
- ucs4_t u;
- JISX0201_R_DECODE(*data, u)
- else return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ JISX0201_R_DECODE(*data, u)
+ else return MAP_UNMAPPABLE;
+ return u;
}
static DBCHAR
jisx0201_r_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- JISX0201_R_ENCODE(*data, coded)
- else return MAP_UNMAPPABLE;
- return coded;
+ DBCHAR coded;
+ JISX0201_R_ENCODE(*data, coded)
+ else return MAP_UNMAPPABLE;
+ return coded;
}
static ucs4_t
jisx0201_k_decoder(const unsigned char *data)
{
- ucs4_t u;
- JISX0201_K_DECODE(*data ^ 0x80, u)
- else return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ JISX0201_K_DECODE(*data ^ 0x80, u)
+ else return MAP_UNMAPPABLE;
+ return u;
}
static DBCHAR
jisx0201_k_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- JISX0201_K_ENCODE(*data, coded)
- else return MAP_UNMAPPABLE;
- return coded - 0x80;
+ DBCHAR coded;
+ JISX0201_K_ENCODE(*data, coded)
+ else return MAP_UNMAPPABLE;
+ return coded - 0x80;
}
static int
gb2312_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) ||
- IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) ||
+ IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
gb2312_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(gb2312, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ TRYMAP_DEC(gb2312, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
gb2312_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- TRYMAP_ENC(gbcommon, coded, *data) {
- if (!(coded & 0x8000))
- return coded;
- }
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ TRYMAP_ENC(gbcommon, coded, *data) {
+ if (!(coded & 0x8000))
+ return coded;
+ }
+ }
+ return MAP_UNMAPPABLE;
}
static ucs4_t
dummy_decoder(const unsigned char *data)
{
- return MAP_UNMAPPABLE;
+ return MAP_UNMAPPABLE;
}
static DBCHAR
dummy_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- return MAP_UNMAPPABLE;
+ return MAP_UNMAPPABLE;
}
/*-*- registry tables -*-*/
-#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \
- ksx1001_init, \
- ksx1001_decoder, ksx1001_encoder }
-#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \
- ksx1001_init, \
- ksx1001_decoder, ksx1001_encoder }
-#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \
- NULL, \
- jisx0201_r_decoder, jisx0201_r_encoder }
-#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \
- NULL, \
- jisx0201_k_decoder, jisx0201_k_encoder }
-#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \
- jisx0208_init, \
- jisx0208_decoder, jisx0208_encoder }
-#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \
- jisx0208_init, \
- jisx0208_decoder, jisx0208_encoder }
-#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \
- jisx0212_init, \
- jisx0212_decoder, jisx0212_encoder }
-#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2000_1_decoder, \
- jisx0213_2000_1_encoder }
+#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \
+ ksx1001_init, \
+ ksx1001_decoder, ksx1001_encoder }
+#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \
+ ksx1001_init, \
+ ksx1001_decoder, ksx1001_encoder }
+#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \
+ NULL, \
+ jisx0201_r_decoder, jisx0201_r_encoder }
+#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \
+ NULL, \
+ jisx0201_k_decoder, jisx0201_k_encoder }
+#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \
+ jisx0208_init, \
+ jisx0208_decoder, jisx0208_encoder }
+#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \
+ jisx0208_init, \
+ jisx0208_decoder, jisx0208_encoder }
+#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \
+ jisx0212_init, \
+ jisx0212_decoder, jisx0212_encoder }
+#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2000_1_decoder, \
+ jisx0213_2000_1_encoder }
#define REGISTRY_JISX0213_2000_1_PAIRONLY { CHARSET_JISX0213_2000_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2000_1_decoder, \
- jisx0213_2000_1_encoder_paironly }
-#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \
- jisx0213_init, \
- jisx0213_2000_2_decoder, \
- jisx0213_2000_2_encoder }
-#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2004_1_decoder, \
- jisx0213_2004_1_encoder }
+ jisx0213_init, \
+ jisx0213_2000_1_decoder, \
+ jisx0213_2000_1_encoder_paironly }
+#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2000_2_decoder, \
+ jisx0213_2000_2_encoder }
+#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2004_1_decoder, \
+ jisx0213_2004_1_encoder }
#define REGISTRY_JISX0213_2004_1_PAIRONLY { CHARSET_JISX0213_2004_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2004_1_decoder, \
- jisx0213_2004_1_encoder_paironly }
-#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \
- jisx0213_init, \
- jisx0213_2004_2_decoder, \
- jisx0213_2004_2_encoder }
-#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \
- gb2312_init, \
- gb2312_decoder, gb2312_encoder }
-#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \
- cns11643_init, \
- cns11643_1_decoder, cns11643_1_encoder }
-#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \
- cns11643_init, \
- cns11643_2_decoder, cns11643_2_encoder }
-#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \
- NULL, dummy_decoder, dummy_encoder }
-#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \
- NULL, dummy_decoder, dummy_encoder }
-#define REGISTRY_SENTINEL { 0, }
-#define CONFIGDEF(var, attrs) \
- static const struct iso2022_config iso2022_##var##_config = { \
- attrs, iso2022_##var##_designations \
- };
+ jisx0213_init, \
+ jisx0213_2004_1_decoder, \
+ jisx0213_2004_1_encoder_paironly }
+#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2004_2_decoder, \
+ jisx0213_2004_2_encoder }
+#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \
+ gb2312_init, \
+ gb2312_decoder, gb2312_encoder }
+#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \
+ cns11643_init, \
+ cns11643_1_decoder, cns11643_1_encoder }
+#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \
+ cns11643_init, \
+ cns11643_2_decoder, cns11643_2_encoder }
+#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \
+ NULL, dummy_decoder, dummy_encoder }
+#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \
+ NULL, dummy_decoder, dummy_encoder }
+#define REGISTRY_SENTINEL { 0, }
+#define CONFIGDEF(var, attrs) \
+ static const struct iso2022_config iso2022_##var##_config = { \
+ attrs, iso2022_##var##_designations \
+ };
static const struct iso2022_designation iso2022_kr_designations[] = {
- REGISTRY_KSX1001_G1, REGISTRY_SENTINEL
+ REGISTRY_KSX1001_G1, REGISTRY_SENTINEL
};
CONFIGDEF(kr, 0)
static const struct iso2022_designation iso2022_jp_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
- REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
+ REGISTRY_SENTINEL
};
CONFIGDEF(jp, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_1_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
- REGISTRY_JISX0208_O, REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
+ REGISTRY_JISX0208_O, REGISTRY_SENTINEL
};
CONFIGDEF(jp_1, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_2_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0,
- REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
- REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0,
+ REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
+ REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL
};
CONFIGDEF(jp_2, NO_SHIFT | USE_G2 | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_2004_designations[] = {
- REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208,
- REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL
+ REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208,
+ REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL
};
CONFIGDEF(jp_2004, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_3_designations[] = {
- REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208,
- REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL
+ REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208,
+ REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL
};
CONFIGDEF(jp_3, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_ext_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
- REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
+ REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL
};
CONFIGDEF(jp_ext, NO_SHIFT | USE_JISX0208_EXT)
@@ -1111,11 +1111,11 @@ BEGIN_MAPPINGS_LIST
/* no mapping table here */
END_MAPPINGS_LIST
-#define ISO2022_CODEC(variation) { \
- "iso2022_" #variation, \
- &iso2022_##variation##_config, \
- iso2022_codec_init, \
- _STATEFUL_METHODS(iso2022) \
+#define ISO2022_CODEC(variation) { \
+ "iso2022_" #variation, \
+ &iso2022_##variation##_config, \
+ iso2022_codec_init, \
+ _STATEFUL_METHODS(iso2022) \
},
BEGIN_CODECS_LIST
diff --git a/Modules/cjkcodecs/_codecs_jp.c b/Modules/cjkcodecs/_codecs_jp.c
index f49a10b..901d3be 100644
--- a/Modules/cjkcodecs/_codecs_jp.c
+++ b/Modules/cjkcodecs/_codecs_jp.c
@@ -19,124 +19,124 @@
ENCODER(cp932)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
- unsigned char c1, c2;
-
- if (c <= 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xff61 && c <= 0xff9f) {
- WRITE1(c - 0xfec0)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xf8f0 && c <= 0xf8f3) {
- /* Windows compatibility */
- REQUIRE_OUTBUF(1)
- if (c == 0xf8f0)
- OUT1(0xa0)
- else
- OUT1(c - 0xfef1 + 0xfd)
- NEXT(1, 1)
- continue;
- }
-
- UCS4INVALID(c)
- REQUIRE_OUTBUF(2)
-
- TRYMAP_ENC(cp932ext, code, c) {
- OUT1(code >> 8)
- OUT2(code & 0xff)
- }
- else TRYMAP_ENC(jisxcommon, code, c) {
- if (code & 0x8000) /* MSB set: JIS X 0212 */
- return 1;
-
- /* JIS X 0208 */
- c1 = code >> 8;
- c2 = code & 0xff;
- c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
- c1 = (c1 - 0x21) >> 1;
- OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
- OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
- }
- else if (c >= 0xe000 && c < 0xe758) {
- /* User-defined area */
- c1 = (Py_UNICODE)(c - 0xe000) / 188;
- c2 = (Py_UNICODE)(c - 0xe000) % 188;
- OUT1(c1 + 0xf0)
- OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
- }
- else
- return 1;
-
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+ unsigned char c1, c2;
+
+ if (c <= 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xff61 && c <= 0xff9f) {
+ WRITE1(c - 0xfec0)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xf8f0 && c <= 0xf8f3) {
+ /* Windows compatibility */
+ REQUIRE_OUTBUF(1)
+ if (c == 0xf8f0)
+ OUT1(0xa0)
+ else
+ OUT1(c - 0xfef1 + 0xfd)
+ NEXT(1, 1)
+ continue;
+ }
+
+ UCS4INVALID(c)
+ REQUIRE_OUTBUF(2)
+
+ TRYMAP_ENC(cp932ext, code, c) {
+ OUT1(code >> 8)
+ OUT2(code & 0xff)
+ }
+ else TRYMAP_ENC(jisxcommon, code, c) {
+ if (code & 0x8000) /* MSB set: JIS X 0212 */
+ return 1;
+
+ /* JIS X 0208 */
+ c1 = code >> 8;
+ c2 = code & 0xff;
+ c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
+ c1 = (c1 - 0x21) >> 1;
+ OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
+ OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
+ }
+ else if (c >= 0xe000 && c < 0xe758) {
+ /* User-defined area */
+ c1 = (Py_UNICODE)(c - 0xe000) / 188;
+ c2 = (Py_UNICODE)(c - 0xe000) % 188;
+ OUT1(c1 + 0xf0)
+ OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
+ }
+ else
+ return 1;
+
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(cp932)
{
- while (inleft > 0) {
- unsigned char c = IN1, c2;
-
- REQUIRE_OUTBUF(1)
- if (c <= 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xa0 && c <= 0xdf) {
- if (c == 0xa0)
- OUT1(0xf8f0) /* half-width katakana */
- else
- OUT1(0xfec0 + c)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xfd/* && c <= 0xff*/) {
- /* Windows compatibility */
- OUT1(0xf8f1 - 0xfd + c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
- c2 = IN2;
-
- TRYMAP_DEC(cp932ext, **outbuf, c, c2);
- else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
- if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
- return 2;
-
- c = (c < 0xe0 ? c - 0x81 : c - 0xc1);
- c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
- c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21);
- c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
-
- TRYMAP_DEC(jisx0208, **outbuf, c, c2);
- else return 2;
- }
- else if (c >= 0xf0 && c <= 0xf9) {
- if ((c2 >= 0x40 && c2 <= 0x7e) ||
- (c2 >= 0x80 && c2 <= 0xfc))
- OUT1(0xe000 + 188 * (c - 0xf0) +
- (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41))
- else
- return 2;
- }
- else
- return 2;
-
- NEXT(2, 1)
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1, c2;
+
+ REQUIRE_OUTBUF(1)
+ if (c <= 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xa0 && c <= 0xdf) {
+ if (c == 0xa0)
+ OUT1(0xf8f0) /* half-width katakana */
+ else
+ OUT1(0xfec0 + c)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xfd/* && c <= 0xff*/) {
+ /* Windows compatibility */
+ OUT1(0xf8f1 - 0xfd + c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+
+ TRYMAP_DEC(cp932ext, **outbuf, c, c2);
+ else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
+ if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
+ return 2;
+
+ c = (c < 0xe0 ? c - 0x81 : c - 0xc1);
+ c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
+ c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21);
+ c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
+
+ TRYMAP_DEC(jisx0208, **outbuf, c, c2);
+ else return 2;
+ }
+ else if (c >= 0xf0 && c <= 0xf9) {
+ if ((c2 >= 0x40 && c2 <= 0x7e) ||
+ (c2 >= 0x80 && c2 <= 0xfc))
+ OUT1(0xe000 + 188 * (c - 0xf0) +
+ (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41))
+ else
+ return 2;
+ }
+ else
+ return 2;
+
+ NEXT(2, 1)
+ }
+
+ return 0;
}
@@ -146,166 +146,166 @@ DECODER(cp932)
ENCODER(euc_jis_2004)
{
- while (inleft > 0) {
- ucs4_t c = IN1;
- DBCHAR code;
- Py_ssize_t insize;
-
- if (c < 0x80) {
- WRITE1(c)
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- insize = GET_INSIZE(c);
-
- if (c <= 0xFFFF) {
- EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
- else TRYMAP_ENC(jisx0213_bmp, code, c) {
- if (code == MULTIC) {
- if (inleft < 2) {
- if (flags & MBENC_FLUSH) {
- code = find_pairencmap(
- (ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- }
- else
- return MBERR_TOOFEW;
- }
- else {
- code = find_pairencmap(
- (ucs2_t)c, (*inbuf)[1],
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV) {
- code = find_pairencmap(
- (ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- } else
- insize = 2;
- }
- }
- }
- else TRYMAP_ENC(jisxcommon, code, c);
- else if (c >= 0xff61 && c <= 0xff9f) {
- /* JIS X 0201 half-width katakana */
- WRITE2(0x8e, c - 0xfec0)
- NEXT(1, 2)
- continue;
- }
- else if (c == 0xff3c)
- /* F/W REVERSE SOLIDUS (see NOTES) */
- code = 0x2140;
- else if (c == 0xff5e)
- /* F/W TILDE (see NOTES) */
- code = 0x2232;
- else
- return 1;
- }
- else if (c >> 16 == EMPBASE >> 16) {
- EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
- else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff);
- else return insize;
- }
- else
- return insize;
-
- if (code & 0x8000) {
- /* Codeset 2 */
- WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
- NEXT(insize, 3)
- } else {
- /* Codeset 1 */
- WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
- NEXT(insize, 2)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ ucs4_t c = IN1;
+ DBCHAR code;
+ Py_ssize_t insize;
+
+ if (c < 0x80) {
+ WRITE1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ insize = GET_INSIZE(c);
+
+ if (c <= 0xFFFF) {
+ EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
+ else TRYMAP_ENC(jisx0213_bmp, code, c) {
+ if (code == MULTIC) {
+ if (inleft < 2) {
+ if (flags & MBENC_FLUSH) {
+ code = find_pairencmap(
+ (ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ }
+ else
+ return MBERR_TOOFEW;
+ }
+ else {
+ code = find_pairencmap(
+ (ucs2_t)c, (*inbuf)[1],
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV) {
+ code = find_pairencmap(
+ (ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ } else
+ insize = 2;
+ }
+ }
+ }
+ else TRYMAP_ENC(jisxcommon, code, c);
+ else if (c >= 0xff61 && c <= 0xff9f) {
+ /* JIS X 0201 half-width katakana */
+ WRITE2(0x8e, c - 0xfec0)
+ NEXT(1, 2)
+ continue;
+ }
+ else if (c == 0xff3c)
+ /* F/W REVERSE SOLIDUS (see NOTES) */
+ code = 0x2140;
+ else if (c == 0xff5e)
+ /* F/W TILDE (see NOTES) */
+ code = 0x2232;
+ else
+ return 1;
+ }
+ else if (c >> 16 == EMPBASE >> 16) {
+ EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
+ else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff);
+ else return insize;
+ }
+ else
+ return insize;
+
+ if (code & 0x8000) {
+ /* Codeset 2 */
+ WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
+ NEXT(insize, 3)
+ } else {
+ /* Codeset 1 */
+ WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
+ NEXT(insize, 2)
+ }
+ }
+
+ return 0;
}
DECODER(euc_jis_2004)
{
- while (inleft > 0) {
- unsigned char c = IN1;
- ucs4_t code;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- if (c == 0x8e) {
- /* JIS X 0201 half-width katakana */
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 >= 0xa1 && c2 <= 0xdf) {
- OUT1(0xfec0 + c2)
- NEXT(2, 1)
- }
- else
- return 2;
- }
- else if (c == 0x8f) {
- unsigned char c2, c3;
-
- REQUIRE_INBUF(3)
- c2 = IN2 ^ 0x80;
- c3 = IN3 ^ 0x80;
-
- /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */
- EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3)
- else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ;
- else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) {
- WRITEUCS4(EMPBASE | code)
- NEXT_IN(3)
- continue;
- }
- else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ;
- else return 3;
- NEXT(3, 1)
- }
- else {
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c ^= 0x80;
- c2 = IN2 ^ 0x80;
-
- /* JIS X 0213 Plane 1 */
- EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2)
- else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c;
- else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e;
- else TRYMAP_DEC(jisx0208, **outbuf, c, c2);
- else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2);
- else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) {
- WRITEUCS4(EMPBASE | code)
- NEXT_IN(2)
- continue;
- }
- else TRYMAP_DEC(jisx0213_pair, code, c, c2) {
- WRITE2(code >> 16, code & 0xffff)
- NEXT(2, 2)
- continue;
- }
- else return 2;
- NEXT(2, 1)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+ ucs4_t code;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ if (c == 0x8e) {
+ /* JIS X 0201 half-width katakana */
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 >= 0xa1 && c2 <= 0xdf) {
+ OUT1(0xfec0 + c2)
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+ else if (c == 0x8f) {
+ unsigned char c2, c3;
+
+ REQUIRE_INBUF(3)
+ c2 = IN2 ^ 0x80;
+ c3 = IN3 ^ 0x80;
+
+ /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */
+ EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3)
+ else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ;
+ else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) {
+ WRITEUCS4(EMPBASE | code)
+ NEXT_IN(3)
+ continue;
+ }
+ else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ;
+ else return 3;
+ NEXT(3, 1)
+ }
+ else {
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c ^= 0x80;
+ c2 = IN2 ^ 0x80;
+
+ /* JIS X 0213 Plane 1 */
+ EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2)
+ else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c;
+ else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e;
+ else TRYMAP_DEC(jisx0208, **outbuf, c, c2);
+ else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2);
+ else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) {
+ WRITEUCS4(EMPBASE | code)
+ NEXT_IN(2)
+ continue;
+ }
+ else TRYMAP_DEC(jisx0213_pair, code, c, c2) {
+ WRITE2(code >> 16, code & 0xffff)
+ NEXT(2, 2)
+ continue;
+ }
+ else return 2;
+ NEXT(2, 1)
+ }
+ }
+
+ return 0;
}
@@ -315,114 +315,114 @@ DECODER(euc_jis_2004)
ENCODER(euc_jp)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
-
- UCS4INVALID(c)
-
- TRYMAP_ENC(jisxcommon, code, c);
- else if (c >= 0xff61 && c <= 0xff9f) {
- /* JIS X 0201 half-width katakana */
- WRITE2(0x8e, c - 0xfec0)
- NEXT(1, 2)
- continue;
- }
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ UCS4INVALID(c)
+
+ TRYMAP_ENC(jisxcommon, code, c);
+ else if (c >= 0xff61 && c <= 0xff9f) {
+ /* JIS X 0201 half-width katakana */
+ WRITE2(0x8e, c - 0xfec0)
+ NEXT(1, 2)
+ continue;
+ }
#ifndef STRICT_BUILD
- else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */
- code = 0x2140;
- else if (c == 0xa5) { /* YEN SIGN */
- WRITE1(0x5c);
- NEXT(1, 1)
- continue;
- } else if (c == 0x203e) { /* OVERLINE */
- WRITE1(0x7e);
- NEXT(1, 1)
- continue;
- }
+ else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */
+ code = 0x2140;
+ else if (c == 0xa5) { /* YEN SIGN */
+ WRITE1(0x5c);
+ NEXT(1, 1)
+ continue;
+ } else if (c == 0x203e) { /* OVERLINE */
+ WRITE1(0x7e);
+ NEXT(1, 1)
+ continue;
+ }
#endif
- else
- return 1;
-
- if (code & 0x8000) {
- /* JIS X 0212 */
- WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
- NEXT(1, 3)
- } else {
- /* JIS X 0208 */
- WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
- NEXT(1, 2)
- }
- }
-
- return 0;
+ else
+ return 1;
+
+ if (code & 0x8000) {
+ /* JIS X 0212 */
+ WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
+ NEXT(1, 3)
+ } else {
+ /* JIS X 0208 */
+ WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
+ NEXT(1, 2)
+ }
+ }
+
+ return 0;
}
DECODER(euc_jp)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- if (c == 0x8e) {
- /* JIS X 0201 half-width katakana */
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 >= 0xa1 && c2 <= 0xdf) {
- OUT1(0xfec0 + c2)
- NEXT(2, 1)
- }
- else
- return 2;
- }
- else if (c == 0x8f) {
- unsigned char c2, c3;
-
- REQUIRE_INBUF(3)
- c2 = IN2;
- c3 = IN3;
- /* JIS X 0212 */
- TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) {
- NEXT(3, 1)
- }
- else
- return 3;
- }
- else {
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- /* JIS X 0208 */
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ if (c == 0x8e) {
+ /* JIS X 0201 half-width katakana */
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 >= 0xa1 && c2 <= 0xdf) {
+ OUT1(0xfec0 + c2)
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+ else if (c == 0x8f) {
+ unsigned char c2, c3;
+
+ REQUIRE_INBUF(3)
+ c2 = IN2;
+ c3 = IN3;
+ /* JIS X 0212 */
+ TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) {
+ NEXT(3, 1)
+ }
+ else
+ return 3;
+ }
+ else {
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ /* JIS X 0208 */
#ifndef STRICT_BUILD
- if (c == 0xa1 && c2 == 0xc0)
- /* FULL-WIDTH REVERSE SOLIDUS */
- **outbuf = 0xff3c;
- else
+ if (c == 0xa1 && c2 == 0xc0)
+ /* FULL-WIDTH REVERSE SOLIDUS */
+ **outbuf = 0xff3c;
+ else
#endif
- TRYMAP_DEC(jisx0208, **outbuf,
- c ^ 0x80, c2 ^ 0x80) ;
- else return 2;
- NEXT(2, 1)
- }
- }
-
- return 0;
+ TRYMAP_DEC(jisx0208, **outbuf,
+ c ^ 0x80, c2 ^ 0x80) ;
+ else return 2;
+ NEXT(2, 1)
+ }
+ }
+
+ return 0;
}
@@ -432,105 +432,105 @@ DECODER(euc_jp)
ENCODER(shift_jis)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
- unsigned char c1, c2;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+ unsigned char c1, c2;
#ifdef STRICT_BUILD
- JISX0201_R_ENCODE(c, code)
+ JISX0201_R_ENCODE(c, code)
#else
- if (c < 0x80) code = c;
- else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */
- else if (c == 0x203e) code = 0x7e; /* OVERLINE */
+ if (c < 0x80) code = c;
+ else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */
+ else if (c == 0x203e) code = 0x7e; /* OVERLINE */
#endif
- else JISX0201_K_ENCODE(c, code)
- else UCS4INVALID(c)
- else code = NOCHAR;
+ else JISX0201_K_ENCODE(c, code)
+ else UCS4INVALID(c)
+ else code = NOCHAR;
- if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
- REQUIRE_OUTBUF(1)
+ if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
+ REQUIRE_OUTBUF(1)
- OUT1((unsigned char)code)
- NEXT(1, 1)
- continue;
- }
+ OUT1((unsigned char)code)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_OUTBUF(2)
+ REQUIRE_OUTBUF(2)
- if (code == NOCHAR) {
- TRYMAP_ENC(jisxcommon, code, c);
+ if (code == NOCHAR) {
+ TRYMAP_ENC(jisxcommon, code, c);
#ifndef STRICT_BUILD
- else if (c == 0xff3c)
- code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */
+ else if (c == 0xff3c)
+ code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */
#endif
- else
- return 1;
-
- if (code & 0x8000) /* MSB set: JIS X 0212 */
- return 1;
- }
-
- c1 = code >> 8;
- c2 = code & 0xff;
- c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
- c1 = (c1 - 0x21) >> 1;
- OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
- OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
- NEXT(1, 2)
- }
-
- return 0;
+ else
+ return 1;
+
+ if (code & 0x8000) /* MSB set: JIS X 0212 */
+ return 1;
+ }
+
+ c1 = code >> 8;
+ c2 = code & 0xff;
+ c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
+ c1 = (c1 - 0x21) >> 1;
+ OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
+ OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(shift_jis)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
#ifdef STRICT_BUILD
- JISX0201_R_DECODE(c, **outbuf)
+ JISX0201_R_DECODE(c, **outbuf)
#else
- if (c < 0x80) **outbuf = c;
+ if (c < 0x80) **outbuf = c;
#endif
- else JISX0201_K_DECODE(c, **outbuf)
- else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
- unsigned char c1, c2;
+ else JISX0201_K_DECODE(c, **outbuf)
+ else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
+ unsigned char c1, c2;
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
- return 2;
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
+ return 2;
- c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
- c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
- c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21);
- c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
+ c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
+ c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
+ c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21);
+ c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
#ifndef STRICT_BUILD
- if (c1 == 0x21 && c2 == 0x40) {
- /* FULL-WIDTH REVERSE SOLIDUS */
- OUT1(0xff3c)
- NEXT(2, 1)
- continue;
- }
+ if (c1 == 0x21 && c2 == 0x40) {
+ /* FULL-WIDTH REVERSE SOLIDUS */
+ OUT1(0xff3c)
+ NEXT(2, 1)
+ continue;
+ }
#endif
- TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
- NEXT(2, 1)
- continue;
- }
- else
- return 2;
- }
- else
- return 2;
-
- NEXT(1, 1) /* JIS X 0201 */
- }
-
- return 0;
+ TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
+ NEXT(2, 1)
+ continue;
+ }
+ else
+ return 2;
+ }
+ else
+ return 2;
+
+ NEXT(1, 1) /* JIS X 0201 */
+ }
+
+ return 0;
}
@@ -540,167 +540,167 @@ DECODER(shift_jis)
ENCODER(shift_jis_2004)
{
- while (inleft > 0) {
- ucs4_t c = IN1;
- DBCHAR code = NOCHAR;
- int c1, c2;
- Py_ssize_t insize;
-
- JISX0201_ENCODE(c, code)
- else DECODE_SURROGATE(c)
-
- if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
- WRITE1((unsigned char)code)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_OUTBUF(2)
- insize = GET_INSIZE(c);
-
- if (code == NOCHAR) {
- if (c <= 0xffff) {
- EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
- else TRYMAP_ENC(jisx0213_bmp, code, c) {
- if (code == MULTIC) {
- if (inleft < 2) {
- if (flags & MBENC_FLUSH) {
- code = find_pairencmap
- ((ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- }
- else
- return MBERR_TOOFEW;
- }
- else {
- code = find_pairencmap(
- (ucs2_t)c, IN2,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV) {
- code = find_pairencmap(
- (ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- }
- else
- insize = 2;
- }
- }
- }
- else TRYMAP_ENC(jisxcommon, code, c) {
- /* abandon JIS X 0212 codes */
- if (code & 0x8000)
- return 1;
- }
- else return 1;
- }
- else if (c >> 16 == EMPBASE >> 16) {
- EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
- else TRYMAP_ENC(jisx0213_emp, code, c&0xffff);
- else return insize;
- }
- else
- return insize;
- }
-
- c1 = code >> 8;
- c2 = (code & 0xff) - 0x21;
-
- if (c1 & 0x80) { /* Plane 2 */
- if (c1 >= 0xee) c1 -= 0x87;
- else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49;
- else c1 -= 0x43;
- }
- else /* Plane 1 */
- c1 -= 0x21;
-
- if (c1 & 1) c2 += 0x5e;
- c1 >>= 1;
- OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1))
- OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41))
-
- NEXT(insize, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ ucs4_t c = IN1;
+ DBCHAR code = NOCHAR;
+ int c1, c2;
+ Py_ssize_t insize;
+
+ JISX0201_ENCODE(c, code)
+ else DECODE_SURROGATE(c)
+
+ if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
+ WRITE1((unsigned char)code)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_OUTBUF(2)
+ insize = GET_INSIZE(c);
+
+ if (code == NOCHAR) {
+ if (c <= 0xffff) {
+ EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
+ else TRYMAP_ENC(jisx0213_bmp, code, c) {
+ if (code == MULTIC) {
+ if (inleft < 2) {
+ if (flags & MBENC_FLUSH) {
+ code = find_pairencmap
+ ((ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ }
+ else
+ return MBERR_TOOFEW;
+ }
+ else {
+ code = find_pairencmap(
+ (ucs2_t)c, IN2,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV) {
+ code = find_pairencmap(
+ (ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ }
+ else
+ insize = 2;
+ }
+ }
+ }
+ else TRYMAP_ENC(jisxcommon, code, c) {
+ /* abandon JIS X 0212 codes */
+ if (code & 0x8000)
+ return 1;
+ }
+ else return 1;
+ }
+ else if (c >> 16 == EMPBASE >> 16) {
+ EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
+ else TRYMAP_ENC(jisx0213_emp, code, c&0xffff);
+ else return insize;
+ }
+ else
+ return insize;
+ }
+
+ c1 = code >> 8;
+ c2 = (code & 0xff) - 0x21;
+
+ if (c1 & 0x80) { /* Plane 2 */
+ if (c1 >= 0xee) c1 -= 0x87;
+ else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49;
+ else c1 -= 0x43;
+ }
+ else /* Plane 1 */
+ c1 -= 0x21;
+
+ if (c1 & 1) c2 += 0x5e;
+ c1 >>= 1;
+ OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1))
+ OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41))
+
+ NEXT(insize, 2)
+ }
+
+ return 0;
}
DECODER(shift_jis_2004)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- REQUIRE_OUTBUF(1)
- JISX0201_DECODE(c, **outbuf)
- else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){
- unsigned char c1, c2;
- ucs4_t code;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
- return 2;
-
- c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
- c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
- c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1));
- c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
-
- if (c1 < 0x5e) { /* Plane 1 */
- c1 += 0x21;
- EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf,
- c1, c2)
- else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
- NEXT_OUT(1)
- }
- else TRYMAP_DEC(jisx0213_1_bmp, **outbuf,
- c1, c2) {
- NEXT_OUT(1)
- }
- else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) {
- WRITEUCS4(EMPBASE | code)
- }
- else TRYMAP_DEC(jisx0213_pair, code, c1, c2) {
- WRITE2(code >> 16, code & 0xffff)
- NEXT_OUT(2)
- }
- else
- return 2;
- NEXT_IN(2)
- }
- else { /* Plane 2 */
- if (c1 >= 0x67) c1 += 0x07;
- else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37;
- else c1 -= 0x3d;
-
- EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf,
- c1, c2)
- else TRYMAP_DEC(jisx0213_2_bmp, **outbuf,
- c1, c2) ;
- else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) {
- WRITEUCS4(EMPBASE | code)
- NEXT_IN(2)
- continue;
- }
- else
- return 2;
- NEXT(2, 1)
- }
- continue;
- }
- else
- return 2;
-
- NEXT(1, 1) /* JIS X 0201 */
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ REQUIRE_OUTBUF(1)
+ JISX0201_DECODE(c, **outbuf)
+ else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){
+ unsigned char c1, c2;
+ ucs4_t code;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
+ return 2;
+
+ c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
+ c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
+ c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1));
+ c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
+
+ if (c1 < 0x5e) { /* Plane 1 */
+ c1 += 0x21;
+ EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf,
+ c1, c2)
+ else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
+ NEXT_OUT(1)
+ }
+ else TRYMAP_DEC(jisx0213_1_bmp, **outbuf,
+ c1, c2) {
+ NEXT_OUT(1)
+ }
+ else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) {
+ WRITEUCS4(EMPBASE | code)
+ }
+ else TRYMAP_DEC(jisx0213_pair, code, c1, c2) {
+ WRITE2(code >> 16, code & 0xffff)
+ NEXT_OUT(2)
+ }
+ else
+ return 2;
+ NEXT_IN(2)
+ }
+ else { /* Plane 2 */
+ if (c1 >= 0x67) c1 += 0x07;
+ else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37;
+ else c1 -= 0x3d;
+
+ EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf,
+ c1, c2)
+ else TRYMAP_DEC(jisx0213_2_bmp, **outbuf,
+ c1, c2) ;
+ else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) {
+ WRITEUCS4(EMPBASE | code)
+ NEXT_IN(2)
+ continue;
+ }
+ else
+ return 2;
+ NEXT(2, 1)
+ }
+ continue;
+ }
+ else
+ return 2;
+
+ NEXT(1, 1) /* JIS X 0201 */
+ }
+
+ return 0;
}
diff --git a/Modules/cjkcodecs/_codecs_kr.c b/Modules/cjkcodecs/_codecs_kr.c
index 161967e..9272e36 100644
--- a/Modules/cjkcodecs/_codecs_kr.c
+++ b/Modules/cjkcodecs/_codecs_kr.c
@@ -11,151 +11,151 @@
* EUC-KR codec
*/
-#define EUCKR_JAMO_FIRSTBYTE 0xA4
-#define EUCKR_JAMO_FILLER 0xD4
+#define EUCKR_JAMO_FIRSTBYTE 0xA4
+#define EUCKR_JAMO_FILLER 0xD4
static const unsigned char u2cgk_choseong[19] = {
- 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2,
- 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,
- 0xbc, 0xbd, 0xbe
+ 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2,
+ 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,
+ 0xbc, 0xbd, 0xbe
};
static const unsigned char u2cgk_jungseong[21] = {
- 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
- 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
- 0xcf, 0xd0, 0xd1, 0xd2, 0xd3
+ 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
+ 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+ 0xcf, 0xd0, 0xd1, 0xd2, 0xd3
};
static const unsigned char u2cgk_jongseong[28] = {
- 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
- 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0,
- 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba,
- 0xbb, 0xbc, 0xbd, 0xbe
+ 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
+ 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0,
+ 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba,
+ 0xbb, 0xbc, 0xbd, 0xbe
};
ENCODER(euc_kr)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(cp949, code, c);
- else return 1;
-
- if ((code & 0x8000) == 0) {
- /* KS X 1001 coded character */
- OUT1((code >> 8) | 0x80)
- OUT2((code & 0xFF) | 0x80)
- NEXT(1, 2)
- }
- else { /* Mapping is found in CP949 extension,
- * but we encode it in KS X 1001:1998 Annex 3,
- * make-up sequence for EUC-KR. */
-
- REQUIRE_OUTBUF(8)
-
- /* syllable composition precedence */
- OUT1(EUCKR_JAMO_FIRSTBYTE)
- OUT2(EUCKR_JAMO_FILLER)
-
- /* All codepoints in CP949 extension are in unicode
- * Hangul Syllable area. */
- assert(0xac00 <= c && c <= 0xd7a3);
- c -= 0xac00;
-
- OUT3(EUCKR_JAMO_FIRSTBYTE)
- OUT4(u2cgk_choseong[c / 588])
- NEXT_OUT(4)
-
- OUT1(EUCKR_JAMO_FIRSTBYTE)
- OUT2(u2cgk_jungseong[(c / 28) % 21])
- OUT3(EUCKR_JAMO_FIRSTBYTE)
- OUT4(u2cgk_jongseong[c % 28])
- NEXT(1, 4)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(cp949, code, c);
+ else return 1;
+
+ if ((code & 0x8000) == 0) {
+ /* KS X 1001 coded character */
+ OUT1((code >> 8) | 0x80)
+ OUT2((code & 0xFF) | 0x80)
+ NEXT(1, 2)
+ }
+ else { /* Mapping is found in CP949 extension,
+ * but we encode it in KS X 1001:1998 Annex 3,
+ * make-up sequence for EUC-KR. */
+
+ REQUIRE_OUTBUF(8)
+
+ /* syllable composition precedence */
+ OUT1(EUCKR_JAMO_FIRSTBYTE)
+ OUT2(EUCKR_JAMO_FILLER)
+
+ /* All codepoints in CP949 extension are in unicode
+ * Hangul Syllable area. */
+ assert(0xac00 <= c && c <= 0xd7a3);
+ c -= 0xac00;
+
+ OUT3(EUCKR_JAMO_FIRSTBYTE)
+ OUT4(u2cgk_choseong[c / 588])
+ NEXT_OUT(4)
+
+ OUT1(EUCKR_JAMO_FIRSTBYTE)
+ OUT2(u2cgk_jungseong[(c / 28) % 21])
+ OUT3(EUCKR_JAMO_FIRSTBYTE)
+ OUT4(u2cgk_jongseong[c % 28])
+ NEXT(1, 4)
+ }
+ }
+
+ return 0;
}
-#define NONE 127
+#define NONE 127
static const unsigned char cgk2u_choseong[] = { /* [A1, BE] */
- 0, 1, NONE, 2, NONE, NONE, 3, 4,
- 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
- 6, 7, 8, NONE, 9, 10, 11, 12,
- 13, 14, 15, 16, 17, 18
+ 0, 1, NONE, 2, NONE, NONE, 3, 4,
+ 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
+ 6, 7, 8, NONE, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18
};
static const unsigned char cgk2u_jongseong[] = { /* [A1, BE] */
- 1, 2, 3, 4, 5, 6, 7, NONE,
- 8, 9, 10, 11, 12, 13, 14, 15,
- 16, 17, NONE, 18, 19, 20, 21, 22,
- NONE, 23, 24, 25, 26, 27
+ 1, 2, 3, 4, 5, 6, 7, NONE,
+ 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, NONE, 18, 19, 20, 21, 22,
+ NONE, 23, 24, 25, 26, 27
};
DECODER(euc_kr)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
-
- if (c == EUCKR_JAMO_FIRSTBYTE &&
- IN2 == EUCKR_JAMO_FILLER) {
- /* KS X 1001:1998 Annex 3 make-up sequence */
- DBCHAR cho, jung, jong;
-
- REQUIRE_INBUF(8)
- if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE ||
- (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE ||
- (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE)
- return 8;
-
- c = (*inbuf)[3];
- if (0xa1 <= c && c <= 0xbe)
- cho = cgk2u_choseong[c - 0xa1];
- else
- cho = NONE;
-
- c = (*inbuf)[5];
- jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE;
-
- c = (*inbuf)[7];
- if (c == EUCKR_JAMO_FILLER)
- jong = 0;
- else if (0xa1 <= c && c <= 0xbe)
- jong = cgk2u_jongseong[c - 0xa1];
- else
- jong = NONE;
-
- if (cho == NONE || jung == NONE || jong == NONE)
- return 8;
-
- OUT1(0xac00 + cho*588 + jung*28 + jong);
- NEXT(8, 1)
- }
- else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
- NEXT(2, 1)
- }
- else
- return 2;
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+
+ if (c == EUCKR_JAMO_FIRSTBYTE &&
+ IN2 == EUCKR_JAMO_FILLER) {
+ /* KS X 1001:1998 Annex 3 make-up sequence */
+ DBCHAR cho, jung, jong;
+
+ REQUIRE_INBUF(8)
+ if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE ||
+ (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE ||
+ (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE)
+ return 8;
+
+ c = (*inbuf)[3];
+ if (0xa1 <= c && c <= 0xbe)
+ cho = cgk2u_choseong[c - 0xa1];
+ else
+ cho = NONE;
+
+ c = (*inbuf)[5];
+ jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE;
+
+ c = (*inbuf)[7];
+ if (c == EUCKR_JAMO_FILLER)
+ jong = 0;
+ else if (0xa1 <= c && c <= 0xbe)
+ jong = cgk2u_jongseong[c - 0xa1];
+ else
+ jong = NONE;
+
+ if (cho == NONE || jung == NONE || jong == NONE)
+ return 8;
+
+ OUT1(0xac00 + cho*588 + jung*28 + jong);
+ NEXT(8, 1)
+ }
+ else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+
+ return 0;
}
#undef NONE
@@ -166,54 +166,54 @@ DECODER(euc_kr)
ENCODER(cp949)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(cp949, code, c);
- else return 1;
-
- OUT1((code >> 8) | 0x80)
- if (code & 0x8000)
- OUT2(code & 0xFF) /* MSB set: CP949 */
- else
- OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(cp949, code, c);
+ else return 1;
+
+ OUT1((code >> 8) | 0x80)
+ if (code & 0x8000)
+ OUT2(code & 0xFF) /* MSB set: CP949 */
+ else
+ OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(cp949)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
- TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80);
- else TRYMAP_DEC(cp949ext, **outbuf, c, IN2);
- else return 2;
+ REQUIRE_INBUF(2)
+ TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80);
+ else TRYMAP_DEC(cp949ext, **outbuf, c, IN2);
+ else return 2;
- NEXT(2, 1)
- }
+ NEXT(2, 1)
+ }
- return 0;
+ return 0;
}
@@ -250,58 +250,58 @@ static const DBCHAR u2johabjamo[] = {
ENCODER(johab)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
-
- if (c >= 0xac00 && c <= 0xd7a3) {
- c -= 0xac00;
- code = 0x8000 |
- (u2johabidx_choseong[c / 588] << 10) |
- (u2johabidx_jungseong[(c / 28) % 21] << 5) |
- u2johabidx_jongseong[c % 28];
- }
- else if (c >= 0x3131 && c <= 0x3163)
- code = u2johabjamo[c - 0x3131];
- else TRYMAP_ENC(cp949, code, c) {
- unsigned char c1, c2, t2;
- unsigned short t1;
-
- assert((code & 0x8000) == 0);
- c1 = code >> 8;
- c2 = code & 0xff;
- if (((c1 >= 0x21 && c1 <= 0x2c) ||
- (c1 >= 0x4a && c1 <= 0x7d)) &&
- (c2 >= 0x21 && c2 <= 0x7e)) {
- t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) :
- (c1 - 0x21 + 0x197));
- t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21);
- OUT1(t1 >> 1)
- OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43)
- NEXT(1, 2)
- continue;
- }
- else
- return 1;
- }
- else
- return 1;
-
- OUT1(code >> 8)
- OUT2(code & 0xff)
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+
+ if (c >= 0xac00 && c <= 0xd7a3) {
+ c -= 0xac00;
+ code = 0x8000 |
+ (u2johabidx_choseong[c / 588] << 10) |
+ (u2johabidx_jungseong[(c / 28) % 21] << 5) |
+ u2johabidx_jongseong[c % 28];
+ }
+ else if (c >= 0x3131 && c <= 0x3163)
+ code = u2johabjamo[c - 0x3131];
+ else TRYMAP_ENC(cp949, code, c) {
+ unsigned char c1, c2, t2;
+ unsigned short t1;
+
+ assert((code & 0x8000) == 0);
+ c1 = code >> 8;
+ c2 = code & 0xff;
+ if (((c1 >= 0x21 && c1 <= 0x2c) ||
+ (c1 >= 0x4a && c1 <= 0x7d)) &&
+ (c2 >= 0x21 && c2 <= 0x7e)) {
+ t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) :
+ (c1 - 0x21 + 0x197));
+ t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21);
+ OUT1(t1 >> 1)
+ OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43)
+ NEXT(1, 2)
+ continue;
+ }
+ else
+ return 1;
+ }
+ else
+ return 1;
+
+ OUT1(code >> 8)
+ OUT2(code & 0xff)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
#define FILL 0xfd
@@ -347,91 +347,91 @@ static const unsigned char johabjamo_jongseong[32] = {
DECODER(johab)
{
- while (inleft > 0) {
- unsigned char c = IN1, c2;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
- c2 = IN2;
-
- if (c < 0xd8) {
- /* johab hangul */
- unsigned char c_cho, c_jung, c_jong;
- unsigned char i_cho, i_jung, i_jong;
-
- c_cho = (c >> 2) & 0x1f;
- c_jung = ((c << 3) | c2 >> 5) & 0x1f;
- c_jong = c2 & 0x1f;
-
- i_cho = johabidx_choseong[c_cho];
- i_jung = johabidx_jungseong[c_jung];
- i_jong = johabidx_jongseong[c_jong];
-
- if (i_cho == NONE || i_jung == NONE || i_jong == NONE)
- return 2;
-
- /* we don't use U+1100 hangul jamo yet. */
- if (i_cho == FILL) {
- if (i_jung == FILL) {
- if (i_jong == FILL)
- OUT1(0x3000)
- else
- OUT1(0x3100 |
- johabjamo_jongseong[c_jong])
- }
- else {
- if (i_jong == FILL)
- OUT1(0x3100 |
- johabjamo_jungseong[c_jung])
- else
- return 2;
- }
- } else {
- if (i_jung == FILL) {
- if (i_jong == FILL)
- OUT1(0x3100 |
- johabjamo_choseong[c_cho])
- else
- return 2;
- }
- else
- OUT1(0xac00 +
- i_cho * 588 +
- i_jung * 28 +
- (i_jong == FILL ? 0 : i_jong))
- }
- NEXT(2, 1)
- } else {
- /* KS X 1001 except hangul jamos and syllables */
- if (c == 0xdf || c > 0xf9 ||
- c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) ||
- (c2 & 0x7f) == 0x7f ||
- (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3)))
- return 2;
- else {
- unsigned char t1, t2;
-
- t1 = (c < 0xe0 ? 2 * (c - 0xd9) :
- 2 * c - 0x197);
- t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43);
- t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21;
- t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21;
-
- TRYMAP_DEC(ksx1001, **outbuf, t1, t2);
- else return 2;
- NEXT(2, 1)
- }
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1, c2;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+
+ if (c < 0xd8) {
+ /* johab hangul */
+ unsigned char c_cho, c_jung, c_jong;
+ unsigned char i_cho, i_jung, i_jong;
+
+ c_cho = (c >> 2) & 0x1f;
+ c_jung = ((c << 3) | c2 >> 5) & 0x1f;
+ c_jong = c2 & 0x1f;
+
+ i_cho = johabidx_choseong[c_cho];
+ i_jung = johabidx_jungseong[c_jung];
+ i_jong = johabidx_jongseong[c_jong];
+
+ if (i_cho == NONE || i_jung == NONE || i_jong == NONE)
+ return 2;
+
+ /* we don't use U+1100 hangul jamo yet. */
+ if (i_cho == FILL) {
+ if (i_jung == FILL) {
+ if (i_jong == FILL)
+ OUT1(0x3000)
+ else
+ OUT1(0x3100 |
+ johabjamo_jongseong[c_jong])
+ }
+ else {
+ if (i_jong == FILL)
+ OUT1(0x3100 |
+ johabjamo_jungseong[c_jung])
+ else
+ return 2;
+ }
+ } else {
+ if (i_jung == FILL) {
+ if (i_jong == FILL)
+ OUT1(0x3100 |
+ johabjamo_choseong[c_cho])
+ else
+ return 2;
+ }
+ else
+ OUT1(0xac00 +
+ i_cho * 588 +
+ i_jung * 28 +
+ (i_jong == FILL ? 0 : i_jong))
+ }
+ NEXT(2, 1)
+ } else {
+ /* KS X 1001 except hangul jamos and syllables */
+ if (c == 0xdf || c > 0xf9 ||
+ c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) ||
+ (c2 & 0x7f) == 0x7f ||
+ (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3)))
+ return 2;
+ else {
+ unsigned char t1, t2;
+
+ t1 = (c < 0xe0 ? 2 * (c - 0xd9) :
+ 2 * c - 0x197);
+ t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43);
+ t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21;
+ t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21;
+
+ TRYMAP_DEC(ksx1001, **outbuf, t1, t2);
+ else return 2;
+ NEXT(2, 1)
+ }
+ }
+ }
+
+ return 0;
}
#undef NONE
#undef FILL
diff --git a/Modules/cjkcodecs/_codecs_tw.c b/Modules/cjkcodecs/_codecs_tw.c
index 8ccbca1..38cf723 100644
--- a/Modules/cjkcodecs/_codecs_tw.c
+++ b/Modules/cjkcodecs/_codecs_tw.c
@@ -13,52 +13,52 @@
ENCODER(big5)
{
- while (inleft > 0) {
- Py_UNICODE c = **inbuf;
- DBCHAR code;
+ while (inleft > 0) {
+ Py_UNICODE c = **inbuf;
+ DBCHAR code;
- if (c < 0x80) {
- REQUIRE_OUTBUF(1)
- **outbuf = (unsigned char)c;
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
+ if (c < 0x80) {
+ REQUIRE_OUTBUF(1)
+ **outbuf = (unsigned char)c;
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
- REQUIRE_OUTBUF(2)
+ REQUIRE_OUTBUF(2)
- TRYMAP_ENC(big5, code, c);
- else return 1;
+ TRYMAP_ENC(big5, code, c);
+ else return 1;
- OUT1(code >> 8)
- OUT2(code & 0xFF)
- NEXT(1, 2)
- }
+ OUT1(code >> 8)
+ OUT2(code & 0xFF)
+ NEXT(1, 2)
+ }
- return 0;
+ return 0;
}
DECODER(big5)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
- TRYMAP_DEC(big5, **outbuf, c, IN2) {
- NEXT(2, 1)
- }
- else return 2;
- }
+ REQUIRE_INBUF(2)
+ TRYMAP_DEC(big5, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ }
+ else return 2;
+ }
- return 0;
+ return 0;
}
@@ -68,53 +68,53 @@ DECODER(big5)
ENCODER(cp950)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(cp950ext, code, c);
- else TRYMAP_ENC(big5, code, c);
- else return 1;
-
- OUT1(code >> 8)
- OUT2(code & 0xFF)
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(cp950ext, code, c);
+ else TRYMAP_ENC(big5, code, c);
+ else return 1;
+
+ OUT1(code >> 8)
+ OUT2(code & 0xFF)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(cp950)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
+ REQUIRE_INBUF(2)
- TRYMAP_DEC(cp950ext, **outbuf, c, IN2);
- else TRYMAP_DEC(big5, **outbuf, c, IN2);
- else return 2;
+ TRYMAP_DEC(cp950ext, **outbuf, c, IN2);
+ else TRYMAP_DEC(big5, **outbuf, c, IN2);
+ else return 2;
- NEXT(2, 1)
- }
+ NEXT(2, 1)
+ }
- return 0;
+ return 0;
}
diff --git a/Modules/cjkcodecs/alg_jisx0201.h b/Modules/cjkcodecs/alg_jisx0201.h
index 1fca06b..0bc7db5 100644
--- a/Modules/cjkcodecs/alg_jisx0201.h
+++ b/Modules/cjkcodecs/alg_jisx0201.h
@@ -1,24 +1,24 @@
-#define JISX0201_R_ENCODE(c, assi) \
- if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \
- (assi) = (c); \
- else if ((c) == 0x00a5) (assi) = 0x5c; \
- else if ((c) == 0x203e) (assi) = 0x7e;
-#define JISX0201_K_ENCODE(c, assi) \
- if ((c) >= 0xff61 && (c) <= 0xff9f) \
- (assi) = (c) - 0xfec0;
-#define JISX0201_ENCODE(c, assi) \
- JISX0201_R_ENCODE(c, assi) \
- else JISX0201_K_ENCODE(c, assi)
+#define JISX0201_R_ENCODE(c, assi) \
+ if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \
+ (assi) = (c); \
+ else if ((c) == 0x00a5) (assi) = 0x5c; \
+ else if ((c) == 0x203e) (assi) = 0x7e;
+#define JISX0201_K_ENCODE(c, assi) \
+ if ((c) >= 0xff61 && (c) <= 0xff9f) \
+ (assi) = (c) - 0xfec0;
+#define JISX0201_ENCODE(c, assi) \
+ JISX0201_R_ENCODE(c, assi) \
+ else JISX0201_K_ENCODE(c, assi)
-#define JISX0201_R_DECODE(c, assi) \
- if ((c) < 0x5c) (assi) = (c); \
- else if ((c) == 0x5c) (assi) = 0x00a5; \
- else if ((c) < 0x7e) (assi) = (c); \
- else if ((c) == 0x7e) (assi) = 0x203e; \
- else if ((c) == 0x7f) (assi) = 0x7f;
-#define JISX0201_K_DECODE(c, assi) \
- if ((c) >= 0xa1 && (c) <= 0xdf) \
- (assi) = 0xfec0 + (c);
-#define JISX0201_DECODE(c, assi) \
- JISX0201_R_DECODE(c, assi) \
- else JISX0201_K_DECODE(c, assi)
+#define JISX0201_R_DECODE(c, assi) \
+ if ((c) < 0x5c) (assi) = (c); \
+ else if ((c) == 0x5c) (assi) = 0x00a5; \
+ else if ((c) < 0x7e) (assi) = (c); \
+ else if ((c) == 0x7e) (assi) = 0x203e; \
+ else if ((c) == 0x7f) (assi) = 0x7f;
+#define JISX0201_K_DECODE(c, assi) \
+ if ((c) >= 0xa1 && (c) <= 0xdf) \
+ (assi) = 0xfec0 + (c);
+#define JISX0201_DECODE(c, assi) \
+ JISX0201_R_DECODE(c, assi) \
+ else JISX0201_K_DECODE(c, assi)
diff --git a/Modules/cjkcodecs/cjkcodecs.h b/Modules/cjkcodecs/cjkcodecs.h
index e630671..ab0682a 100644
--- a/Modules/cjkcodecs/cjkcodecs.h
+++ b/Modules/cjkcodecs/cjkcodecs.h
@@ -13,12 +13,12 @@
/* a unicode "undefined" codepoint */
-#define UNIINV 0xFFFE
+#define UNIINV 0xFFFE
/* internal-use DBCS codepoints which aren't used by any charsets */
-#define NOCHAR 0xFFFF
-#define MULTIC 0xFFFE
-#define DBCINV 0xFFFD
+#define NOCHAR 0xFFFF
+#define MULTIC 0xFFFE
+#define DBCINV 0xFFFD
/* shorter macros to save source size of mapping tables */
#define U UNIINV
@@ -27,94 +27,94 @@
#define D DBCINV
struct dbcs_index {
- const ucs2_t *map;
- unsigned char bottom, top;
+ const ucs2_t *map;
+ unsigned char bottom, top;
};
typedef struct dbcs_index decode_map;
struct widedbcs_index {
- const ucs4_t *map;
- unsigned char bottom, top;
+ const ucs4_t *map;
+ unsigned char bottom, top;
};
typedef struct widedbcs_index widedecode_map;
struct unim_index {
- const DBCHAR *map;
- unsigned char bottom, top;
+ const DBCHAR *map;
+ unsigned char bottom, top;
};
typedef struct unim_index encode_map;
struct unim_index_bytebased {
- const unsigned char *map;
- unsigned char bottom, top;
+ const unsigned char *map;
+ unsigned char bottom, top;
};
struct dbcs_map {
- const char *charset;
- const struct unim_index *encmap;
- const struct dbcs_index *decmap;
+ const char *charset;
+ const struct unim_index *encmap;
+ const struct dbcs_index *decmap;
};
struct pair_encodemap {
- ucs4_t uniseq;
- DBCHAR code;
+ ucs4_t uniseq;
+ DBCHAR code;
};
static const MultibyteCodec *codec_list;
static const struct dbcs_map *mapping_list;
-#define CODEC_INIT(encoding) \
- static int encoding##_codec_init(const void *config)
-
-#define ENCODER_INIT(encoding) \
- static int encoding##_encode_init( \
- MultibyteCodec_State *state, const void *config)
-#define ENCODER(encoding) \
- static Py_ssize_t encoding##_encode( \
- MultibyteCodec_State *state, const void *config, \
- const Py_UNICODE **inbuf, Py_ssize_t inleft, \
- unsigned char **outbuf, Py_ssize_t outleft, int flags)
-#define ENCODER_RESET(encoding) \
- static Py_ssize_t encoding##_encode_reset( \
- MultibyteCodec_State *state, const void *config, \
- unsigned char **outbuf, Py_ssize_t outleft)
-
-#define DECODER_INIT(encoding) \
- static int encoding##_decode_init( \
- MultibyteCodec_State *state, const void *config)
-#define DECODER(encoding) \
- static Py_ssize_t encoding##_decode( \
- MultibyteCodec_State *state, const void *config, \
- const unsigned char **inbuf, Py_ssize_t inleft, \
- Py_UNICODE **outbuf, Py_ssize_t outleft)
-#define DECODER_RESET(encoding) \
- static Py_ssize_t encoding##_decode_reset( \
- MultibyteCodec_State *state, const void *config)
+#define CODEC_INIT(encoding) \
+ static int encoding##_codec_init(const void *config)
+
+#define ENCODER_INIT(encoding) \
+ static int encoding##_encode_init( \
+ MultibyteCodec_State *state, const void *config)
+#define ENCODER(encoding) \
+ static Py_ssize_t encoding##_encode( \
+ MultibyteCodec_State *state, const void *config, \
+ const Py_UNICODE **inbuf, Py_ssize_t inleft, \
+ unsigned char **outbuf, Py_ssize_t outleft, int flags)
+#define ENCODER_RESET(encoding) \
+ static Py_ssize_t encoding##_encode_reset( \
+ MultibyteCodec_State *state, const void *config, \
+ unsigned char **outbuf, Py_ssize_t outleft)
+
+#define DECODER_INIT(encoding) \
+ static int encoding##_decode_init( \
+ MultibyteCodec_State *state, const void *config)
+#define DECODER(encoding) \
+ static Py_ssize_t encoding##_decode( \
+ MultibyteCodec_State *state, const void *config, \
+ const unsigned char **inbuf, Py_ssize_t inleft, \
+ Py_UNICODE **outbuf, Py_ssize_t outleft)
+#define DECODER_RESET(encoding) \
+ static Py_ssize_t encoding##_decode_reset( \
+ MultibyteCodec_State *state, const void *config)
#if Py_UNICODE_SIZE == 4
-#define UCS4INVALID(code) \
- if ((code) > 0xFFFF) \
- return 1;
+#define UCS4INVALID(code) \
+ if ((code) > 0xFFFF) \
+ return 1;
#else
-#define UCS4INVALID(code) \
- if (0) ;
+#define UCS4INVALID(code) \
+ if (0) ;
#endif
-#define NEXT_IN(i) \
- (*inbuf) += (i); \
- (inleft) -= (i);
-#define NEXT_OUT(o) \
- (*outbuf) += (o); \
- (outleft) -= (o);
-#define NEXT(i, o) \
- NEXT_IN(i) NEXT_OUT(o)
-
-#define REQUIRE_INBUF(n) \
- if (inleft < (n)) \
- return MBERR_TOOFEW;
-#define REQUIRE_OUTBUF(n) \
- if (outleft < (n)) \
- return MBERR_TOOSMALL;
+#define NEXT_IN(i) \
+ (*inbuf) += (i); \
+ (inleft) -= (i);
+#define NEXT_OUT(o) \
+ (*outbuf) += (o); \
+ (outleft) -= (o);
+#define NEXT(i, o) \
+ NEXT_IN(i) NEXT_OUT(o)
+
+#define REQUIRE_INBUF(n) \
+ if (inleft < (n)) \
+ return MBERR_TOOFEW;
+#define REQUIRE_OUTBUF(n) \
+ if (outleft < (n)) \
+ return MBERR_TOOSMALL;
#define IN1 ((*inbuf)[0])
#define IN2 ((*inbuf)[1])
@@ -126,289 +126,289 @@ static const struct dbcs_map *mapping_list;
#define OUT3(c) ((*outbuf)[2]) = (c);
#define OUT4(c) ((*outbuf)[3]) = (c);
-#define WRITE1(c1) \
- REQUIRE_OUTBUF(1) \
- (*outbuf)[0] = (c1);
-#define WRITE2(c1, c2) \
- REQUIRE_OUTBUF(2) \
- (*outbuf)[0] = (c1); \
- (*outbuf)[1] = (c2);
-#define WRITE3(c1, c2, c3) \
- REQUIRE_OUTBUF(3) \
- (*outbuf)[0] = (c1); \
- (*outbuf)[1] = (c2); \
- (*outbuf)[2] = (c3);
-#define WRITE4(c1, c2, c3, c4) \
- REQUIRE_OUTBUF(4) \
- (*outbuf)[0] = (c1); \
- (*outbuf)[1] = (c2); \
- (*outbuf)[2] = (c3); \
- (*outbuf)[3] = (c4);
+#define WRITE1(c1) \
+ REQUIRE_OUTBUF(1) \
+ (*outbuf)[0] = (c1);
+#define WRITE2(c1, c2) \
+ REQUIRE_OUTBUF(2) \
+ (*outbuf)[0] = (c1); \
+ (*outbuf)[1] = (c2);
+#define WRITE3(c1, c2, c3) \
+ REQUIRE_OUTBUF(3) \
+ (*outbuf)[0] = (c1); \
+ (*outbuf)[1] = (c2); \
+ (*outbuf)[2] = (c3);
+#define WRITE4(c1, c2, c3, c4) \
+ REQUIRE_OUTBUF(4) \
+ (*outbuf)[0] = (c1); \
+ (*outbuf)[1] = (c2); \
+ (*outbuf)[2] = (c3); \
+ (*outbuf)[3] = (c4);
#if Py_UNICODE_SIZE == 2
-# define WRITEUCS4(c) \
- REQUIRE_OUTBUF(2) \
- (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \
- (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \
- NEXT_OUT(2)
+# define WRITEUCS4(c) \
+ REQUIRE_OUTBUF(2) \
+ (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \
+ (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \
+ NEXT_OUT(2)
#else
-# define WRITEUCS4(c) \
- REQUIRE_OUTBUF(1) \
- **outbuf = (Py_UNICODE)(c); \
- NEXT_OUT(1)
+# define WRITEUCS4(c) \
+ REQUIRE_OUTBUF(1) \
+ **outbuf = (Py_UNICODE)(c); \
+ NEXT_OUT(1)
#endif
-#define _TRYMAP_ENC(m, assi, val) \
- ((m)->map != NULL && (val) >= (m)->bottom && \
- (val)<= (m)->top && ((assi) = (m)->map[(val) - \
- (m)->bottom]) != NOCHAR)
-#define TRYMAP_ENC_COND(charset, assi, uni) \
- _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff)
-#define TRYMAP_ENC(charset, assi, uni) \
- if TRYMAP_ENC_COND(charset, assi, uni)
-
-#define _TRYMAP_DEC(m, assi, val) \
- ((m)->map != NULL && (val) >= (m)->bottom && \
- (val)<= (m)->top && ((assi) = (m)->map[(val) - \
- (m)->bottom]) != UNIINV)
-#define TRYMAP_DEC(charset, assi, c1, c2) \
- if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2)
-
-#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \
- ((m)->map != NULL && (val) >= (m)->bottom && \
- (val)<= (m)->top && \
- ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \
- (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \
- (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1))
-#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \
- if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \
- assplane, asshi, asslo, (uni) & 0xff)
-#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \
- if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2)
+#define _TRYMAP_ENC(m, assi, val) \
+ ((m)->map != NULL && (val) >= (m)->bottom && \
+ (val)<= (m)->top && ((assi) = (m)->map[(val) - \
+ (m)->bottom]) != NOCHAR)
+#define TRYMAP_ENC_COND(charset, assi, uni) \
+ _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff)
+#define TRYMAP_ENC(charset, assi, uni) \
+ if TRYMAP_ENC_COND(charset, assi, uni)
+
+#define _TRYMAP_DEC(m, assi, val) \
+ ((m)->map != NULL && (val) >= (m)->bottom && \
+ (val)<= (m)->top && ((assi) = (m)->map[(val) - \
+ (m)->bottom]) != UNIINV)
+#define TRYMAP_DEC(charset, assi, c1, c2) \
+ if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2)
+
+#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \
+ ((m)->map != NULL && (val) >= (m)->bottom && \
+ (val)<= (m)->top && \
+ ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \
+ (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \
+ (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1))
+#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \
+ if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \
+ assplane, asshi, asslo, (uni) & 0xff)
+#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \
+ if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2)
#if Py_UNICODE_SIZE == 2
-#define DECODE_SURROGATE(c) \
- if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \
- REQUIRE_INBUF(2) \
- if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \
- c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \
- ((ucs4_t)(IN2) - 0xdc00); \
- } \
- }
-#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1)
+#define DECODE_SURROGATE(c) \
+ if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \
+ REQUIRE_INBUF(2) \
+ if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \
+ c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \
+ ((ucs4_t)(IN2) - 0xdc00); \
+ } \
+ }
+#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1)
#else
#define DECODE_SURROGATE(c) {;}
-#define GET_INSIZE(c) 1
+#define GET_INSIZE(c) 1
#endif
#define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = {
#define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL},
#define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap},
#define MAPPING_ENCDEC(enc) {#enc, (void*)enc##_encmap, (void*)enc##_decmap},
-#define END_MAPPINGS_LIST \
- {"", NULL, NULL} }; \
- static const struct dbcs_map *mapping_list = \
- (const struct dbcs_map *)_mapping_list;
+#define END_MAPPINGS_LIST \
+ {"", NULL, NULL} }; \
+ static const struct dbcs_map *mapping_list = \
+ (const struct dbcs_map *)_mapping_list;
#define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = {
-#define _STATEFUL_METHODS(enc) \
- enc##_encode, \
- enc##_encode_init, \
- enc##_encode_reset, \
- enc##_decode, \
- enc##_decode_init, \
- enc##_decode_reset,
-#define _STATELESS_METHODS(enc) \
- enc##_encode, NULL, NULL, \
- enc##_decode, NULL, NULL,
-#define CODEC_STATEFUL(enc) { \
- #enc, NULL, NULL, \
- _STATEFUL_METHODS(enc) \
+#define _STATEFUL_METHODS(enc) \
+ enc##_encode, \
+ enc##_encode_init, \
+ enc##_encode_reset, \
+ enc##_decode, \
+ enc##_decode_init, \
+ enc##_decode_reset,
+#define _STATELESS_METHODS(enc) \
+ enc##_encode, NULL, NULL, \
+ enc##_decode, NULL, NULL,
+#define CODEC_STATEFUL(enc) { \
+ #enc, NULL, NULL, \
+ _STATEFUL_METHODS(enc) \
},
-#define CODEC_STATELESS(enc) { \
- #enc, NULL, NULL, \
- _STATELESS_METHODS(enc) \
+#define CODEC_STATELESS(enc) { \
+ #enc, NULL, NULL, \
+ _STATELESS_METHODS(enc) \
},
-#define CODEC_STATELESS_WINIT(enc) { \
- #enc, NULL, \
- enc##_codec_init, \
- _STATELESS_METHODS(enc) \
+#define CODEC_STATELESS_WINIT(enc) { \
+ #enc, NULL, \
+ enc##_codec_init, \
+ _STATELESS_METHODS(enc) \
},
-#define END_CODECS_LIST \
- {"", NULL,} }; \
- static const MultibyteCodec *codec_list = \
- (const MultibyteCodec *)_codec_list;
+#define END_CODECS_LIST \
+ {"", NULL,} }; \
+ static const MultibyteCodec *codec_list = \
+ (const MultibyteCodec *)_codec_list;
static PyObject *
getmultibytecodec(void)
{
- static PyObject *cofunc = NULL;
-
- if (cofunc == NULL) {
- PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec");
- if (mod == NULL)
- return NULL;
- cofunc = PyObject_GetAttrString(mod, "__create_codec");
- Py_DECREF(mod);
- }
- return cofunc;
+ static PyObject *cofunc = NULL;
+
+ if (cofunc == NULL) {
+ PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec");
+ if (mod == NULL)
+ return NULL;
+ cofunc = PyObject_GetAttrString(mod, "__create_codec");
+ Py_DECREF(mod);
+ }
+ return cofunc;
}
static PyObject *
getcodec(PyObject *self, PyObject *encoding)
{
- PyObject *codecobj, *r, *cofunc;
- const MultibyteCodec *codec;
- const char *enc;
-
- if (!PyUnicode_Check(encoding)) {
- PyErr_SetString(PyExc_TypeError,
- "encoding name must be a string.");
- return NULL;
- }
- enc = _PyUnicode_AsString(encoding);
- if (enc == NULL)
- return NULL;
-
- cofunc = getmultibytecodec();
- if (cofunc == NULL)
- return NULL;
-
- for (codec = codec_list; codec->encoding[0]; codec++)
- if (strcmp(codec->encoding, enc) == 0)
- break;
-
- if (codec->encoding[0] == '\0') {
- PyErr_SetString(PyExc_LookupError,
- "no such codec is supported.");
- return NULL;
- }
-
- codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
- if (codecobj == NULL)
- return NULL;
-
- r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL);
- Py_DECREF(codecobj);
-
- return r;
+ PyObject *codecobj, *r, *cofunc;
+ const MultibyteCodec *codec;
+ const char *enc;
+
+ if (!PyUnicode_Check(encoding)) {
+ PyErr_SetString(PyExc_TypeError,
+ "encoding name must be a string.");
+ return NULL;
+ }
+ enc = _PyUnicode_AsString(encoding);
+ if (enc == NULL)
+ return NULL;
+
+ cofunc = getmultibytecodec();
+ if (cofunc == NULL)
+ return NULL;
+
+ for (codec = codec_list; codec->encoding[0]; codec++)
+ if (strcmp(codec->encoding, enc) == 0)
+ break;
+
+ if (codec->encoding[0] == '\0') {
+ PyErr_SetString(PyExc_LookupError,
+ "no such codec is supported.");
+ return NULL;
+ }
+
+ codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
+ if (codecobj == NULL)
+ return NULL;
+
+ r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL);
+ Py_DECREF(codecobj);
+
+ return r;
}
static struct PyMethodDef __methods[] = {
- {"getcodec", (PyCFunction)getcodec, METH_O, ""},
- {NULL, NULL},
+ {"getcodec", (PyCFunction)getcodec, METH_O, ""},
+ {NULL, NULL},
};
static int
register_maps(PyObject *module)
{
- const struct dbcs_map *h;
-
- for (h = mapping_list; h->charset[0] != '\0'; h++) {
- char mhname[256] = "__map_";
- int r;
- strcpy(mhname + sizeof("__map_") - 1, h->charset);
- r = PyModule_AddObject(module, mhname,
- PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL));
- if (r == -1)
- return -1;
- }
- return 0;
+ const struct dbcs_map *h;
+
+ for (h = mapping_list; h->charset[0] != '\0'; h++) {
+ char mhname[256] = "__map_";
+ int r;
+ strcpy(mhname + sizeof("__map_") - 1, h->charset);
+ r = PyModule_AddObject(module, mhname,
+ PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL));
+ if (r == -1)
+ return -1;
+ }
+ return 0;
}
#ifdef USING_BINARY_PAIR_SEARCH
static DBCHAR
find_pairencmap(ucs2_t body, ucs2_t modifier,
- const struct pair_encodemap *haystack, int haystacksize)
+ const struct pair_encodemap *haystack, int haystacksize)
{
- int pos, min, max;
- ucs4_t value = body << 16 | modifier;
-
- min = 0;
- max = haystacksize;
-
- for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
- if (value < haystack[pos].uniseq) {
- if (max == pos) break;
- else max = pos;
- }
- else if (value > haystack[pos].uniseq) {
- if (min == pos) break;
- else min = pos;
- }
- else
- break;
-
- if (value == haystack[pos].uniseq)
- return haystack[pos].code;
- else
- return DBCINV;
+ int pos, min, max;
+ ucs4_t value = body << 16 | modifier;
+
+ min = 0;
+ max = haystacksize;
+
+ for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
+ if (value < haystack[pos].uniseq) {
+ if (max == pos) break;
+ else max = pos;
+ }
+ else if (value > haystack[pos].uniseq) {
+ if (min == pos) break;
+ else min = pos;
+ }
+ else
+ break;
+
+ if (value == haystack[pos].uniseq)
+ return haystack[pos].code;
+ else
+ return DBCINV;
}
#endif
#ifdef USING_IMPORTED_MAPS
#define IMPORT_MAP(locale, charset, encmap, decmap) \
- importmap("_codecs_" #locale, "__map_" #charset, \
- (const void**)encmap, (const void**)decmap)
+ importmap("_codecs_" #locale, "__map_" #charset, \
+ (const void**)encmap, (const void**)decmap)
static int
importmap(const char *modname, const char *symbol,
- const void **encmap, const void **decmap)
+ const void **encmap, const void **decmap)
{
- PyObject *o, *mod;
-
- mod = PyImport_ImportModule((char *)modname);
- if (mod == NULL)
- return -1;
-
- o = PyObject_GetAttrString(mod, (char*)symbol);
- if (o == NULL)
- goto errorexit;
- else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) {
- PyErr_SetString(PyExc_ValueError,
- "map data must be a Capsule.");
- goto errorexit;
- }
- else {
- struct dbcs_map *map;
- map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME);
- if (encmap != NULL)
- *encmap = map->encmap;
- if (decmap != NULL)
- *decmap = map->decmap;
- Py_DECREF(o);
- }
-
- Py_DECREF(mod);
- return 0;
+ PyObject *o, *mod;
+
+ mod = PyImport_ImportModule((char *)modname);
+ if (mod == NULL)
+ return -1;
+
+ o = PyObject_GetAttrString(mod, (char*)symbol);
+ if (o == NULL)
+ goto errorexit;
+ else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) {
+ PyErr_SetString(PyExc_ValueError,
+ "map data must be a Capsule.");
+ goto errorexit;
+ }
+ else {
+ struct dbcs_map *map;
+ map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME);
+ if (encmap != NULL)
+ *encmap = map->encmap;
+ if (decmap != NULL)
+ *decmap = map->decmap;
+ Py_DECREF(o);
+ }
+
+ Py_DECREF(mod);
+ return 0;
errorexit:
- Py_DECREF(mod);
- return -1;
+ Py_DECREF(mod);
+ return -1;
}
#endif
-#define I_AM_A_MODULE_FOR(loc) \
- static struct PyModuleDef __module = { \
- PyModuleDef_HEAD_INIT, \
- "_codecs_"#loc, \
- NULL, \
- 0, \
- __methods, \
- NULL, \
- NULL, \
- NULL, \
- NULL \
- }; \
- PyObject* \
- PyInit__codecs_##loc(void) \
- { \
- PyObject *m = PyModule_Create(&__module); \
- if (m != NULL) \
- (void)register_maps(m); \
- return m; \
- }
+#define I_AM_A_MODULE_FOR(loc) \
+ static struct PyModuleDef __module = { \
+ PyModuleDef_HEAD_INIT, \
+ "_codecs_"#loc, \
+ NULL, \
+ 0, \
+ __methods, \
+ NULL, \
+ NULL, \
+ NULL, \
+ NULL \
+ }; \
+ PyObject* \
+ PyInit__codecs_##loc(void) \
+ { \
+ PyObject *m = PyModule_Create(&__module); \
+ if (m != NULL) \
+ (void)register_maps(m); \
+ return m; \
+ }
#endif
diff --git a/Modules/cjkcodecs/emu_jisx0213_2000.h b/Modules/cjkcodecs/emu_jisx0213_2000.h
index 250c673..4227fb2 100644
--- a/Modules/cjkcodecs/emu_jisx0213_2000.h
+++ b/Modules/cjkcodecs/emu_jisx0213_2000.h
@@ -5,39 +5,39 @@
#define EMULATE_JISX0213_2000_ENCODE_INVALID 1
#endif
-#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \
- if (config == (void *)2000 && ( \
- (c) == 0x9B1C || (c) == 0x4FF1 || \
- (c) == 0x525D || (c) == 0x541E || \
- (c) == 0x5653 || (c) == 0x59F8 || \
- (c) == 0x5C5B || (c) == 0x5E77 || \
- (c) == 0x7626 || (c) == 0x7E6B)) \
- return EMULATE_JISX0213_2000_ENCODE_INVALID; \
- else if (config == (void *)2000 && (c) == 0x9B1D) \
- (assi) = 0x8000 | 0x7d3b; \
+#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \
+ if (config == (void *)2000 && ( \
+ (c) == 0x9B1C || (c) == 0x4FF1 || \
+ (c) == 0x525D || (c) == 0x541E || \
+ (c) == 0x5653 || (c) == 0x59F8 || \
+ (c) == 0x5C5B || (c) == 0x5E77 || \
+ (c) == 0x7626 || (c) == 0x7E6B)) \
+ return EMULATE_JISX0213_2000_ENCODE_INVALID; \
+ else if (config == (void *)2000 && (c) == 0x9B1D) \
+ (assi) = 0x8000 | 0x7d3b; \
-#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \
- if (config == (void *)2000 && (c) == 0x20B9F) \
- return EMULATE_JISX0213_2000_ENCODE_INVALID;
+#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \
+ if (config == (void *)2000 && (c) == 0x20B9F) \
+ return EMULATE_JISX0213_2000_ENCODE_INVALID;
#ifndef EMULATE_JISX0213_2000_DECODE_INVALID
#define EMULATE_JISX0213_2000_DECODE_INVALID 2
#endif
-#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \
- if (config == (void *)2000 && \
- (((c1) == 0x2E && (c2) == 0x21) || \
- ((c1) == 0x2F && (c2) == 0x7E) || \
- ((c1) == 0x4F && (c2) == 0x54) || \
- ((c1) == 0x4F && (c2) == 0x7E) || \
- ((c1) == 0x74 && (c2) == 0x27) || \
- ((c1) == 0x7E && (c2) == 0x7A) || \
- ((c1) == 0x7E && (c2) == 0x7B) || \
- ((c1) == 0x7E && (c2) == 0x7C) || \
- ((c1) == 0x7E && (c2) == 0x7D) || \
- ((c1) == 0x7E && (c2) == 0x7E))) \
- return EMULATE_JISX0213_2000_DECODE_INVALID;
+#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \
+ if (config == (void *)2000 && \
+ (((c1) == 0x2E && (c2) == 0x21) || \
+ ((c1) == 0x2F && (c2) == 0x7E) || \
+ ((c1) == 0x4F && (c2) == 0x54) || \
+ ((c1) == 0x4F && (c2) == 0x7E) || \
+ ((c1) == 0x74 && (c2) == 0x27) || \
+ ((c1) == 0x7E && (c2) == 0x7A) || \
+ ((c1) == 0x7E && (c2) == 0x7B) || \
+ ((c1) == 0x7E && (c2) == 0x7C) || \
+ ((c1) == 0x7E && (c2) == 0x7D) || \
+ ((c1) == 0x7E && (c2) == 0x7E))) \
+ return EMULATE_JISX0213_2000_DECODE_INVALID;
-#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \
- if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \
- (assi) = 0x9B1D;
+#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \
+ if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \
+ (assi) = 0x9B1D;
diff --git a/Modules/cjkcodecs/multibytecodec.c b/Modules/cjkcodecs/multibytecodec.c
index 1735dfd..af7ea5b 100644
--- a/Modules/cjkcodecs/multibytecodec.c
+++ b/Modules/cjkcodecs/multibytecodec.c
@@ -45,179 +45,179 @@ static char *incrementalkwarglist[] = {"input", "final", NULL};
static char *streamkwarglist[] = {"stream", "errors", NULL};
static PyObject *multibytecodec_encode(MultibyteCodec *,
- MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t,
- PyObject *, int);
+ MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t,
+ PyObject *, int);
-#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */
+#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */
static PyObject *
make_tuple(PyObject *object, Py_ssize_t len)
{
- PyObject *v, *w;
-
- if (object == NULL)
- return NULL;
-
- v = PyTuple_New(2);
- if (v == NULL) {
- Py_DECREF(object);
- return NULL;
- }
- PyTuple_SET_ITEM(v, 0, object);
-
- w = PyLong_FromSsize_t(len);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyTuple_SET_ITEM(v, 1, w);
-
- return v;
+ PyObject *v, *w;
+
+ if (object == NULL)
+ return NULL;
+
+ v = PyTuple_New(2);
+ if (v == NULL) {
+ Py_DECREF(object);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(v, 0, object);
+
+ w = PyLong_FromSsize_t(len);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(v, 1, w);
+
+ return v;
}
static PyObject *
internal_error_callback(const char *errors)
{
- if (errors == NULL || strcmp(errors, "strict") == 0)
- return ERROR_STRICT;
- else if (strcmp(errors, "ignore") == 0)
- return ERROR_IGNORE;
- else if (strcmp(errors, "replace") == 0)
- return ERROR_REPLACE;
- else
- return PyUnicode_FromString(errors);
+ if (errors == NULL || strcmp(errors, "strict") == 0)
+ return ERROR_STRICT;
+ else if (strcmp(errors, "ignore") == 0)
+ return ERROR_IGNORE;
+ else if (strcmp(errors, "replace") == 0)
+ return ERROR_REPLACE;
+ else
+ return PyUnicode_FromString(errors);
}
static PyObject *
call_error_callback(PyObject *errors, PyObject *exc)
{
- PyObject *args, *cb, *r;
- const char *str;
-
- assert(PyUnicode_Check(errors));
- str = _PyUnicode_AsString(errors);
- if (str == NULL)
- return NULL;
- cb = PyCodec_LookupError(str);
- if (cb == NULL)
- return NULL;
-
- args = PyTuple_New(1);
- if (args == NULL) {
- Py_DECREF(cb);
- return NULL;
- }
-
- PyTuple_SET_ITEM(args, 0, exc);
- Py_INCREF(exc);
-
- r = PyObject_CallObject(cb, args);
- Py_DECREF(args);
- Py_DECREF(cb);
- return r;
+ PyObject *args, *cb, *r;
+ const char *str;
+
+ assert(PyUnicode_Check(errors));
+ str = _PyUnicode_AsString(errors);
+ if (str == NULL)
+ return NULL;
+ cb = PyCodec_LookupError(str);
+ if (cb == NULL)
+ return NULL;
+
+ args = PyTuple_New(1);
+ if (args == NULL) {
+ Py_DECREF(cb);
+ return NULL;
+ }
+
+ PyTuple_SET_ITEM(args, 0, exc);
+ Py_INCREF(exc);
+
+ r = PyObject_CallObject(cb, args);
+ Py_DECREF(args);
+ Py_DECREF(cb);
+ return r;
}
static PyObject *
codecctx_errors_get(MultibyteStatefulCodecContext *self)
{
- const char *errors;
-
- if (self->errors == ERROR_STRICT)
- errors = "strict";
- else if (self->errors == ERROR_IGNORE)
- errors = "ignore";
- else if (self->errors == ERROR_REPLACE)
- errors = "replace";
- else {
- Py_INCREF(self->errors);
- return self->errors;
- }
-
- return PyUnicode_FromString(errors);
+ const char *errors;
+
+ if (self->errors == ERROR_STRICT)
+ errors = "strict";
+ else if (self->errors == ERROR_IGNORE)
+ errors = "ignore";
+ else if (self->errors == ERROR_REPLACE)
+ errors = "replace";
+ else {
+ Py_INCREF(self->errors);
+ return self->errors;
+ }
+
+ return PyUnicode_FromString(errors);
}
static int
codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value,
- void *closure)
+ void *closure)
{
- PyObject *cb;
- const char *str;
+ PyObject *cb;
+ const char *str;
- if (!PyUnicode_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "errors must be a string");
- return -1;
- }
+ if (!PyUnicode_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "errors must be a string");
+ return -1;
+ }
- str = _PyUnicode_AsString(value);
- if (str == NULL)
- return -1;
+ str = _PyUnicode_AsString(value);
+ if (str == NULL)
+ return -1;
- cb = internal_error_callback(str);
- if (cb == NULL)
- return -1;
+ cb = internal_error_callback(str);
+ if (cb == NULL)
+ return -1;
- ERROR_DECREF(self->errors);
- self->errors = cb;
- return 0;
+ ERROR_DECREF(self->errors);
+ self->errors = cb;
+ return 0;
}
/* This getset handlers list is used by all the stateful codec objects */
static PyGetSetDef codecctx_getsets[] = {
- {"errors", (getter)codecctx_errors_get,
- (setter)codecctx_errors_set,
- PyDoc_STR("how to treat errors")},
- {NULL,}
+ {"errors", (getter)codecctx_errors_get,
+ (setter)codecctx_errors_set,
+ PyDoc_STR("how to treat errors")},
+ {NULL,}
};
static int
expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize)
{
- Py_ssize_t orgpos, orgsize, incsize;
+ Py_ssize_t orgpos, orgsize, incsize;
- orgpos = (Py_ssize_t)((char *)buf->outbuf -
- PyBytes_AS_STRING(buf->outobj));
- orgsize = PyBytes_GET_SIZE(buf->outobj);
- incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
+ orgpos = (Py_ssize_t)((char *)buf->outbuf -
+ PyBytes_AS_STRING(buf->outobj));
+ orgsize = PyBytes_GET_SIZE(buf->outobj);
+ incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
- if (orgsize > PY_SSIZE_T_MAX - incsize)
- return -1;
+ if (orgsize > PY_SSIZE_T_MAX - incsize)
+ return -1;
- if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1)
- return -1;
+ if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1)
+ return -1;
- buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos;
- buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj)
- + PyBytes_GET_SIZE(buf->outobj);
+ buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos;
+ buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj)
+ + PyBytes_GET_SIZE(buf->outobj);
- return 0;
+ return 0;
}
-#define REQUIRE_ENCODEBUFFER(buf, s) { \
- if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
- if (expand_encodebuffer(buf, s) == -1) \
- goto errorexit; \
+#define REQUIRE_ENCODEBUFFER(buf, s) { \
+ if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
+ if (expand_encodebuffer(buf, s) == -1) \
+ goto errorexit; \
}
static int
expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
{
- Py_ssize_t orgpos, orgsize;
+ Py_ssize_t orgpos, orgsize;
- orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj));
- orgsize = PyUnicode_GET_SIZE(buf->outobj);
- if (PyUnicode_Resize(&buf->outobj, orgsize + (
- esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1)
- return -1;
+ orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj));
+ orgsize = PyUnicode_GET_SIZE(buf->outobj);
+ if (PyUnicode_Resize(&buf->outobj, orgsize + (
+ esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1)
+ return -1;
- buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos;
- buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj)
- + PyUnicode_GET_SIZE(buf->outobj);
+ buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos;
+ buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj)
+ + PyUnicode_GET_SIZE(buf->outobj);
- return 0;
+ return 0;
}
-#define REQUIRE_DECODEBUFFER(buf, s) { \
- if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
- if (expand_decodebuffer(buf, s) == -1) \
- goto errorexit; \
+#define REQUIRE_DECODEBUFFER(buf, s) { \
+ if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
+ if (expand_decodebuffer(buf, s) == -1) \
+ goto errorexit; \
}
@@ -227,504 +227,504 @@ expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
static int
multibytecodec_encerror(MultibyteCodec *codec,
- MultibyteCodec_State *state,
- MultibyteEncodeBuffer *buf,
- PyObject *errors, Py_ssize_t e)
+ MultibyteCodec_State *state,
+ MultibyteEncodeBuffer *buf,
+ PyObject *errors, Py_ssize_t e)
{
- PyObject *retobj = NULL, *retstr = NULL, *tobj;
- Py_ssize_t retstrsize, newpos;
- Py_ssize_t esize, start, end;
- const char *reason;
-
- if (e > 0) {
- reason = "illegal multibyte sequence";
- esize = e;
- }
- else {
- switch (e) {
- case MBERR_TOOSMALL:
- REQUIRE_ENCODEBUFFER(buf, -1);
- return 0; /* retry it */
- case MBERR_TOOFEW:
- reason = "incomplete multibyte sequence";
- esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- break;
- case MBERR_INTERNAL:
- PyErr_SetString(PyExc_RuntimeError,
- "internal codec error");
- return -1;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "unknown runtime error");
- return -1;
- }
- }
-
- if (errors == ERROR_REPLACE) {
- const Py_UNICODE replchar = '?', *inbuf = &replchar;
- Py_ssize_t r;
-
- for (;;) {
- Py_ssize_t outleft;
-
- outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
- r = codec->encode(state, codec->config, &inbuf, 1,
- &buf->outbuf, outleft, 0);
- if (r == MBERR_TOOSMALL) {
- REQUIRE_ENCODEBUFFER(buf, -1);
- continue;
- }
- else
- break;
- }
-
- if (r != 0) {
- REQUIRE_ENCODEBUFFER(buf, 1);
- *buf->outbuf++ = '?';
- }
- }
- if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
- buf->inbuf += esize;
- return 0;
- }
-
- start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
- end = start + esize;
-
- /* use cached exception object if available */
- if (buf->excobj == NULL) {
- buf->excobj = PyUnicodeEncodeError_Create(codec->encoding,
- buf->inbuf_top,
- buf->inbuf_end - buf->inbuf_top,
- start, end, reason);
- if (buf->excobj == NULL)
- goto errorexit;
- }
- else
- if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 ||
- PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 ||
- PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0)
- goto errorexit;
-
- if (errors == ERROR_STRICT) {
- PyCodec_StrictErrors(buf->excobj);
- goto errorexit;
- }
-
- retobj = call_error_callback(errors, buf->excobj);
- if (retobj == NULL)
- goto errorexit;
-
- if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
- !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) ||
- !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) {
- PyErr_SetString(PyExc_TypeError,
- "encoding error handler must return "
- "(unicode, int) tuple");
- goto errorexit;
- }
-
- {
- const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj);
-
- retstr = multibytecodec_encode(codec, state, &uraw,
- PyUnicode_GET_SIZE(tobj), ERROR_STRICT,
- MBENC_FLUSH);
- if (retstr == NULL)
- goto errorexit;
- }
-
- assert(PyBytes_Check(retstr));
- retstrsize = PyBytes_GET_SIZE(retstr);
- REQUIRE_ENCODEBUFFER(buf, retstrsize);
-
- memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize);
- buf->outbuf += retstrsize;
-
- newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
- if (newpos < 0 && !PyErr_Occurred())
- newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
- if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
- PyErr_Clear();
- PyErr_Format(PyExc_IndexError,
- "position %zd from error handler out of bounds",
- newpos);
- goto errorexit;
- }
- buf->inbuf = buf->inbuf_top + newpos;
-
- Py_DECREF(retobj);
- Py_DECREF(retstr);
- return 0;
+ PyObject *retobj = NULL, *retstr = NULL, *tobj;
+ Py_ssize_t retstrsize, newpos;
+ Py_ssize_t esize, start, end;
+ const char *reason;
+
+ if (e > 0) {
+ reason = "illegal multibyte sequence";
+ esize = e;
+ }
+ else {
+ switch (e) {
+ case MBERR_TOOSMALL:
+ REQUIRE_ENCODEBUFFER(buf, -1);
+ return 0; /* retry it */
+ case MBERR_TOOFEW:
+ reason = "incomplete multibyte sequence";
+ esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ break;
+ case MBERR_INTERNAL:
+ PyErr_SetString(PyExc_RuntimeError,
+ "internal codec error");
+ return -1;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "unknown runtime error");
+ return -1;
+ }
+ }
+
+ if (errors == ERROR_REPLACE) {
+ const Py_UNICODE replchar = '?', *inbuf = &replchar;
+ Py_ssize_t r;
+
+ for (;;) {
+ Py_ssize_t outleft;
+
+ outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
+ r = codec->encode(state, codec->config, &inbuf, 1,
+ &buf->outbuf, outleft, 0);
+ if (r == MBERR_TOOSMALL) {
+ REQUIRE_ENCODEBUFFER(buf, -1);
+ continue;
+ }
+ else
+ break;
+ }
+
+ if (r != 0) {
+ REQUIRE_ENCODEBUFFER(buf, 1);
+ *buf->outbuf++ = '?';
+ }
+ }
+ if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
+ buf->inbuf += esize;
+ return 0;
+ }
+
+ start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
+ end = start + esize;
+
+ /* use cached exception object if available */
+ if (buf->excobj == NULL) {
+ buf->excobj = PyUnicodeEncodeError_Create(codec->encoding,
+ buf->inbuf_top,
+ buf->inbuf_end - buf->inbuf_top,
+ start, end, reason);
+ if (buf->excobj == NULL)
+ goto errorexit;
+ }
+ else
+ if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 ||
+ PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 ||
+ PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0)
+ goto errorexit;
+
+ if (errors == ERROR_STRICT) {
+ PyCodec_StrictErrors(buf->excobj);
+ goto errorexit;
+ }
+
+ retobj = call_error_callback(errors, buf->excobj);
+ if (retobj == NULL)
+ goto errorexit;
+
+ if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
+ !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) ||
+ !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) {
+ PyErr_SetString(PyExc_TypeError,
+ "encoding error handler must return "
+ "(unicode, int) tuple");
+ goto errorexit;
+ }
+
+ {
+ const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj);
+
+ retstr = multibytecodec_encode(codec, state, &uraw,
+ PyUnicode_GET_SIZE(tobj), ERROR_STRICT,
+ MBENC_FLUSH);
+ if (retstr == NULL)
+ goto errorexit;
+ }
+
+ assert(PyBytes_Check(retstr));
+ retstrsize = PyBytes_GET_SIZE(retstr);
+ REQUIRE_ENCODEBUFFER(buf, retstrsize);
+
+ memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize);
+ buf->outbuf += retstrsize;
+
+ newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
+ if (newpos < 0 && !PyErr_Occurred())
+ newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
+ if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
+ PyErr_Clear();
+ PyErr_Format(PyExc_IndexError,
+ "position %zd from error handler out of bounds",
+ newpos);
+ goto errorexit;
+ }
+ buf->inbuf = buf->inbuf_top + newpos;
+
+ Py_DECREF(retobj);
+ Py_DECREF(retstr);
+ return 0;
errorexit:
- Py_XDECREF(retobj);
- Py_XDECREF(retstr);
- return -1;
+ Py_XDECREF(retobj);
+ Py_XDECREF(retstr);
+ return -1;
}
static int
multibytecodec_decerror(MultibyteCodec *codec,
- MultibyteCodec_State *state,
- MultibyteDecodeBuffer *buf,
- PyObject *errors, Py_ssize_t e)
+ MultibyteCodec_State *state,
+ MultibyteDecodeBuffer *buf,
+ PyObject *errors, Py_ssize_t e)
{
- PyObject *retobj = NULL, *retuni = NULL;
- Py_ssize_t retunisize, newpos;
- const char *reason;
- Py_ssize_t esize, start, end;
-
- if (e > 0) {
- reason = "illegal multibyte sequence";
- esize = e;
- }
- else {
- switch (e) {
- case MBERR_TOOSMALL:
- REQUIRE_DECODEBUFFER(buf, -1);
- return 0; /* retry it */
- case MBERR_TOOFEW:
- reason = "incomplete multibyte sequence";
- esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- break;
- case MBERR_INTERNAL:
- PyErr_SetString(PyExc_RuntimeError,
- "internal codec error");
- return -1;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "unknown runtime error");
- return -1;
- }
- }
-
- if (errors == ERROR_REPLACE) {
- REQUIRE_DECODEBUFFER(buf, 1);
- *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER;
- }
- if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
- buf->inbuf += esize;
- return 0;
- }
-
- start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
- end = start + esize;
-
- /* use cached exception object if available */
- if (buf->excobj == NULL) {
- buf->excobj = PyUnicodeDecodeError_Create(codec->encoding,
- (const char *)buf->inbuf_top,
- (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top),
- start, end, reason);
- if (buf->excobj == NULL)
- goto errorexit;
- }
- else
- if (PyUnicodeDecodeError_SetStart(buf->excobj, start) ||
- PyUnicodeDecodeError_SetEnd(buf->excobj, end) ||
- PyUnicodeDecodeError_SetReason(buf->excobj, reason))
- goto errorexit;
-
- if (errors == ERROR_STRICT) {
- PyCodec_StrictErrors(buf->excobj);
- goto errorexit;
- }
-
- retobj = call_error_callback(errors, buf->excobj);
- if (retobj == NULL)
- goto errorexit;
-
- if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
- !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) ||
- !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) {
- PyErr_SetString(PyExc_TypeError,
- "decoding error handler must return "
- "(unicode, int) tuple");
- goto errorexit;
- }
-
- retunisize = PyUnicode_GET_SIZE(retuni);
- if (retunisize > 0) {
- REQUIRE_DECODEBUFFER(buf, retunisize);
- memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni),
- retunisize * Py_UNICODE_SIZE);
- buf->outbuf += retunisize;
- }
-
- newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
- if (newpos < 0 && !PyErr_Occurred())
- newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
- if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
- PyErr_Clear();
- PyErr_Format(PyExc_IndexError,
- "position %zd from error handler out of bounds",
- newpos);
- goto errorexit;
- }
- buf->inbuf = buf->inbuf_top + newpos;
- Py_DECREF(retobj);
- return 0;
+ PyObject *retobj = NULL, *retuni = NULL;
+ Py_ssize_t retunisize, newpos;
+ const char *reason;
+ Py_ssize_t esize, start, end;
+
+ if (e > 0) {
+ reason = "illegal multibyte sequence";
+ esize = e;
+ }
+ else {
+ switch (e) {
+ case MBERR_TOOSMALL:
+ REQUIRE_DECODEBUFFER(buf, -1);
+ return 0; /* retry it */
+ case MBERR_TOOFEW:
+ reason = "incomplete multibyte sequence";
+ esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ break;
+ case MBERR_INTERNAL:
+ PyErr_SetString(PyExc_RuntimeError,
+ "internal codec error");
+ return -1;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "unknown runtime error");
+ return -1;
+ }
+ }
+
+ if (errors == ERROR_REPLACE) {
+ REQUIRE_DECODEBUFFER(buf, 1);
+ *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER;
+ }
+ if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
+ buf->inbuf += esize;
+ return 0;
+ }
+
+ start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
+ end = start + esize;
+
+ /* use cached exception object if available */
+ if (buf->excobj == NULL) {
+ buf->excobj = PyUnicodeDecodeError_Create(codec->encoding,
+ (const char *)buf->inbuf_top,
+ (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top),
+ start, end, reason);
+ if (buf->excobj == NULL)
+ goto errorexit;
+ }
+ else
+ if (PyUnicodeDecodeError_SetStart(buf->excobj, start) ||
+ PyUnicodeDecodeError_SetEnd(buf->excobj, end) ||
+ PyUnicodeDecodeError_SetReason(buf->excobj, reason))
+ goto errorexit;
+
+ if (errors == ERROR_STRICT) {
+ PyCodec_StrictErrors(buf->excobj);
+ goto errorexit;
+ }
+
+ retobj = call_error_callback(errors, buf->excobj);
+ if (retobj == NULL)
+ goto errorexit;
+
+ if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
+ !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) ||
+ !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) {
+ PyErr_SetString(PyExc_TypeError,
+ "decoding error handler must return "
+ "(unicode, int) tuple");
+ goto errorexit;
+ }
+
+ retunisize = PyUnicode_GET_SIZE(retuni);
+ if (retunisize > 0) {
+ REQUIRE_DECODEBUFFER(buf, retunisize);
+ memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni),
+ retunisize * Py_UNICODE_SIZE);
+ buf->outbuf += retunisize;
+ }
+
+ newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
+ if (newpos < 0 && !PyErr_Occurred())
+ newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
+ if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
+ PyErr_Clear();
+ PyErr_Format(PyExc_IndexError,
+ "position %zd from error handler out of bounds",
+ newpos);
+ goto errorexit;
+ }
+ buf->inbuf = buf->inbuf_top + newpos;
+ Py_DECREF(retobj);
+ return 0;
errorexit:
- Py_XDECREF(retobj);
- return -1;
+ Py_XDECREF(retobj);
+ return -1;
}
static PyObject *
multibytecodec_encode(MultibyteCodec *codec,
- MultibyteCodec_State *state,
- const Py_UNICODE **data, Py_ssize_t datalen,
- PyObject *errors, int flags)
+ MultibyteCodec_State *state,
+ const Py_UNICODE **data, Py_ssize_t datalen,
+ PyObject *errors, int flags)
{
- MultibyteEncodeBuffer buf;
- Py_ssize_t finalsize, r = 0;
-
- if (datalen == 0)
- return PyBytes_FromStringAndSize(NULL, 0);
-
- buf.excobj = NULL;
- buf.inbuf = buf.inbuf_top = *data;
- buf.inbuf_end = buf.inbuf_top + datalen;
-
- if (datalen > (PY_SSIZE_T_MAX - 16) / 2) {
- PyErr_NoMemory();
- goto errorexit;
- }
-
- buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16);
- if (buf.outobj == NULL)
- goto errorexit;
- buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj);
- buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj);
-
- while (buf.inbuf < buf.inbuf_end) {
- Py_ssize_t inleft, outleft;
-
- /* we don't reuse inleft and outleft here.
- * error callbacks can relocate the cursor anywhere on buffer*/
- inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
- outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
- r = codec->encode(state, codec->config, &buf.inbuf, inleft,
- &buf.outbuf, outleft, flags);
- if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH)))
- break;
- else if (multibytecodec_encerror(codec, state, &buf, errors,r))
- goto errorexit;
- else if (r == MBERR_TOOFEW)
- break;
- }
-
- if (codec->encreset != NULL)
- for (;;) {
- Py_ssize_t outleft;
-
- outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
- r = codec->encreset(state, codec->config, &buf.outbuf,
- outleft);
- if (r == 0)
- break;
- else if (multibytecodec_encerror(codec, state,
- &buf, errors, r))
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)((char *)buf.outbuf -
- PyBytes_AS_STRING(buf.outobj));
-
- if (finalsize != PyBytes_GET_SIZE(buf.outobj))
- if (_PyBytes_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- *data = buf.inbuf;
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteEncodeBuffer buf;
+ Py_ssize_t finalsize, r = 0;
+
+ if (datalen == 0)
+ return PyBytes_FromStringAndSize(NULL, 0);
+
+ buf.excobj = NULL;
+ buf.inbuf = buf.inbuf_top = *data;
+ buf.inbuf_end = buf.inbuf_top + datalen;
+
+ if (datalen > (PY_SSIZE_T_MAX - 16) / 2) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+
+ buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16);
+ if (buf.outobj == NULL)
+ goto errorexit;
+ buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj);
+ buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj);
+
+ while (buf.inbuf < buf.inbuf_end) {
+ Py_ssize_t inleft, outleft;
+
+ /* we don't reuse inleft and outleft here.
+ * error callbacks can relocate the cursor anywhere on buffer*/
+ inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
+ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
+ r = codec->encode(state, codec->config, &buf.inbuf, inleft,
+ &buf.outbuf, outleft, flags);
+ if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH)))
+ break;
+ else if (multibytecodec_encerror(codec, state, &buf, errors,r))
+ goto errorexit;
+ else if (r == MBERR_TOOFEW)
+ break;
+ }
+
+ if (codec->encreset != NULL)
+ for (;;) {
+ Py_ssize_t outleft;
+
+ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
+ r = codec->encreset(state, codec->config, &buf.outbuf,
+ outleft);
+ if (r == 0)
+ break;
+ else if (multibytecodec_encerror(codec, state,
+ &buf, errors, r))
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)((char *)buf.outbuf -
+ PyBytes_AS_STRING(buf.outobj));
+
+ if (finalsize != PyBytes_GET_SIZE(buf.outobj))
+ if (_PyBytes_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ *data = buf.inbuf;
+ Py_XDECREF(buf.excobj);
+ return buf.outobj;
errorexit:
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
- return NULL;
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
+ return NULL;
}
static PyObject *
MultibyteCodec_Encode(MultibyteCodecObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- MultibyteCodec_State state;
- Py_UNICODE *data;
- PyObject *errorcb, *r, *arg, *ucvt;
- const char *errors = NULL;
- Py_ssize_t datalen;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode",
- codeckwarglist, &arg, &errors))
- return NULL;
-
- if (PyUnicode_Check(arg))
- ucvt = NULL;
- else {
- arg = ucvt = PyObject_Str(arg);
- if (arg == NULL)
- return NULL;
- else if (!PyUnicode_Check(arg)) {
- PyErr_SetString(PyExc_TypeError,
- "couldn't convert the object to unicode.");
- Py_DECREF(ucvt);
- return NULL;
- }
- }
-
- data = PyUnicode_AS_UNICODE(arg);
- datalen = PyUnicode_GET_SIZE(arg);
-
- errorcb = internal_error_callback(errors);
- if (errorcb == NULL) {
- Py_XDECREF(ucvt);
- return NULL;
- }
-
- if (self->codec->encinit != NULL &&
- self->codec->encinit(&state, self->codec->config) != 0)
- goto errorexit;
- r = multibytecodec_encode(self->codec, &state,
- (const Py_UNICODE **)&data, datalen, errorcb,
- MBENC_FLUSH | MBENC_RESET);
- if (r == NULL)
- goto errorexit;
-
- ERROR_DECREF(errorcb);
- Py_XDECREF(ucvt);
- return make_tuple(r, datalen);
+ MultibyteCodec_State state;
+ Py_UNICODE *data;
+ PyObject *errorcb, *r, *arg, *ucvt;
+ const char *errors = NULL;
+ Py_ssize_t datalen;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode",
+ codeckwarglist, &arg, &errors))
+ return NULL;
+
+ if (PyUnicode_Check(arg))
+ ucvt = NULL;
+ else {
+ arg = ucvt = PyObject_Str(arg);
+ if (arg == NULL)
+ return NULL;
+ else if (!PyUnicode_Check(arg)) {
+ PyErr_SetString(PyExc_TypeError,
+ "couldn't convert the object to unicode.");
+ Py_DECREF(ucvt);
+ return NULL;
+ }
+ }
+
+ data = PyUnicode_AS_UNICODE(arg);
+ datalen = PyUnicode_GET_SIZE(arg);
+
+ errorcb = internal_error_callback(errors);
+ if (errorcb == NULL) {
+ Py_XDECREF(ucvt);
+ return NULL;
+ }
+
+ if (self->codec->encinit != NULL &&
+ self->codec->encinit(&state, self->codec->config) != 0)
+ goto errorexit;
+ r = multibytecodec_encode(self->codec, &state,
+ (const Py_UNICODE **)&data, datalen, errorcb,
+ MBENC_FLUSH | MBENC_RESET);
+ if (r == NULL)
+ goto errorexit;
+
+ ERROR_DECREF(errorcb);
+ Py_XDECREF(ucvt);
+ return make_tuple(r, datalen);
errorexit:
- ERROR_DECREF(errorcb);
- Py_XDECREF(ucvt);
- return NULL;
+ ERROR_DECREF(errorcb);
+ Py_XDECREF(ucvt);
+ return NULL;
}
static PyObject *
MultibyteCodec_Decode(MultibyteCodecObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- MultibyteCodec_State state;
- MultibyteDecodeBuffer buf;
- PyObject *errorcb;
- Py_buffer pdata;
- const char *data, *errors = NULL;
- Py_ssize_t datalen, finalsize;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode",
- codeckwarglist, &pdata, &errors))
- return NULL;
- data = pdata.buf;
- datalen = pdata.len;
-
- errorcb = internal_error_callback(errors);
- if (errorcb == NULL) {
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- if (datalen == 0) {
- PyBuffer_Release(&pdata);
- ERROR_DECREF(errorcb);
- return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0);
- }
-
- buf.excobj = NULL;
- buf.inbuf = buf.inbuf_top = (unsigned char *)data;
- buf.inbuf_end = buf.inbuf_top + datalen;
- buf.outobj = PyUnicode_FromUnicode(NULL, datalen);
- if (buf.outobj == NULL)
- goto errorexit;
- buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj);
- buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj);
-
- if (self->codec->decinit != NULL &&
- self->codec->decinit(&state, self->codec->config) != 0)
- goto errorexit;
-
- while (buf.inbuf < buf.inbuf_end) {
- Py_ssize_t inleft, outleft, r;
-
- inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
- outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
-
- r = self->codec->decode(&state, self->codec->config,
- &buf.inbuf, inleft, &buf.outbuf, outleft);
- if (r == 0)
- break;
- else if (multibytecodec_decerror(self->codec, &state,
- &buf, errorcb, r))
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)(buf.outbuf -
- PyUnicode_AS_UNICODE(buf.outobj));
-
- if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
- if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- PyBuffer_Release(&pdata);
- Py_XDECREF(buf.excobj);
- ERROR_DECREF(errorcb);
- return make_tuple(buf.outobj, datalen);
+ MultibyteCodec_State state;
+ MultibyteDecodeBuffer buf;
+ PyObject *errorcb;
+ Py_buffer pdata;
+ const char *data, *errors = NULL;
+ Py_ssize_t datalen, finalsize;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode",
+ codeckwarglist, &pdata, &errors))
+ return NULL;
+ data = pdata.buf;
+ datalen = pdata.len;
+
+ errorcb = internal_error_callback(errors);
+ if (errorcb == NULL) {
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ if (datalen == 0) {
+ PyBuffer_Release(&pdata);
+ ERROR_DECREF(errorcb);
+ return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0);
+ }
+
+ buf.excobj = NULL;
+ buf.inbuf = buf.inbuf_top = (unsigned char *)data;
+ buf.inbuf_end = buf.inbuf_top + datalen;
+ buf.outobj = PyUnicode_FromUnicode(NULL, datalen);
+ if (buf.outobj == NULL)
+ goto errorexit;
+ buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj);
+ buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj);
+
+ if (self->codec->decinit != NULL &&
+ self->codec->decinit(&state, self->codec->config) != 0)
+ goto errorexit;
+
+ while (buf.inbuf < buf.inbuf_end) {
+ Py_ssize_t inleft, outleft, r;
+
+ inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
+ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
+
+ r = self->codec->decode(&state, self->codec->config,
+ &buf.inbuf, inleft, &buf.outbuf, outleft);
+ if (r == 0)
+ break;
+ else if (multibytecodec_decerror(self->codec, &state,
+ &buf, errorcb, r))
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)(buf.outbuf -
+ PyUnicode_AS_UNICODE(buf.outobj));
+
+ if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
+ if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ PyBuffer_Release(&pdata);
+ Py_XDECREF(buf.excobj);
+ ERROR_DECREF(errorcb);
+ return make_tuple(buf.outobj, datalen);
errorexit:
- PyBuffer_Release(&pdata);
- ERROR_DECREF(errorcb);
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
+ PyBuffer_Release(&pdata);
+ ERROR_DECREF(errorcb);
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
- return NULL;
+ return NULL;
}
static struct PyMethodDef multibytecodec_methods[] = {
- {"encode", (PyCFunction)MultibyteCodec_Encode,
- METH_VARARGS | METH_KEYWORDS,
- MultibyteCodec_Encode__doc__},
- {"decode", (PyCFunction)MultibyteCodec_Decode,
- METH_VARARGS | METH_KEYWORDS,
- MultibyteCodec_Decode__doc__},
- {NULL, NULL},
+ {"encode", (PyCFunction)MultibyteCodec_Encode,
+ METH_VARARGS | METH_KEYWORDS,
+ MultibyteCodec_Encode__doc__},
+ {"decode", (PyCFunction)MultibyteCodec_Decode,
+ METH_VARARGS | METH_KEYWORDS,
+ MultibyteCodec_Decode__doc__},
+ {NULL, NULL},
};
static void
multibytecodec_dealloc(MultibyteCodecObject *self)
{
- PyObject_Del(self);
+ PyObject_Del(self);
}
static PyTypeObject MultibyteCodec_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteCodec", /* tp_name */
- sizeof(MultibyteCodecObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)multibytecodec_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- multibytecodec_methods, /* tp_methods */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteCodec", /* tp_name */
+ sizeof(MultibyteCodecObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)multibytecodec_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ multibytecodec_methods, /* tp_methods */
};
@@ -732,150 +732,150 @@ static PyTypeObject MultibyteCodec_Type = {
* Utility functions for stateful codec mechanism
*/
-#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o))
-#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o))
+#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o))
+#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o))
static PyObject *
encoder_encode_stateful(MultibyteStatefulEncoderContext *ctx,
- PyObject *unistr, int final)
+ PyObject *unistr, int final)
{
- PyObject *ucvt, *r = NULL;
- Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL;
- Py_ssize_t datalen, origpending;
-
- if (PyUnicode_Check(unistr))
- ucvt = NULL;
- else {
- unistr = ucvt = PyObject_Str(unistr);
- if (unistr == NULL)
- return NULL;
- else if (!PyUnicode_Check(unistr)) {
- PyErr_SetString(PyExc_TypeError,
- "couldn't convert the object to unicode.");
- Py_DECREF(ucvt);
- return NULL;
- }
- }
-
- datalen = PyUnicode_GET_SIZE(unistr);
- origpending = ctx->pendingsize;
-
- if (origpending > 0) {
- if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) {
- PyErr_NoMemory();
- /* inbuf_tmp == NULL */
- goto errorexit;
- }
- inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize);
- if (inbuf_tmp == NULL)
- goto errorexit;
- memcpy(inbuf_tmp, ctx->pending,
- Py_UNICODE_SIZE * ctx->pendingsize);
- memcpy(inbuf_tmp + ctx->pendingsize,
- PyUnicode_AS_UNICODE(unistr),
- Py_UNICODE_SIZE * datalen);
- datalen += ctx->pendingsize;
- ctx->pendingsize = 0;
- inbuf = inbuf_tmp;
- }
- else
- inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr);
-
- inbuf_end = inbuf + datalen;
-
- r = multibytecodec_encode(ctx->codec, &ctx->state,
- (const Py_UNICODE **)&inbuf,
- datalen, ctx->errors, final ? MBENC_FLUSH : 0);
- if (r == NULL) {
- /* recover the original pending buffer */
- if (origpending > 0)
- memcpy(ctx->pending, inbuf_tmp,
- Py_UNICODE_SIZE * origpending);
- ctx->pendingsize = origpending;
- goto errorexit;
- }
-
- if (inbuf < inbuf_end) {
- ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf);
- if (ctx->pendingsize > MAXENCPENDING) {
- /* normal codecs can't reach here */
- ctx->pendingsize = 0;
- PyErr_SetString(PyExc_UnicodeError,
- "pending buffer overflow");
- goto errorexit;
- }
- memcpy(ctx->pending, inbuf,
- ctx->pendingsize * Py_UNICODE_SIZE);
- }
-
- if (inbuf_tmp != NULL)
- PyMem_Del(inbuf_tmp);
- Py_XDECREF(ucvt);
- return r;
+ PyObject *ucvt, *r = NULL;
+ Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL;
+ Py_ssize_t datalen, origpending;
+
+ if (PyUnicode_Check(unistr))
+ ucvt = NULL;
+ else {
+ unistr = ucvt = PyObject_Str(unistr);
+ if (unistr == NULL)
+ return NULL;
+ else if (!PyUnicode_Check(unistr)) {
+ PyErr_SetString(PyExc_TypeError,
+ "couldn't convert the object to unicode.");
+ Py_DECREF(ucvt);
+ return NULL;
+ }
+ }
+
+ datalen = PyUnicode_GET_SIZE(unistr);
+ origpending = ctx->pendingsize;
+
+ if (origpending > 0) {
+ if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) {
+ PyErr_NoMemory();
+ /* inbuf_tmp == NULL */
+ goto errorexit;
+ }
+ inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize);
+ if (inbuf_tmp == NULL)
+ goto errorexit;
+ memcpy(inbuf_tmp, ctx->pending,
+ Py_UNICODE_SIZE * ctx->pendingsize);
+ memcpy(inbuf_tmp + ctx->pendingsize,
+ PyUnicode_AS_UNICODE(unistr),
+ Py_UNICODE_SIZE * datalen);
+ datalen += ctx->pendingsize;
+ ctx->pendingsize = 0;
+ inbuf = inbuf_tmp;
+ }
+ else
+ inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr);
+
+ inbuf_end = inbuf + datalen;
+
+ r = multibytecodec_encode(ctx->codec, &ctx->state,
+ (const Py_UNICODE **)&inbuf,
+ datalen, ctx->errors, final ? MBENC_FLUSH : 0);
+ if (r == NULL) {
+ /* recover the original pending buffer */
+ if (origpending > 0)
+ memcpy(ctx->pending, inbuf_tmp,
+ Py_UNICODE_SIZE * origpending);
+ ctx->pendingsize = origpending;
+ goto errorexit;
+ }
+
+ if (inbuf < inbuf_end) {
+ ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf);
+ if (ctx->pendingsize > MAXENCPENDING) {
+ /* normal codecs can't reach here */
+ ctx->pendingsize = 0;
+ PyErr_SetString(PyExc_UnicodeError,
+ "pending buffer overflow");
+ goto errorexit;
+ }
+ memcpy(ctx->pending, inbuf,
+ ctx->pendingsize * Py_UNICODE_SIZE);
+ }
+
+ if (inbuf_tmp != NULL)
+ PyMem_Del(inbuf_tmp);
+ Py_XDECREF(ucvt);
+ return r;
errorexit:
- if (inbuf_tmp != NULL)
- PyMem_Del(inbuf_tmp);
- Py_XDECREF(r);
- Py_XDECREF(ucvt);
- return NULL;
+ if (inbuf_tmp != NULL)
+ PyMem_Del(inbuf_tmp);
+ Py_XDECREF(r);
+ Py_XDECREF(ucvt);
+ return NULL;
}
static int
decoder_append_pending(MultibyteStatefulDecoderContext *ctx,
- MultibyteDecodeBuffer *buf)
+ MultibyteDecodeBuffer *buf)
{
- Py_ssize_t npendings;
-
- npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- if (npendings + ctx->pendingsize > MAXDECPENDING ||
- npendings > PY_SSIZE_T_MAX - ctx->pendingsize) {
- PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow");
- return -1;
- }
- memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings);
- ctx->pendingsize += npendings;
- return 0;
+ Py_ssize_t npendings;
+
+ npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ if (npendings + ctx->pendingsize > MAXDECPENDING ||
+ npendings > PY_SSIZE_T_MAX - ctx->pendingsize) {
+ PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow");
+ return -1;
+ }
+ memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings);
+ ctx->pendingsize += npendings;
+ return 0;
}
static int
decoder_prepare_buffer(MultibyteDecodeBuffer *buf, const char *data,
- Py_ssize_t size)
+ Py_ssize_t size)
{
- buf->inbuf = buf->inbuf_top = (const unsigned char *)data;
- buf->inbuf_end = buf->inbuf_top + size;
- if (buf->outobj == NULL) { /* only if outobj is not allocated yet */
- buf->outobj = PyUnicode_FromUnicode(NULL, size);
- if (buf->outobj == NULL)
- return -1;
- buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj);
- buf->outbuf_end = buf->outbuf +
- PyUnicode_GET_SIZE(buf->outobj);
- }
-
- return 0;
+ buf->inbuf = buf->inbuf_top = (const unsigned char *)data;
+ buf->inbuf_end = buf->inbuf_top + size;
+ if (buf->outobj == NULL) { /* only if outobj is not allocated yet */
+ buf->outobj = PyUnicode_FromUnicode(NULL, size);
+ if (buf->outobj == NULL)
+ return -1;
+ buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj);
+ buf->outbuf_end = buf->outbuf +
+ PyUnicode_GET_SIZE(buf->outobj);
+ }
+
+ return 0;
}
static int
decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx,
- MultibyteDecodeBuffer *buf)
+ MultibyteDecodeBuffer *buf)
{
- while (buf->inbuf < buf->inbuf_end) {
- Py_ssize_t inleft, outleft;
- Py_ssize_t r;
-
- inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
-
- r = ctx->codec->decode(&ctx->state, ctx->codec->config,
- &buf->inbuf, inleft, &buf->outbuf, outleft);
- if (r == 0 || r == MBERR_TOOFEW)
- break;
- else if (multibytecodec_decerror(ctx->codec, &ctx->state,
- buf, ctx->errors, r))
- return -1;
- }
- return 0;
+ while (buf->inbuf < buf->inbuf_end) {
+ Py_ssize_t inleft, outleft;
+ Py_ssize_t r;
+
+ inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
+
+ r = ctx->codec->decode(&ctx->state, ctx->codec->config,
+ &buf->inbuf, inleft, &buf->outbuf, outleft);
+ if (r == 0 || r == MBERR_TOOFEW)
+ break;
+ else if (multibytecodec_decerror(ctx->codec, &ctx->state,
+ buf, ctx->errors, r))
+ return -1;
+ }
+ return 0;
}
@@ -885,142 +885,142 @@ decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx,
static PyObject *
mbiencoder_encode(MultibyteIncrementalEncoderObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- PyObject *data;
- int final = 0;
+ PyObject *data;
+ int final = 0;
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode",
- incrementalkwarglist, &data, &final))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode",
+ incrementalkwarglist, &data, &final))
+ return NULL;
- return encoder_encode_stateful(STATEFUL_ECTX(self), data, final);
+ return encoder_encode_stateful(STATEFUL_ECTX(self), data, final);
}
static PyObject *
mbiencoder_reset(MultibyteIncrementalEncoderObject *self)
{
- if (self->codec->decreset != NULL &&
- self->codec->decreset(&self->state, self->codec->config) != 0)
- return NULL;
- self->pendingsize = 0;
+ if (self->codec->decreset != NULL &&
+ self->codec->decreset(&self->state, self->codec->config) != 0)
+ return NULL;
+ self->pendingsize = 0;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef mbiencoder_methods[] = {
- {"encode", (PyCFunction)mbiencoder_encode,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"reset", (PyCFunction)mbiencoder_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"encode", (PyCFunction)mbiencoder_encode,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"reset", (PyCFunction)mbiencoder_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyObject *
mbiencoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteIncrementalEncoderObject *self;
- PyObject *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder",
- incnewkwarglist, &errors))
- return NULL;
-
- self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->encinit != NULL &&
- self->codec->encinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteIncrementalEncoderObject *self;
+ PyObject *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder",
+ incnewkwarglist, &errors))
+ return NULL;
+
+ self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->encinit != NULL &&
+ self->codec->encinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbiencoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbiencoder_traverse(MultibyteIncrementalEncoderObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ return 0;
}
static void
mbiencoder_dealloc(MultibyteIncrementalEncoderObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_TYPE(self)->tp_free(self);
}
static PyTypeObject MultibyteIncrementalEncoder_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteIncrementalEncoder", /* tp_name */
- sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbiencoder_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbiencoder_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbiencoder_methods, /* tp_methods */
- 0, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbiencoder_init, /* tp_init */
- 0, /* tp_alloc */
- mbiencoder_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteIncrementalEncoder", /* tp_name */
+ sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbiencoder_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbiencoder_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbiencoder_methods, /* tp_methods */
+ 0, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbiencoder_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbiencoder_new, /* tp_new */
};
@@ -1030,206 +1030,206 @@ static PyTypeObject MultibyteIncrementalEncoder_Type = {
static PyObject *
mbidecoder_decode(MultibyteIncrementalDecoderObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- MultibyteDecodeBuffer buf;
- char *data, *wdata = NULL;
- Py_buffer pdata;
- Py_ssize_t wsize, finalsize = 0, size, origpending;
- int final = 0;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode",
- incrementalkwarglist, &pdata, &final))
- return NULL;
- data = pdata.buf;
- size = pdata.len;
-
- buf.outobj = buf.excobj = NULL;
- origpending = self->pendingsize;
-
- if (self->pendingsize == 0) {
- wsize = size;
- wdata = data;
- }
- else {
- if (size > PY_SSIZE_T_MAX - self->pendingsize) {
- PyErr_NoMemory();
- goto errorexit;
- }
- wsize = size + self->pendingsize;
- wdata = PyMem_Malloc(wsize);
- if (wdata == NULL)
- goto errorexit;
- memcpy(wdata, self->pending, self->pendingsize);
- memcpy(wdata + self->pendingsize, data, size);
- self->pendingsize = 0;
- }
-
- if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)
- goto errorexit;
-
- if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf))
- goto errorexit;
-
- if (final && buf.inbuf < buf.inbuf_end) {
- if (multibytecodec_decerror(self->codec, &self->state,
- &buf, self->errors, MBERR_TOOFEW)) {
- /* recover the original pending buffer */
- memcpy(self->pending, wdata, origpending);
- self->pendingsize = origpending;
- goto errorexit;
- }
- }
-
- if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */
- if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0)
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj));
- if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
- if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- PyBuffer_Release(&pdata);
- if (wdata != data)
- PyMem_Del(wdata);
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteDecodeBuffer buf;
+ char *data, *wdata = NULL;
+ Py_buffer pdata;
+ Py_ssize_t wsize, finalsize = 0, size, origpending;
+ int final = 0;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode",
+ incrementalkwarglist, &pdata, &final))
+ return NULL;
+ data = pdata.buf;
+ size = pdata.len;
+
+ buf.outobj = buf.excobj = NULL;
+ origpending = self->pendingsize;
+
+ if (self->pendingsize == 0) {
+ wsize = size;
+ wdata = data;
+ }
+ else {
+ if (size > PY_SSIZE_T_MAX - self->pendingsize) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+ wsize = size + self->pendingsize;
+ wdata = PyMem_Malloc(wsize);
+ if (wdata == NULL)
+ goto errorexit;
+ memcpy(wdata, self->pending, self->pendingsize);
+ memcpy(wdata + self->pendingsize, data, size);
+ self->pendingsize = 0;
+ }
+
+ if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)
+ goto errorexit;
+
+ if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf))
+ goto errorexit;
+
+ if (final && buf.inbuf < buf.inbuf_end) {
+ if (multibytecodec_decerror(self->codec, &self->state,
+ &buf, self->errors, MBERR_TOOFEW)) {
+ /* recover the original pending buffer */
+ memcpy(self->pending, wdata, origpending);
+ self->pendingsize = origpending;
+ goto errorexit;
+ }
+ }
+
+ if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */
+ if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0)
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj));
+ if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
+ if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ PyBuffer_Release(&pdata);
+ if (wdata != data)
+ PyMem_Del(wdata);
+ Py_XDECREF(buf.excobj);
+ return buf.outobj;
errorexit:
- PyBuffer_Release(&pdata);
- if (wdata != NULL && wdata != data)
- PyMem_Del(wdata);
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
- return NULL;
+ PyBuffer_Release(&pdata);
+ if (wdata != NULL && wdata != data)
+ PyMem_Del(wdata);
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
+ return NULL;
}
static PyObject *
mbidecoder_reset(MultibyteIncrementalDecoderObject *self)
{
- if (self->codec->decreset != NULL &&
- self->codec->decreset(&self->state, self->codec->config) != 0)
- return NULL;
- self->pendingsize = 0;
+ if (self->codec->decreset != NULL &&
+ self->codec->decreset(&self->state, self->codec->config) != 0)
+ return NULL;
+ self->pendingsize = 0;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef mbidecoder_methods[] = {
- {"decode", (PyCFunction)mbidecoder_decode,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"reset", (PyCFunction)mbidecoder_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"decode", (PyCFunction)mbidecoder_decode,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"reset", (PyCFunction)mbidecoder_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyObject *
mbidecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteIncrementalDecoderObject *self;
- PyObject *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder",
- incnewkwarglist, &errors))
- return NULL;
-
- self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->decinit != NULL &&
- self->codec->decinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteIncrementalDecoderObject *self;
+ PyObject *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder",
+ incnewkwarglist, &errors))
+ return NULL;
+
+ self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->decinit != NULL &&
+ self->codec->decinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbidecoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbidecoder_traverse(MultibyteIncrementalDecoderObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ return 0;
}
static void
mbidecoder_dealloc(MultibyteIncrementalDecoderObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_TYPE(self)->tp_free(self);
}
static PyTypeObject MultibyteIncrementalDecoder_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteIncrementalDecoder", /* tp_name */
- sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbidecoder_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbidecoder_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbidecoder_methods, /* tp_methods */
- 0, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbidecoder_init, /* tp_init */
- 0, /* tp_alloc */
- mbidecoder_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteIncrementalDecoder", /* tp_name */
+ sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbidecoder_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbidecoder_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbidecoder_methods, /* tp_methods */
+ 0, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbidecoder_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbidecoder_new, /* tp_new */
};
@@ -1239,327 +1239,327 @@ static PyTypeObject MultibyteIncrementalDecoder_Type = {
static PyObject *
mbstreamreader_iread(MultibyteStreamReaderObject *self,
- const char *method, Py_ssize_t sizehint)
+ const char *method, Py_ssize_t sizehint)
{
- MultibyteDecodeBuffer buf;
- PyObject *cres;
- Py_ssize_t rsize, finalsize = 0;
-
- if (sizehint == 0)
- return PyUnicode_FromUnicode(NULL, 0);
-
- buf.outobj = buf.excobj = NULL;
- cres = NULL;
-
- for (;;) {
- int endoffile;
-
- if (sizehint < 0)
- cres = PyObject_CallMethod(self->stream,
- (char *)method, NULL);
- else
- cres = PyObject_CallMethod(self->stream,
- (char *)method, "i", sizehint);
- if (cres == NULL)
- goto errorexit;
-
- if (!PyBytes_Check(cres)) {
- PyErr_Format(PyExc_TypeError,
- "stream function returned a "
- "non-bytes object (%.100s)",
- cres->ob_type->tp_name);
- goto errorexit;
- }
-
- endoffile = (PyBytes_GET_SIZE(cres) == 0);
-
- if (self->pendingsize > 0) {
- PyObject *ctr;
- char *ctrdata;
-
- if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
- PyErr_NoMemory();
- goto errorexit;
- }
- rsize = PyBytes_GET_SIZE(cres) + self->pendingsize;
- ctr = PyBytes_FromStringAndSize(NULL, rsize);
- if (ctr == NULL)
- goto errorexit;
- ctrdata = PyBytes_AS_STRING(ctr);
- memcpy(ctrdata, self->pending, self->pendingsize);
- memcpy(ctrdata + self->pendingsize,
- PyBytes_AS_STRING(cres),
- PyBytes_GET_SIZE(cres));
- Py_DECREF(cres);
- cres = ctr;
- self->pendingsize = 0;
- }
-
- rsize = PyBytes_GET_SIZE(cres);
- if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres),
- rsize) != 0)
- goto errorexit;
-
- if (rsize > 0 && decoder_feed_buffer(
- (MultibyteStatefulDecoderContext *)self, &buf))
- goto errorexit;
-
- if (endoffile || sizehint < 0) {
- if (buf.inbuf < buf.inbuf_end &&
- multibytecodec_decerror(self->codec, &self->state,
- &buf, self->errors, MBERR_TOOFEW))
- goto errorexit;
- }
-
- if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */
- if (decoder_append_pending(STATEFUL_DCTX(self),
- &buf) != 0)
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)(buf.outbuf -
- PyUnicode_AS_UNICODE(buf.outobj));
- Py_DECREF(cres);
- cres = NULL;
-
- if (sizehint < 0 || finalsize != 0 || rsize == 0)
- break;
-
- sizehint = 1; /* read 1 more byte and retry */
- }
-
- if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
- if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- Py_XDECREF(cres);
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteDecodeBuffer buf;
+ PyObject *cres;
+ Py_ssize_t rsize, finalsize = 0;
+
+ if (sizehint == 0)
+ return PyUnicode_FromUnicode(NULL, 0);
+
+ buf.outobj = buf.excobj = NULL;
+ cres = NULL;
+
+ for (;;) {
+ int endoffile;
+
+ if (sizehint < 0)
+ cres = PyObject_CallMethod(self->stream,
+ (char *)method, NULL);
+ else
+ cres = PyObject_CallMethod(self->stream,
+ (char *)method, "i", sizehint);
+ if (cres == NULL)
+ goto errorexit;
+
+ if (!PyBytes_Check(cres)) {
+ PyErr_Format(PyExc_TypeError,
+ "stream function returned a "
+ "non-bytes object (%.100s)",
+ cres->ob_type->tp_name);
+ goto errorexit;
+ }
+
+ endoffile = (PyBytes_GET_SIZE(cres) == 0);
+
+ if (self->pendingsize > 0) {
+ PyObject *ctr;
+ char *ctrdata;
+
+ if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+ rsize = PyBytes_GET_SIZE(cres) + self->pendingsize;
+ ctr = PyBytes_FromStringAndSize(NULL, rsize);
+ if (ctr == NULL)
+ goto errorexit;
+ ctrdata = PyBytes_AS_STRING(ctr);
+ memcpy(ctrdata, self->pending, self->pendingsize);
+ memcpy(ctrdata + self->pendingsize,
+ PyBytes_AS_STRING(cres),
+ PyBytes_GET_SIZE(cres));
+ Py_DECREF(cres);
+ cres = ctr;
+ self->pendingsize = 0;
+ }
+
+ rsize = PyBytes_GET_SIZE(cres);
+ if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres),
+ rsize) != 0)
+ goto errorexit;
+
+ if (rsize > 0 && decoder_feed_buffer(
+ (MultibyteStatefulDecoderContext *)self, &buf))
+ goto errorexit;
+
+ if (endoffile || sizehint < 0) {
+ if (buf.inbuf < buf.inbuf_end &&
+ multibytecodec_decerror(self->codec, &self->state,
+ &buf, self->errors, MBERR_TOOFEW))
+ goto errorexit;
+ }
+
+ if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */
+ if (decoder_append_pending(STATEFUL_DCTX(self),
+ &buf) != 0)
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)(buf.outbuf -
+ PyUnicode_AS_UNICODE(buf.outobj));
+ Py_DECREF(cres);
+ cres = NULL;
+
+ if (sizehint < 0 || finalsize != 0 || rsize == 0)
+ break;
+
+ sizehint = 1; /* read 1 more byte and retry */
+ }
+
+ if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
+ if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ Py_XDECREF(cres);
+ Py_XDECREF(buf.excobj);
+ return buf.outobj;
errorexit:
- Py_XDECREF(cres);
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
- return NULL;
+ Py_XDECREF(cres);
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
+ return NULL;
}
static PyObject *
mbstreamreader_read(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizeobj = NULL;
- Py_ssize_t size;
+ PyObject *sizeobj = NULL;
+ Py_ssize_t size;
- if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
+ return NULL;
- if (sizeobj == Py_None || sizeobj == NULL)
- size = -1;
- else if (PyLong_Check(sizeobj))
- size = PyLong_AsSsize_t(sizeobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
+ if (sizeobj == Py_None || sizeobj == NULL)
+ size = -1;
+ else if (PyLong_Check(sizeobj))
+ size = PyLong_AsSsize_t(sizeobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
- if (size == -1 && PyErr_Occurred())
- return NULL;
+ if (size == -1 && PyErr_Occurred())
+ return NULL;
- return mbstreamreader_iread(self, "read", size);
+ return mbstreamreader_iread(self, "read", size);
}
static PyObject *
mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizeobj = NULL;
- Py_ssize_t size;
+ PyObject *sizeobj = NULL;
+ Py_ssize_t size;
- if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
+ return NULL;
- if (sizeobj == Py_None || sizeobj == NULL)
- size = -1;
- else if (PyLong_Check(sizeobj))
- size = PyLong_AsSsize_t(sizeobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
+ if (sizeobj == Py_None || sizeobj == NULL)
+ size = -1;
+ else if (PyLong_Check(sizeobj))
+ size = PyLong_AsSsize_t(sizeobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
- if (size == -1 && PyErr_Occurred())
- return NULL;
+ if (size == -1 && PyErr_Occurred())
+ return NULL;
- return mbstreamreader_iread(self, "readline", size);
+ return mbstreamreader_iread(self, "readline", size);
}
static PyObject *
mbstreamreader_readlines(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizehintobj = NULL, *r, *sr;
- Py_ssize_t sizehint;
-
- if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj))
- return NULL;
-
- if (sizehintobj == Py_None || sizehintobj == NULL)
- sizehint = -1;
- else if (PyLong_Check(sizehintobj))
- sizehint = PyLong_AsSsize_t(sizehintobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
-
- if (sizehint == -1 && PyErr_Occurred())
- return NULL;
-
- r = mbstreamreader_iread(self, "read", sizehint);
- if (r == NULL)
- return NULL;
-
- sr = PyUnicode_Splitlines(r, 1);
- Py_DECREF(r);
- return sr;
+ PyObject *sizehintobj = NULL, *r, *sr;
+ Py_ssize_t sizehint;
+
+ if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj))
+ return NULL;
+
+ if (sizehintobj == Py_None || sizehintobj == NULL)
+ sizehint = -1;
+ else if (PyLong_Check(sizehintobj))
+ sizehint = PyLong_AsSsize_t(sizehintobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
+
+ if (sizehint == -1 && PyErr_Occurred())
+ return NULL;
+
+ r = mbstreamreader_iread(self, "read", sizehint);
+ if (r == NULL)
+ return NULL;
+
+ sr = PyUnicode_Splitlines(r, 1);
+ Py_DECREF(r);
+ return sr;
}
static PyObject *
mbstreamreader_reset(MultibyteStreamReaderObject *self)
{
- if (self->codec->decreset != NULL &&
- self->codec->decreset(&self->state, self->codec->config) != 0)
- return NULL;
- self->pendingsize = 0;
+ if (self->codec->decreset != NULL &&
+ self->codec->decreset(&self->state, self->codec->config) != 0)
+ return NULL;
+ self->pendingsize = 0;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef mbstreamreader_methods[] = {
- {"read", (PyCFunction)mbstreamreader_read,
- METH_VARARGS, NULL},
- {"readline", (PyCFunction)mbstreamreader_readline,
- METH_VARARGS, NULL},
- {"readlines", (PyCFunction)mbstreamreader_readlines,
- METH_VARARGS, NULL},
- {"reset", (PyCFunction)mbstreamreader_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"read", (PyCFunction)mbstreamreader_read,
+ METH_VARARGS, NULL},
+ {"readline", (PyCFunction)mbstreamreader_readline,
+ METH_VARARGS, NULL},
+ {"readlines", (PyCFunction)mbstreamreader_readlines,
+ METH_VARARGS, NULL},
+ {"reset", (PyCFunction)mbstreamreader_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyMemberDef mbstreamreader_members[] = {
- {"stream", T_OBJECT,
- offsetof(MultibyteStreamReaderObject, stream),
- READONLY, NULL},
- {NULL,}
+ {"stream", T_OBJECT,
+ offsetof(MultibyteStreamReaderObject, stream),
+ READONLY, NULL},
+ {NULL,}
};
static PyObject *
mbstreamreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteStreamReaderObject *self;
- PyObject *stream, *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader",
- streamkwarglist, &stream, &errors))
- return NULL;
-
- self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->stream = stream;
- Py_INCREF(stream);
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->decinit != NULL &&
- self->codec->decinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteStreamReaderObject *self;
+ PyObject *stream, *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader",
+ streamkwarglist, &stream, &errors))
+ return NULL;
+
+ self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->stream = stream;
+ Py_INCREF(stream);
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->decinit != NULL &&
+ self->codec->decinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbstreamreader_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbstreamreader_traverse(MultibyteStreamReaderObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- Py_VISIT(self->stream);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ Py_VISIT(self->stream);
+ return 0;
}
static void
mbstreamreader_dealloc(MultibyteStreamReaderObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_XDECREF(self->stream);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_XDECREF(self->stream);
+ Py_TYPE(self)->tp_free(self);
}
static PyTypeObject MultibyteStreamReader_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteStreamReader", /* tp_name */
- sizeof(MultibyteStreamReaderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbstreamreader_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbstreamreader_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbstreamreader_methods, /* tp_methods */
- mbstreamreader_members, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbstreamreader_init, /* tp_init */
- 0, /* tp_alloc */
- mbstreamreader_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteStreamReader", /* tp_name */
+ sizeof(MultibyteStreamReaderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbstreamreader_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbstreamreader_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbstreamreader_methods, /* tp_methods */
+ mbstreamreader_members, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbstreamreader_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbstreamreader_new, /* tp_new */
};
@@ -1569,217 +1569,217 @@ static PyTypeObject MultibyteStreamReader_Type = {
static int
mbstreamwriter_iwrite(MultibyteStreamWriterObject *self,
- PyObject *unistr)
+ PyObject *unistr)
{
- PyObject *str, *wr;
+ PyObject *str, *wr;
- str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0);
- if (str == NULL)
- return -1;
+ str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0);
+ if (str == NULL)
+ return -1;
- wr = PyObject_CallMethod(self->stream, "write", "O", str);
- Py_DECREF(str);
- if (wr == NULL)
- return -1;
+ wr = PyObject_CallMethod(self->stream, "write", "O", str);
+ Py_DECREF(str);
+ if (wr == NULL)
+ return -1;
- Py_DECREF(wr);
- return 0;
+ Py_DECREF(wr);
+ return 0;
}
static PyObject *
mbstreamwriter_write(MultibyteStreamWriterObject *self, PyObject *strobj)
{
- if (mbstreamwriter_iwrite(self, strobj))
- return NULL;
- else
- Py_RETURN_NONE;
+ if (mbstreamwriter_iwrite(self, strobj))
+ return NULL;
+ else
+ Py_RETURN_NONE;
}
static PyObject *
mbstreamwriter_writelines(MultibyteStreamWriterObject *self, PyObject *lines)
{
- PyObject *strobj;
- int i, r;
-
- if (!PySequence_Check(lines)) {
- PyErr_SetString(PyExc_TypeError,
- "arg must be a sequence object");
- return NULL;
- }
-
- for (i = 0; i < PySequence_Length(lines); i++) {
- /* length can be changed even within this loop */
- strobj = PySequence_GetItem(lines, i);
- if (strobj == NULL)
- return NULL;
-
- r = mbstreamwriter_iwrite(self, strobj);
- Py_DECREF(strobj);
- if (r == -1)
- return NULL;
- }
-
- Py_RETURN_NONE;
+ PyObject *strobj;
+ int i, r;
+
+ if (!PySequence_Check(lines)) {
+ PyErr_SetString(PyExc_TypeError,
+ "arg must be a sequence object");
+ return NULL;
+ }
+
+ for (i = 0; i < PySequence_Length(lines); i++) {
+ /* length can be changed even within this loop */
+ strobj = PySequence_GetItem(lines, i);
+ if (strobj == NULL)
+ return NULL;
+
+ r = mbstreamwriter_iwrite(self, strobj);
+ Py_DECREF(strobj);
+ if (r == -1)
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
static PyObject *
mbstreamwriter_reset(MultibyteStreamWriterObject *self)
{
- const Py_UNICODE *pending;
- PyObject *pwrt;
-
- pending = self->pending;
- pwrt = multibytecodec_encode(self->codec, &self->state,
- &pending, self->pendingsize, self->errors,
- MBENC_FLUSH | MBENC_RESET);
- /* some pending buffer can be truncated when UnicodeEncodeError is
- * raised on 'strict' mode. but, 'reset' method is designed to
- * reset the pending buffer or states so failed string sequence
- * ought to be missed */
- self->pendingsize = 0;
- if (pwrt == NULL)
- return NULL;
-
- assert(PyBytes_Check(pwrt));
- if (PyBytes_Size(pwrt) > 0) {
- PyObject *wr;
- wr = PyObject_CallMethod(self->stream, "write", "O", pwrt);
- if (wr == NULL) {
- Py_DECREF(pwrt);
- return NULL;
- }
- }
- Py_DECREF(pwrt);
-
- Py_RETURN_NONE;
+ const Py_UNICODE *pending;
+ PyObject *pwrt;
+
+ pending = self->pending;
+ pwrt = multibytecodec_encode(self->codec, &self->state,
+ &pending, self->pendingsize, self->errors,
+ MBENC_FLUSH | MBENC_RESET);
+ /* some pending buffer can be truncated when UnicodeEncodeError is
+ * raised on 'strict' mode. but, 'reset' method is designed to
+ * reset the pending buffer or states so failed string sequence
+ * ought to be missed */
+ self->pendingsize = 0;
+ if (pwrt == NULL)
+ return NULL;
+
+ assert(PyBytes_Check(pwrt));
+ if (PyBytes_Size(pwrt) > 0) {
+ PyObject *wr;
+ wr = PyObject_CallMethod(self->stream, "write", "O", pwrt);
+ if (wr == NULL) {
+ Py_DECREF(pwrt);
+ return NULL;
+ }
+ }
+ Py_DECREF(pwrt);
+
+ Py_RETURN_NONE;
}
static PyObject *
mbstreamwriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteStreamWriterObject *self;
- PyObject *stream, *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter",
- streamkwarglist, &stream, &errors))
- return NULL;
-
- self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->stream = stream;
- Py_INCREF(stream);
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->encinit != NULL &&
- self->codec->encinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteStreamWriterObject *self;
+ PyObject *stream, *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter",
+ streamkwarglist, &stream, &errors))
+ return NULL;
+
+ self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->stream = stream;
+ Py_INCREF(stream);
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->encinit != NULL &&
+ self->codec->encinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbstreamwriter_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbstreamwriter_traverse(MultibyteStreamWriterObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- Py_VISIT(self->stream);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ Py_VISIT(self->stream);
+ return 0;
}
static void
mbstreamwriter_dealloc(MultibyteStreamWriterObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_XDECREF(self->stream);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_XDECREF(self->stream);
+ Py_TYPE(self)->tp_free(self);
}
static struct PyMethodDef mbstreamwriter_methods[] = {
- {"write", (PyCFunction)mbstreamwriter_write,
- METH_O, NULL},
- {"writelines", (PyCFunction)mbstreamwriter_writelines,
- METH_O, NULL},
- {"reset", (PyCFunction)mbstreamwriter_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"write", (PyCFunction)mbstreamwriter_write,
+ METH_O, NULL},
+ {"writelines", (PyCFunction)mbstreamwriter_writelines,
+ METH_O, NULL},
+ {"reset", (PyCFunction)mbstreamwriter_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyMemberDef mbstreamwriter_members[] = {
- {"stream", T_OBJECT,
- offsetof(MultibyteStreamWriterObject, stream),
- READONLY, NULL},
- {NULL,}
+ {"stream", T_OBJECT,
+ offsetof(MultibyteStreamWriterObject, stream),
+ READONLY, NULL},
+ {NULL,}
};
static PyTypeObject MultibyteStreamWriter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteStreamWriter", /* tp_name */
- sizeof(MultibyteStreamWriterObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbstreamwriter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbstreamwriter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbstreamwriter_methods, /* tp_methods */
- mbstreamwriter_members, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbstreamwriter_init, /* tp_init */
- 0, /* tp_alloc */
- mbstreamwriter_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteStreamWriter", /* tp_name */
+ sizeof(MultibyteStreamWriterObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbstreamwriter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbstreamwriter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbstreamwriter_methods, /* tp_methods */
+ mbstreamwriter_members, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbstreamwriter_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbstreamwriter_new, /* tp_new */
};
@@ -1790,76 +1790,76 @@ static PyTypeObject MultibyteStreamWriter_Type = {
static PyObject *
__create_codec(PyObject *ignore, PyObject *arg)
{
- MultibyteCodecObject *self;
- MultibyteCodec *codec;
+ MultibyteCodecObject *self;
+ MultibyteCodec *codec;
- if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) {
- PyErr_SetString(PyExc_ValueError, "argument type invalid");
- return NULL;
- }
+ if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) {
+ PyErr_SetString(PyExc_ValueError, "argument type invalid");
+ return NULL;
+ }
- codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME);
- if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0)
- return NULL;
+ codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME);
+ if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0)
+ return NULL;
- self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type);
- if (self == NULL)
- return NULL;
- self->codec = codec;
+ self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type);
+ if (self == NULL)
+ return NULL;
+ self->codec = codec;
- return (PyObject *)self;
+ return (PyObject *)self;
}
static struct PyMethodDef __methods[] = {
- {"__create_codec", (PyCFunction)__create_codec, METH_O},
- {NULL, NULL},
+ {"__create_codec", (PyCFunction)__create_codec, METH_O},
+ {NULL, NULL},
};
static struct PyModuleDef _multibytecodecmodule = {
- PyModuleDef_HEAD_INIT,
- "_multibytecodec",
- NULL,
- -1,
- __methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_multibytecodec",
+ NULL,
+ -1,
+ __methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__multibytecodec(void)
{
- int i;
- PyObject *m;
- PyTypeObject *typelist[] = {
- &MultibyteIncrementalEncoder_Type,
- &MultibyteIncrementalDecoder_Type,
- &MultibyteStreamReader_Type,
- &MultibyteStreamWriter_Type,
- NULL
- };
-
- if (PyType_Ready(&MultibyteCodec_Type) < 0)
- return NULL;
-
- m = PyModule_Create(&_multibytecodecmodule);
- if (m == NULL)
- return NULL;
-
- for (i = 0; typelist[i] != NULL; i++) {
- if (PyType_Ready(typelist[i]) < 0)
- return NULL;
- Py_INCREF(typelist[i]);
- PyModule_AddObject(m, typelist[i]->tp_name,
- (PyObject *)typelist[i]);
- }
-
- if (PyErr_Occurred()) {
- Py_FatalError("can't initialize the _multibytecodec module");
- Py_DECREF(m);
- m = NULL;
- }
- return m;
+ int i;
+ PyObject *m;
+ PyTypeObject *typelist[] = {
+ &MultibyteIncrementalEncoder_Type,
+ &MultibyteIncrementalDecoder_Type,
+ &MultibyteStreamReader_Type,
+ &MultibyteStreamWriter_Type,
+ NULL
+ };
+
+ if (PyType_Ready(&MultibyteCodec_Type) < 0)
+ return NULL;
+
+ m = PyModule_Create(&_multibytecodecmodule);
+ if (m == NULL)
+ return NULL;
+
+ for (i = 0; typelist[i] != NULL; i++) {
+ if (PyType_Ready(typelist[i]) < 0)
+ return NULL;
+ Py_INCREF(typelist[i]);
+ PyModule_AddObject(m, typelist[i]->tp_name,
+ (PyObject *)typelist[i]);
+ }
+
+ if (PyErr_Occurred()) {
+ Py_FatalError("can't initialize the _multibytecodec module");
+ Py_DECREF(m);
+ m = NULL;
+ }
+ return m;
}
diff --git a/Modules/cjkcodecs/multibytecodec.h b/Modules/cjkcodecs/multibytecodec.h
index 71c02cc..1b6ef55 100644
--- a/Modules/cjkcodecs/multibytecodec.h
+++ b/Modules/cjkcodecs/multibytecodec.h
@@ -23,114 +23,114 @@ typedef unsigned short ucs2_t, DBCHAR;
#endif
typedef union {
- void *p;
- int i;
- unsigned char c[8];
- ucs2_t u2[4];
- ucs4_t u4[2];
+ void *p;
+ int i;
+ unsigned char c[8];
+ ucs2_t u2[4];
+ ucs4_t u4[2];
} MultibyteCodec_State;
typedef int (*mbcodec_init)(const void *config);
typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state,
- const void *config,
- const Py_UNICODE **inbuf, Py_ssize_t inleft,
- unsigned char **outbuf, Py_ssize_t outleft,
- int flags);
+ const void *config,
+ const Py_UNICODE **inbuf, Py_ssize_t inleft,
+ unsigned char **outbuf, Py_ssize_t outleft,
+ int flags);
typedef int (*mbencodeinit_func)(MultibyteCodec_State *state,
- const void *config);
+ const void *config);
typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state,
- const void *config,
- unsigned char **outbuf, Py_ssize_t outleft);
+ const void *config,
+ unsigned char **outbuf, Py_ssize_t outleft);
typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state,
- const void *config,
- const unsigned char **inbuf, Py_ssize_t inleft,
- Py_UNICODE **outbuf, Py_ssize_t outleft);
+ const void *config,
+ const unsigned char **inbuf, Py_ssize_t inleft,
+ Py_UNICODE **outbuf, Py_ssize_t outleft);
typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state,
- const void *config);
+ const void *config);
typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state,
- const void *config);
+ const void *config);
typedef struct {
- const char *encoding;
- const void *config;
- mbcodec_init codecinit;
- mbencode_func encode;
- mbencodeinit_func encinit;
- mbencodereset_func encreset;
- mbdecode_func decode;
- mbdecodeinit_func decinit;
- mbdecodereset_func decreset;
+ const char *encoding;
+ const void *config;
+ mbcodec_init codecinit;
+ mbencode_func encode;
+ mbencodeinit_func encinit;
+ mbencodereset_func encreset;
+ mbdecode_func decode;
+ mbdecodeinit_func decinit;
+ mbdecodereset_func decreset;
} MultibyteCodec;
typedef struct {
- PyObject_HEAD
- MultibyteCodec *codec;
+ PyObject_HEAD
+ MultibyteCodec *codec;
} MultibyteCodecObject;
#define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type)
-#define _MultibyteStatefulCodec_HEAD \
- PyObject_HEAD \
- MultibyteCodec *codec; \
- MultibyteCodec_State state; \
- PyObject *errors;
+#define _MultibyteStatefulCodec_HEAD \
+ PyObject_HEAD \
+ MultibyteCodec *codec; \
+ MultibyteCodec_State state; \
+ PyObject *errors;
typedef struct {
- _MultibyteStatefulCodec_HEAD
+ _MultibyteStatefulCodec_HEAD
} MultibyteStatefulCodecContext;
-#define MAXENCPENDING 2
-#define _MultibyteStatefulEncoder_HEAD \
- _MultibyteStatefulCodec_HEAD \
- Py_UNICODE pending[MAXENCPENDING]; \
- Py_ssize_t pendingsize;
+#define MAXENCPENDING 2
+#define _MultibyteStatefulEncoder_HEAD \
+ _MultibyteStatefulCodec_HEAD \
+ Py_UNICODE pending[MAXENCPENDING]; \
+ Py_ssize_t pendingsize;
typedef struct {
- _MultibyteStatefulEncoder_HEAD
+ _MultibyteStatefulEncoder_HEAD
} MultibyteStatefulEncoderContext;
-#define MAXDECPENDING 8
-#define _MultibyteStatefulDecoder_HEAD \
- _MultibyteStatefulCodec_HEAD \
- unsigned char pending[MAXDECPENDING]; \
- Py_ssize_t pendingsize;
+#define MAXDECPENDING 8
+#define _MultibyteStatefulDecoder_HEAD \
+ _MultibyteStatefulCodec_HEAD \
+ unsigned char pending[MAXDECPENDING]; \
+ Py_ssize_t pendingsize;
typedef struct {
- _MultibyteStatefulDecoder_HEAD
+ _MultibyteStatefulDecoder_HEAD
} MultibyteStatefulDecoderContext;
typedef struct {
- _MultibyteStatefulEncoder_HEAD
+ _MultibyteStatefulEncoder_HEAD
} MultibyteIncrementalEncoderObject;
typedef struct {
- _MultibyteStatefulDecoder_HEAD
+ _MultibyteStatefulDecoder_HEAD
} MultibyteIncrementalDecoderObject;
typedef struct {
- _MultibyteStatefulDecoder_HEAD
- PyObject *stream;
+ _MultibyteStatefulDecoder_HEAD
+ PyObject *stream;
} MultibyteStreamReaderObject;
typedef struct {
- _MultibyteStatefulEncoder_HEAD
- PyObject *stream;
+ _MultibyteStatefulEncoder_HEAD
+ PyObject *stream;
} MultibyteStreamWriterObject;
/* positive values for illegal sequences */
-#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
-#define MBERR_TOOFEW (-2) /* incomplete input buffer */
-#define MBERR_INTERNAL (-3) /* internal runtime error */
-
-#define ERROR_STRICT (PyObject *)(1)
-#define ERROR_IGNORE (PyObject *)(2)
-#define ERROR_REPLACE (PyObject *)(3)
-#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
-#define ERROR_DECREF(p) do { \
- if (p != NULL && ERROR_ISCUSTOM(p)) { \
- Py_DECREF(p); \
- } \
+#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
+#define MBERR_TOOFEW (-2) /* incomplete input buffer */
+#define MBERR_INTERNAL (-3) /* internal runtime error */
+
+#define ERROR_STRICT (PyObject *)(1)
+#define ERROR_IGNORE (PyObject *)(2)
+#define ERROR_REPLACE (PyObject *)(3)
+#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
+#define ERROR_DECREF(p) do { \
+ if (p != NULL && ERROR_ISCUSTOM(p)) { \
+ Py_DECREF(p); \
+ } \
} while (0);
-#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
-#define MBENC_MAX MBENC_FLUSH
+#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
+#define MBENC_MAX MBENC_FLUSH
#define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*"
diff --git a/Modules/cmathmodule.c b/Modules/cmathmodule.c
index 4d13e58..2af2e53 100644
--- a/Modules/cmathmodule.c
+++ b/Modules/cmathmodule.c
@@ -32,7 +32,7 @@
#define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE))
#define CM_SQRT_DBL_MIN (sqrt(DBL_MIN))
-/*
+/*
CM_SCALE_UP is an odd integer chosen such that multiplication by
2**CM_SCALE_UP is sufficient to turn a subnormal into a normal.
CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute
@@ -63,46 +63,46 @@ static PyObject * math_error(void);
*/
enum special_types {
- ST_NINF, /* 0, negative infinity */
- ST_NEG, /* 1, negative finite number (nonzero) */
- ST_NZERO, /* 2, -0. */
- ST_PZERO, /* 3, +0. */
- ST_POS, /* 4, positive finite number (nonzero) */
- ST_PINF, /* 5, positive infinity */
- ST_NAN /* 6, Not a Number */
+ ST_NINF, /* 0, negative infinity */
+ ST_NEG, /* 1, negative finite number (nonzero) */
+ ST_NZERO, /* 2, -0. */
+ ST_PZERO, /* 3, +0. */
+ ST_POS, /* 4, positive finite number (nonzero) */
+ ST_PINF, /* 5, positive infinity */
+ ST_NAN /* 6, Not a Number */
};
static enum special_types
special_type(double d)
{
- if (Py_IS_FINITE(d)) {
- if (d != 0) {
- if (copysign(1., d) == 1.)
- return ST_POS;
- else
- return ST_NEG;
- }
- else {
- if (copysign(1., d) == 1.)
- return ST_PZERO;
- else
- return ST_NZERO;
- }
- }
- if (Py_IS_NAN(d))
- return ST_NAN;
- if (copysign(1., d) == 1.)
- return ST_PINF;
- else
- return ST_NINF;
+ if (Py_IS_FINITE(d)) {
+ if (d != 0) {
+ if (copysign(1., d) == 1.)
+ return ST_POS;
+ else
+ return ST_NEG;
+ }
+ else {
+ if (copysign(1., d) == 1.)
+ return ST_PZERO;
+ else
+ return ST_NZERO;
+ }
+ }
+ if (Py_IS_NAN(d))
+ return ST_NAN;
+ if (copysign(1., d) == 1.)
+ return ST_PINF;
+ else
+ return ST_NINF;
}
-#define SPECIAL_VALUE(z, table) \
- if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \
- errno = 0; \
- return table[special_type((z).real)] \
- [special_type((z).imag)]; \
- }
+#define SPECIAL_VALUE(z, table) \
+ if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \
+ errno = 0; \
+ return table[special_type((z).real)] \
+ [special_type((z).imag)]; \
+ }
#define P Py_MATH_PI
#define P14 0.25*Py_MATH_PI
@@ -126,34 +126,34 @@ static Py_complex acos_special_values[7][7];
static Py_complex
c_acos(Py_complex z)
{
- Py_complex s1, s2, r;
-
- SPECIAL_VALUE(z, acos_special_values);
-
- if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
- /* avoid unnecessary overflow for large arguments */
- r.real = atan2(fabs(z.imag), z.real);
- /* split into cases to make sure that the branch cut has the
- correct continuity on systems with unsigned zeros */
- if (z.real < 0.) {
- r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., z.imag);
- } else {
- r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., -z.imag);
- }
- } else {
- s1.real = 1.-z.real;
- s1.imag = -z.imag;
- s1 = c_sqrt(s1);
- s2.real = 1.+z.real;
- s2.imag = z.imag;
- s2 = c_sqrt(s2);
- r.real = 2.*atan2(s1.real, s2.real);
- r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real);
- }
- errno = 0;
- return r;
+ Py_complex s1, s2, r;
+
+ SPECIAL_VALUE(z, acos_special_values);
+
+ if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
+ /* avoid unnecessary overflow for large arguments */
+ r.real = atan2(fabs(z.imag), z.real);
+ /* split into cases to make sure that the branch cut has the
+ correct continuity on systems with unsigned zeros */
+ if (z.real < 0.) {
+ r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., z.imag);
+ } else {
+ r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., -z.imag);
+ }
+ } else {
+ s1.real = 1.-z.real;
+ s1.imag = -z.imag;
+ s1 = c_sqrt(s1);
+ s2.real = 1.+z.real;
+ s2.imag = z.imag;
+ s2 = c_sqrt(s2);
+ r.real = 2.*atan2(s1.real, s2.real);
+ r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_acos_doc,
@@ -167,26 +167,26 @@ static Py_complex acosh_special_values[7][7];
static Py_complex
c_acosh(Py_complex z)
{
- Py_complex s1, s2, r;
-
- SPECIAL_VALUE(z, acosh_special_values);
-
- if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
- /* avoid unnecessary overflow for large arguments */
- r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.;
- r.imag = atan2(z.imag, z.real);
- } else {
- s1.real = z.real - 1.;
- s1.imag = z.imag;
- s1 = c_sqrt(s1);
- s2.real = z.real + 1.;
- s2.imag = z.imag;
- s2 = c_sqrt(s2);
- r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag);
- r.imag = 2.*atan2(s1.imag, s2.real);
- }
- errno = 0;
- return r;
+ Py_complex s1, s2, r;
+
+ SPECIAL_VALUE(z, acosh_special_values);
+
+ if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
+ /* avoid unnecessary overflow for large arguments */
+ r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.;
+ r.imag = atan2(z.imag, z.real);
+ } else {
+ s1.real = z.real - 1.;
+ s1.imag = z.imag;
+ s1 = c_sqrt(s1);
+ s2.real = z.real + 1.;
+ s2.imag = z.imag;
+ s2 = c_sqrt(s2);
+ r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag);
+ r.imag = 2.*atan2(s1.imag, s2.real);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_acosh_doc,
@@ -198,14 +198,14 @@ PyDoc_STRVAR(c_acosh_doc,
static Py_complex
c_asin(Py_complex z)
{
- /* asin(z) = -i asinh(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_asinh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* asin(z) = -i asinh(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_asinh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
PyDoc_STRVAR(c_asin_doc,
@@ -219,31 +219,31 @@ static Py_complex asinh_special_values[7][7];
static Py_complex
c_asinh(Py_complex z)
{
- Py_complex s1, s2, r;
-
- SPECIAL_VALUE(z, asinh_special_values);
-
- if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
- if (z.imag >= 0.) {
- r.real = copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., z.real);
- } else {
- r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., -z.real);
- }
- r.imag = atan2(z.imag, fabs(z.real));
- } else {
- s1.real = 1.+z.imag;
- s1.imag = -z.real;
- s1 = c_sqrt(s1);
- s2.real = 1.-z.imag;
- s2.imag = z.real;
- s2 = c_sqrt(s2);
- r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag);
- r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag);
- }
- errno = 0;
- return r;
+ Py_complex s1, s2, r;
+
+ SPECIAL_VALUE(z, asinh_special_values);
+
+ if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
+ if (z.imag >= 0.) {
+ r.real = copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., z.real);
+ } else {
+ r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., -z.real);
+ }
+ r.imag = atan2(z.imag, fabs(z.real));
+ } else {
+ s1.real = 1.+z.imag;
+ s1.imag = -z.real;
+ s1 = c_sqrt(s1);
+ s2.real = 1.-z.imag;
+ s2.imag = z.real;
+ s2 = c_sqrt(s2);
+ r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag);
+ r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_asinh_doc,
@@ -255,14 +255,14 @@ PyDoc_STRVAR(c_asinh_doc,
static Py_complex
c_atan(Py_complex z)
{
- /* atan(z) = -i atanh(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_atanh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* atan(z) = -i atanh(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_atanh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
/* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow
@@ -270,29 +270,29 @@ c_atan(Py_complex z)
static double
c_atan2(Py_complex z)
{
- if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag))
- return Py_NAN;
- if (Py_IS_INFINITY(z.imag)) {
- if (Py_IS_INFINITY(z.real)) {
- if (copysign(1., z.real) == 1.)
- /* atan2(+-inf, +inf) == +-pi/4 */
- return copysign(0.25*Py_MATH_PI, z.imag);
- else
- /* atan2(+-inf, -inf) == +-pi*3/4 */
- return copysign(0.75*Py_MATH_PI, z.imag);
- }
- /* atan2(+-inf, x) == +-pi/2 for finite x */
- return copysign(0.5*Py_MATH_PI, z.imag);
- }
- if (Py_IS_INFINITY(z.real) || z.imag == 0.) {
- if (copysign(1., z.real) == 1.)
- /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
- return copysign(0., z.imag);
- else
- /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
- return copysign(Py_MATH_PI, z.imag);
- }
- return atan2(z.imag, z.real);
+ if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag))
+ return Py_NAN;
+ if (Py_IS_INFINITY(z.imag)) {
+ if (Py_IS_INFINITY(z.real)) {
+ if (copysign(1., z.real) == 1.)
+ /* atan2(+-inf, +inf) == +-pi/4 */
+ return copysign(0.25*Py_MATH_PI, z.imag);
+ else
+ /* atan2(+-inf, -inf) == +-pi*3/4 */
+ return copysign(0.75*Py_MATH_PI, z.imag);
+ }
+ /* atan2(+-inf, x) == +-pi/2 for finite x */
+ return copysign(0.5*Py_MATH_PI, z.imag);
+ }
+ if (Py_IS_INFINITY(z.real) || z.imag == 0.) {
+ if (copysign(1., z.real) == 1.)
+ /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
+ return copysign(0., z.imag);
+ else
+ /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
+ return copysign(Py_MATH_PI, z.imag);
+ }
+ return atan2(z.imag, z.real);
}
PyDoc_STRVAR(c_atan_doc,
@@ -306,48 +306,48 @@ static Py_complex atanh_special_values[7][7];
static Py_complex
c_atanh(Py_complex z)
{
- Py_complex r;
- double ay, h;
-
- SPECIAL_VALUE(z, atanh_special_values);
-
- /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */
- if (z.real < 0.) {
- return c_neg(c_atanh(c_neg(z)));
- }
-
- ay = fabs(z.imag);
- if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) {
- /*
- if abs(z) is large then we use the approximation
- atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign
- of z.imag)
- */
- h = hypot(z.real/2., z.imag/2.); /* safe from overflow */
- r.real = z.real/4./h/h;
- /* the two negations in the next line cancel each other out
- except when working with unsigned zeros: they're there to
- ensure that the branch cut has the correct continuity on
- systems that don't support signed zeros */
- r.imag = -copysign(Py_MATH_PI/2., -z.imag);
- errno = 0;
- } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) {
- /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */
- if (ay == 0.) {
- r.real = INF;
- r.imag = z.imag;
- errno = EDOM;
- } else {
- r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.)));
- r.imag = copysign(atan2(2., -ay)/2, z.imag);
- errno = 0;
- }
- } else {
- r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.;
- r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.;
- errno = 0;
- }
- return r;
+ Py_complex r;
+ double ay, h;
+
+ SPECIAL_VALUE(z, atanh_special_values);
+
+ /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */
+ if (z.real < 0.) {
+ return c_neg(c_atanh(c_neg(z)));
+ }
+
+ ay = fabs(z.imag);
+ if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) {
+ /*
+ if abs(z) is large then we use the approximation
+ atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign
+ of z.imag)
+ */
+ h = hypot(z.real/2., z.imag/2.); /* safe from overflow */
+ r.real = z.real/4./h/h;
+ /* the two negations in the next line cancel each other out
+ except when working with unsigned zeros: they're there to
+ ensure that the branch cut has the correct continuity on
+ systems that don't support signed zeros */
+ r.imag = -copysign(Py_MATH_PI/2., -z.imag);
+ errno = 0;
+ } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) {
+ /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */
+ if (ay == 0.) {
+ r.real = INF;
+ r.imag = z.imag;
+ errno = EDOM;
+ } else {
+ r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.)));
+ r.imag = copysign(atan2(2., -ay)/2, z.imag);
+ errno = 0;
+ }
+ } else {
+ r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.;
+ r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.;
+ errno = 0;
+ }
+ return r;
}
PyDoc_STRVAR(c_atanh_doc,
@@ -359,12 +359,12 @@ PyDoc_STRVAR(c_atanh_doc,
static Py_complex
c_cos(Py_complex z)
{
- /* cos(z) = cosh(iz) */
- Py_complex r;
- r.real = -z.imag;
- r.imag = z.real;
- r = c_cosh(r);
- return r;
+ /* cos(z) = cosh(iz) */
+ Py_complex r;
+ r.real = -z.imag;
+ r.imag = z.real;
+ r = c_cosh(r);
+ return r;
}
PyDoc_STRVAR(c_cos_doc,
@@ -379,51 +379,51 @@ static Py_complex cosh_special_values[7][7];
static Py_complex
c_cosh(Py_complex z)
{
- Py_complex r;
- double x_minus_one;
-
- /* special treatment for cosh(+/-inf + iy) if y is not a NaN */
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) &&
- (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- else {
- r.real = copysign(INF, cos(z.imag));
- r.imag = -copysign(INF, sin(z.imag));
- }
- }
- else {
- r = cosh_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if y is +/- infinity and x is not
- a NaN */
- if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
- /* deal correctly with cases where cosh(z.real) overflows but
- cosh(z) does not. */
- x_minus_one = z.real - copysign(1., z.real);
- r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E;
- r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E;
- } else {
- r.real = cos(z.imag) * cosh(z.real);
- r.imag = sin(z.imag) * sinh(z.real);
- }
- /* detect overflow, and set errno accordingly */
- if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
- errno = ERANGE;
- else
- errno = 0;
- return r;
+ Py_complex r;
+ double x_minus_one;
+
+ /* special treatment for cosh(+/-inf + iy) if y is not a NaN */
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) &&
+ (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ else {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = -copysign(INF, sin(z.imag));
+ }
+ }
+ else {
+ r = cosh_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if y is +/- infinity and x is not
+ a NaN */
+ if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
+ /* deal correctly with cases where cosh(z.real) overflows but
+ cosh(z) does not. */
+ x_minus_one = z.real - copysign(1., z.real);
+ r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E;
+ r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E;
+ } else {
+ r.real = cos(z.imag) * cosh(z.real);
+ r.imag = sin(z.imag) * sinh(z.real);
+ }
+ /* detect overflow, and set errno accordingly */
+ if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_cosh_doc,
@@ -439,51 +439,51 @@ static Py_complex exp_special_values[7][7];
static Py_complex
c_exp(Py_complex z)
{
- Py_complex r;
- double l;
-
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
- && (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- else {
- r.real = copysign(0., cos(z.imag));
- r.imag = copysign(0., sin(z.imag));
- }
- }
- else {
- r = exp_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if y is +/- infinity and x is not
- a NaN and not -infinity */
- if (Py_IS_INFINITY(z.imag) &&
- (Py_IS_FINITE(z.real) ||
- (Py_IS_INFINITY(z.real) && z.real > 0)))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- if (z.real > CM_LOG_LARGE_DOUBLE) {
- l = exp(z.real-1.);
- r.real = l*cos(z.imag)*Py_MATH_E;
- r.imag = l*sin(z.imag)*Py_MATH_E;
- } else {
- l = exp(z.real);
- r.real = l*cos(z.imag);
- r.imag = l*sin(z.imag);
- }
- /* detect overflow, and set errno accordingly */
- if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
- errno = ERANGE;
- else
- errno = 0;
- return r;
+ Py_complex r;
+ double l;
+
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
+ && (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ else {
+ r.real = copysign(0., cos(z.imag));
+ r.imag = copysign(0., sin(z.imag));
+ }
+ }
+ else {
+ r = exp_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if y is +/- infinity and x is not
+ a NaN and not -infinity */
+ if (Py_IS_INFINITY(z.imag) &&
+ (Py_IS_FINITE(z.real) ||
+ (Py_IS_INFINITY(z.real) && z.real > 0)))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ if (z.real > CM_LOG_LARGE_DOUBLE) {
+ l = exp(z.real-1.);
+ r.real = l*cos(z.imag)*Py_MATH_E;
+ r.imag = l*sin(z.imag)*Py_MATH_E;
+ } else {
+ l = exp(z.real);
+ r.real = l*cos(z.imag);
+ r.imag = l*sin(z.imag);
+ }
+ /* detect overflow, and set errno accordingly */
+ if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_exp_doc,
@@ -497,85 +497,85 @@ static Py_complex log_special_values[7][7];
static Py_complex
c_log(Py_complex z)
{
- /*
- The usual formula for the real part is log(hypot(z.real, z.imag)).
- There are four situations where this formula is potentially
- problematic:
-
- (1) the absolute value of z is subnormal. Then hypot is subnormal,
- so has fewer than the usual number of bits of accuracy, hence may
- have large relative error. This then gives a large absolute error
- in the log. This can be solved by rescaling z by a suitable power
- of 2.
-
- (2) the absolute value of z is greater than DBL_MAX (e.g. when both
- z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
- Again, rescaling solves this.
-
- (3) the absolute value of z is close to 1. In this case it's
- difficult to achieve good accuracy, at least in part because a
- change of 1ulp in the real or imaginary part of z can result in a
- change of billions of ulps in the correctly rounded answer.
-
- (4) z = 0. The simplest thing to do here is to call the
- floating-point log with an argument of 0, and let its behaviour
- (returning -infinity, signaling a floating-point exception, setting
- errno, or whatever) determine that of c_log. So the usual formula
- is fine here.
-
- */
-
- Py_complex r;
- double ax, ay, am, an, h;
-
- SPECIAL_VALUE(z, log_special_values);
-
- ax = fabs(z.real);
- ay = fabs(z.imag);
-
- if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) {
- r.real = log(hypot(ax/2., ay/2.)) + M_LN2;
- } else if (ax < DBL_MIN && ay < DBL_MIN) {
- if (ax > 0. || ay > 0.) {
- /* catch cases where hypot(ax, ay) is subnormal */
- r.real = log(hypot(ldexp(ax, DBL_MANT_DIG),
- ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2;
- }
- else {
- /* log(+/-0. +/- 0i) */
- r.real = -INF;
- r.imag = atan2(z.imag, z.real);
- errno = EDOM;
- return r;
- }
- } else {
- h = hypot(ax, ay);
- if (0.71 <= h && h <= 1.73) {
- am = ax > ay ? ax : ay; /* max(ax, ay) */
- an = ax > ay ? ay : ax; /* min(ax, ay) */
- r.real = m_log1p((am-1)*(am+1)+an*an)/2.;
- } else {
- r.real = log(h);
- }
- }
- r.imag = atan2(z.imag, z.real);
- errno = 0;
- return r;
+ /*
+ The usual formula for the real part is log(hypot(z.real, z.imag)).
+ There are four situations where this formula is potentially
+ problematic:
+
+ (1) the absolute value of z is subnormal. Then hypot is subnormal,
+ so has fewer than the usual number of bits of accuracy, hence may
+ have large relative error. This then gives a large absolute error
+ in the log. This can be solved by rescaling z by a suitable power
+ of 2.
+
+ (2) the absolute value of z is greater than DBL_MAX (e.g. when both
+ z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
+ Again, rescaling solves this.
+
+ (3) the absolute value of z is close to 1. In this case it's
+ difficult to achieve good accuracy, at least in part because a
+ change of 1ulp in the real or imaginary part of z can result in a
+ change of billions of ulps in the correctly rounded answer.
+
+ (4) z = 0. The simplest thing to do here is to call the
+ floating-point log with an argument of 0, and let its behaviour
+ (returning -infinity, signaling a floating-point exception, setting
+ errno, or whatever) determine that of c_log. So the usual formula
+ is fine here.
+
+ */
+
+ Py_complex r;
+ double ax, ay, am, an, h;
+
+ SPECIAL_VALUE(z, log_special_values);
+
+ ax = fabs(z.real);
+ ay = fabs(z.imag);
+
+ if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) {
+ r.real = log(hypot(ax/2., ay/2.)) + M_LN2;
+ } else if (ax < DBL_MIN && ay < DBL_MIN) {
+ if (ax > 0. || ay > 0.) {
+ /* catch cases where hypot(ax, ay) is subnormal */
+ r.real = log(hypot(ldexp(ax, DBL_MANT_DIG),
+ ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2;
+ }
+ else {
+ /* log(+/-0. +/- 0i) */
+ r.real = -INF;
+ r.imag = atan2(z.imag, z.real);
+ errno = EDOM;
+ return r;
+ }
+ } else {
+ h = hypot(ax, ay);
+ if (0.71 <= h && h <= 1.73) {
+ am = ax > ay ? ax : ay; /* max(ax, ay) */
+ an = ax > ay ? ay : ax; /* min(ax, ay) */
+ r.real = m_log1p((am-1)*(am+1)+an*an)/2.;
+ } else {
+ r.real = log(h);
+ }
+ }
+ r.imag = atan2(z.imag, z.real);
+ errno = 0;
+ return r;
}
static Py_complex
c_log10(Py_complex z)
{
- Py_complex r;
- int errno_save;
-
- r = c_log(z);
- errno_save = errno; /* just in case the divisions affect errno */
- r.real = r.real / M_LN10;
- r.imag = r.imag / M_LN10;
- errno = errno_save;
- return r;
+ Py_complex r;
+ int errno_save;
+
+ r = c_log(z);
+ errno_save = errno; /* just in case the divisions affect errno */
+ r.real = r.real / M_LN10;
+ r.imag = r.imag / M_LN10;
+ errno = errno_save;
+ return r;
}
PyDoc_STRVAR(c_log10_doc,
@@ -587,14 +587,14 @@ PyDoc_STRVAR(c_log10_doc,
static Py_complex
c_sin(Py_complex z)
{
- /* sin(z) = -i sin(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_sinh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* sin(z) = -i sin(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_sinh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
PyDoc_STRVAR(c_sin_doc,
@@ -609,50 +609,50 @@ static Py_complex sinh_special_values[7][7];
static Py_complex
c_sinh(Py_complex z)
{
- Py_complex r;
- double x_minus_one;
-
- /* special treatment for sinh(+/-inf + iy) if y is finite and
- nonzero */
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
- && (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- else {
- r.real = -copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- }
- else {
- r = sinh_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if y is +/- infinity and x is not
- a NaN */
- if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
- x_minus_one = z.real - copysign(1., z.real);
- r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E;
- r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E;
- } else {
- r.real = cos(z.imag) * sinh(z.real);
- r.imag = sin(z.imag) * cosh(z.real);
- }
- /* detect overflow, and set errno accordingly */
- if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
- errno = ERANGE;
- else
- errno = 0;
- return r;
+ Py_complex r;
+ double x_minus_one;
+
+ /* special treatment for sinh(+/-inf + iy) if y is finite and
+ nonzero */
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
+ && (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ else {
+ r.real = -copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ }
+ else {
+ r = sinh_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if y is +/- infinity and x is not
+ a NaN */
+ if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
+ x_minus_one = z.real - copysign(1., z.real);
+ r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E;
+ r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E;
+ } else {
+ r.real = cos(z.imag) * sinh(z.real);
+ r.imag = sin(z.imag) * cosh(z.real);
+ }
+ /* detect overflow, and set errno accordingly */
+ if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_sinh_doc,
@@ -666,68 +666,68 @@ static Py_complex sqrt_special_values[7][7];
static Py_complex
c_sqrt(Py_complex z)
{
- /*
- Method: use symmetries to reduce to the case when x = z.real and y
- = z.imag are nonnegative. Then the real part of the result is
- given by
-
- s = sqrt((x + hypot(x, y))/2)
-
- and the imaginary part is
-
- d = (y/2)/s
-
- If either x or y is very large then there's a risk of overflow in
- computation of the expression x + hypot(x, y). We can avoid this
- by rewriting the formula for s as:
-
- s = 2*sqrt(x/8 + hypot(x/8, y/8))
-
- This costs us two extra multiplications/divisions, but avoids the
- overhead of checking for x and y large.
-
- If both x and y are subnormal then hypot(x, y) may also be
- subnormal, so will lack full precision. We solve this by rescaling
- x and y by a sufficiently large power of 2 to ensure that x and y
- are normal.
- */
-
-
- Py_complex r;
- double s,d;
- double ax, ay;
-
- SPECIAL_VALUE(z, sqrt_special_values);
-
- if (z.real == 0. && z.imag == 0.) {
- r.real = 0.;
- r.imag = z.imag;
- return r;
- }
-
- ax = fabs(z.real);
- ay = fabs(z.imag);
-
- if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) {
- /* here we catch cases where hypot(ax, ay) is subnormal */
- ax = ldexp(ax, CM_SCALE_UP);
- s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))),
- CM_SCALE_DOWN);
- } else {
- ax /= 8.;
- s = 2.*sqrt(ax + hypot(ax, ay/8.));
- }
- d = ay/(2.*s);
-
- if (z.real >= 0.) {
- r.real = s;
- r.imag = copysign(d, z.imag);
- } else {
- r.real = d;
- r.imag = copysign(s, z.imag);
- }
- errno = 0;
- return r;
+ /*
+ Method: use symmetries to reduce to the case when x = z.real and y
+ = z.imag are nonnegative. Then the real part of the result is
+ given by
+
+ s = sqrt((x + hypot(x, y))/2)
+
+ and the imaginary part is
+
+ d = (y/2)/s
+
+ If either x or y is very large then there's a risk of overflow in
+ computation of the expression x + hypot(x, y). We can avoid this
+ by rewriting the formula for s as:
+
+ s = 2*sqrt(x/8 + hypot(x/8, y/8))
+
+ This costs us two extra multiplications/divisions, but avoids the
+ overhead of checking for x and y large.
+
+ If both x and y are subnormal then hypot(x, y) may also be
+ subnormal, so will lack full precision. We solve this by rescaling
+ x and y by a sufficiently large power of 2 to ensure that x and y
+ are normal.
+ */
+
+
+ Py_complex r;
+ double s,d;
+ double ax, ay;
+
+ SPECIAL_VALUE(z, sqrt_special_values);
+
+ if (z.real == 0. && z.imag == 0.) {
+ r.real = 0.;
+ r.imag = z.imag;
+ return r;
+ }
+
+ ax = fabs(z.real);
+ ay = fabs(z.imag);
+
+ if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) {
+ /* here we catch cases where hypot(ax, ay) is subnormal */
+ ax = ldexp(ax, CM_SCALE_UP);
+ s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))),
+ CM_SCALE_DOWN);
+ } else {
+ ax /= 8.;
+ s = 2.*sqrt(ax + hypot(ax, ay/8.));
+ }
+ d = ay/(2.*s);
+
+ if (z.real >= 0.) {
+ r.real = s;
+ r.imag = copysign(d, z.imag);
+ } else {
+ r.real = d;
+ r.imag = copysign(s, z.imag);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_sqrt_doc,
@@ -739,14 +739,14 @@ PyDoc_STRVAR(c_sqrt_doc,
static Py_complex
c_tan(Py_complex z)
{
- /* tan(z) = -i tanh(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_tanh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* tan(z) = -i tanh(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_tanh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
PyDoc_STRVAR(c_tan_doc,
@@ -761,65 +761,65 @@ static Py_complex tanh_special_values[7][7];
static Py_complex
c_tanh(Py_complex z)
{
- /* Formula:
-
- tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) /
- (1+tan(y)^2 tanh(x)^2)
-
- To avoid excessive roundoff error, 1-tanh(x)^2 is better computed
- as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2
- by 4 exp(-2*x) instead, to avoid possible overflow in the
- computation of cosh(x).
-
- */
-
- Py_complex r;
- double tx, ty, cx, txty, denom;
-
- /* special treatment for tanh(+/-inf + iy) if y is finite and
- nonzero */
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
- && (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = 1.0;
- r.imag = copysign(0.,
- 2.*sin(z.imag)*cos(z.imag));
- }
- else {
- r.real = -1.0;
- r.imag = copysign(0.,
- 2.*sin(z.imag)*cos(z.imag));
- }
- }
- else {
- r = tanh_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if z.imag is +/-infinity and
- z.real is finite */
- if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- /* danger of overflow in 2.*z.imag !*/
- if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
- r.real = copysign(1., z.real);
- r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real));
- } else {
- tx = tanh(z.real);
- ty = tan(z.imag);
- cx = 1./cosh(z.real);
- txty = tx*ty;
- denom = 1. + txty*txty;
- r.real = tx*(1.+ty*ty)/denom;
- r.imag = ((ty/denom)*cx)*cx;
- }
- errno = 0;
- return r;
+ /* Formula:
+
+ tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) /
+ (1+tan(y)^2 tanh(x)^2)
+
+ To avoid excessive roundoff error, 1-tanh(x)^2 is better computed
+ as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2
+ by 4 exp(-2*x) instead, to avoid possible overflow in the
+ computation of cosh(x).
+
+ */
+
+ Py_complex r;
+ double tx, ty, cx, txty, denom;
+
+ /* special treatment for tanh(+/-inf + iy) if y is finite and
+ nonzero */
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
+ && (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = 1.0;
+ r.imag = copysign(0.,
+ 2.*sin(z.imag)*cos(z.imag));
+ }
+ else {
+ r.real = -1.0;
+ r.imag = copysign(0.,
+ 2.*sin(z.imag)*cos(z.imag));
+ }
+ }
+ else {
+ r = tanh_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if z.imag is +/-infinity and
+ z.real is finite */
+ if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ /* danger of overflow in 2.*z.imag !*/
+ if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
+ r.real = copysign(1., z.real);
+ r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real));
+ } else {
+ tx = tanh(z.real);
+ ty = tan(z.imag);
+ cx = 1./cosh(z.real);
+ txty = tx*ty;
+ denom = 1. + txty*txty;
+ r.real = tx*(1.+ty*ty)/denom;
+ r.imag = ((ty/denom)*cx)*cx;
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_tanh_doc,
@@ -831,23 +831,23 @@ PyDoc_STRVAR(c_tanh_doc,
static PyObject *
cmath_log(PyObject *self, PyObject *args)
{
- Py_complex x;
- Py_complex y;
-
- if (!PyArg_ParseTuple(args, "D|D", &x, &y))
- return NULL;
-
- errno = 0;
- PyFPE_START_PROTECT("complex function", return 0)
- x = c_log(x);
- if (PyTuple_GET_SIZE(args) == 2) {
- y = c_log(y);
- x = c_quot(x, y);
- }
- PyFPE_END_PROTECT(x)
- if (errno != 0)
- return math_error();
- return PyComplex_FromCComplex(x);
+ Py_complex x;
+ Py_complex y;
+
+ if (!PyArg_ParseTuple(args, "D|D", &x, &y))
+ return NULL;
+
+ errno = 0;
+ PyFPE_START_PROTECT("complex function", return 0)
+ x = c_log(x);
+ if (PyTuple_GET_SIZE(args) == 2) {
+ y = c_log(y);
+ x = c_quot(x, y);
+ }
+ PyFPE_END_PROTECT(x)
+ if (errno != 0)
+ return math_error();
+ return PyComplex_FromCComplex(x);
}
PyDoc_STRVAR(cmath_log_doc,
@@ -860,42 +860,42 @@ If the base not specified, returns the natural logarithm (base e) of x.");
static PyObject *
math_error(void)
{
- if (errno == EDOM)
- PyErr_SetString(PyExc_ValueError, "math domain error");
- else if (errno == ERANGE)
- PyErr_SetString(PyExc_OverflowError, "math range error");
- else /* Unexpected math error */
- PyErr_SetFromErrno(PyExc_ValueError);
- return NULL;
+ if (errno == EDOM)
+ PyErr_SetString(PyExc_ValueError, "math domain error");
+ else if (errno == ERANGE)
+ PyErr_SetString(PyExc_OverflowError, "math range error");
+ else /* Unexpected math error */
+ PyErr_SetFromErrno(PyExc_ValueError);
+ return NULL;
}
static PyObject *
math_1(PyObject *args, Py_complex (*func)(Py_complex))
{
- Py_complex x,r ;
- if (!PyArg_ParseTuple(args, "D", &x))
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("complex function", return 0);
- r = (*func)(x);
- PyFPE_END_PROTECT(r);
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ValueError, "math domain error");
- return NULL;
- }
- else if (errno == ERANGE) {
- PyErr_SetString(PyExc_OverflowError, "math range error");
- return NULL;
- }
- else {
- return PyComplex_FromCComplex(r);
- }
+ Py_complex x,r ;
+ if (!PyArg_ParseTuple(args, "D", &x))
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("complex function", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ValueError, "math domain error");
+ return NULL;
+ }
+ else if (errno == ERANGE) {
+ PyErr_SetString(PyExc_OverflowError, "math range error");
+ return NULL;
+ }
+ else {
+ return PyComplex_FromCComplex(r);
+ }
}
#define FUNC1(stubname, func) \
- static PyObject * stubname(PyObject *self, PyObject *args) { \
- return math_1(args, func); \
- }
+ static PyObject * stubname(PyObject *self, PyObject *args) { \
+ return math_1(args, func); \
+ }
FUNC1(cmath_acos, c_acos)
FUNC1(cmath_acosh, c_acosh)
@@ -916,18 +916,18 @@ FUNC1(cmath_tanh, c_tanh)
static PyObject *
cmath_phase(PyObject *self, PyObject *args)
{
- Py_complex z;
- double phi;
- if (!PyArg_ParseTuple(args, "D:phase", &z))
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("arg function", return 0)
- phi = c_atan2(z);
- PyFPE_END_PROTECT(phi)
- if (errno != 0)
- return math_error();
- else
- return PyFloat_FromDouble(phi);
+ Py_complex z;
+ double phi;
+ if (!PyArg_ParseTuple(args, "D:phase", &z))
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("arg function", return 0)
+ phi = c_atan2(z);
+ PyFPE_END_PROTECT(phi)
+ if (errno != 0)
+ return math_error();
+ else
+ return PyFloat_FromDouble(phi);
}
PyDoc_STRVAR(cmath_phase_doc,
@@ -937,18 +937,18 @@ Return argument, also known as the phase angle, of a complex.");
static PyObject *
cmath_polar(PyObject *self, PyObject *args)
{
- Py_complex z;
- double r, phi;
- if (!PyArg_ParseTuple(args, "D:polar", &z))
- return NULL;
- PyFPE_START_PROTECT("polar function", return 0)
- phi = c_atan2(z); /* should not cause any exception */
- r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */
- PyFPE_END_PROTECT(r)
- if (errno != 0)
- return math_error();
- else
- return Py_BuildValue("dd", r, phi);
+ Py_complex z;
+ double r, phi;
+ if (!PyArg_ParseTuple(args, "D:polar", &z))
+ return NULL;
+ PyFPE_START_PROTECT("polar function", return 0)
+ phi = c_atan2(z); /* should not cause any exception */
+ r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */
+ PyFPE_END_PROTECT(r)
+ if (errno != 0)
+ return math_error();
+ else
+ return Py_BuildValue("dd", r, phi);
}
PyDoc_STRVAR(cmath_polar_doc,
@@ -972,51 +972,51 @@ static Py_complex rect_special_values[7][7];
static PyObject *
cmath_rect(PyObject *self, PyObject *args)
{
- Py_complex z;
- double r, phi;
- if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi))
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("rect function", return 0)
-
- /* deal with special values */
- if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) {
- /* if r is +/-infinity and phi is finite but nonzero then
- result is (+-INF +-INF i), but we need to compute cos(phi)
- and sin(phi) to figure out the signs. */
- if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi)
- && (phi != 0.))) {
- if (r > 0) {
- z.real = copysign(INF, cos(phi));
- z.imag = copysign(INF, sin(phi));
- }
- else {
- z.real = -copysign(INF, cos(phi));
- z.imag = -copysign(INF, sin(phi));
- }
- }
- else {
- z = rect_special_values[special_type(r)]
- [special_type(phi)];
- }
- /* need to set errno = EDOM if r is a nonzero number and phi
- is infinite */
- if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi))
- errno = EDOM;
- else
- errno = 0;
- }
- else {
- z.real = r * cos(phi);
- z.imag = r * sin(phi);
- errno = 0;
- }
-
- PyFPE_END_PROTECT(z)
- if (errno != 0)
- return math_error();
- else
- return PyComplex_FromCComplex(z);
+ Py_complex z;
+ double r, phi;
+ if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi))
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("rect function", return 0)
+
+ /* deal with special values */
+ if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) {
+ /* if r is +/-infinity and phi is finite but nonzero then
+ result is (+-INF +-INF i), but we need to compute cos(phi)
+ and sin(phi) to figure out the signs. */
+ if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi)
+ && (phi != 0.))) {
+ if (r > 0) {
+ z.real = copysign(INF, cos(phi));
+ z.imag = copysign(INF, sin(phi));
+ }
+ else {
+ z.real = -copysign(INF, cos(phi));
+ z.imag = -copysign(INF, sin(phi));
+ }
+ }
+ else {
+ z = rect_special_values[special_type(r)]
+ [special_type(phi)];
+ }
+ /* need to set errno = EDOM if r is a nonzero number and phi
+ is infinite */
+ if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else {
+ z.real = r * cos(phi);
+ z.imag = r * sin(phi);
+ errno = 0;
+ }
+
+ PyFPE_END_PROTECT(z)
+ if (errno != 0)
+ return math_error();
+ else
+ return PyComplex_FromCComplex(z);
}
PyDoc_STRVAR(cmath_rect_doc,
@@ -1026,10 +1026,10 @@ Convert from polar coordinates to rectangular coordinates.");
static PyObject *
cmath_isnan(PyObject *self, PyObject *args)
{
- Py_complex z;
- if (!PyArg_ParseTuple(args, "D:isnan", &z))
- return NULL;
- return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag));
+ Py_complex z;
+ if (!PyArg_ParseTuple(args, "D:isnan", &z))
+ return NULL;
+ return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag));
}
PyDoc_STRVAR(cmath_isnan_doc,
@@ -1039,11 +1039,11 @@ Checks if the real or imaginary part of z not a number (NaN)");
static PyObject *
cmath_isinf(PyObject *self, PyObject *args)
{
- Py_complex z;
- if (!PyArg_ParseTuple(args, "D:isnan", &z))
- return NULL;
- return PyBool_FromLong(Py_IS_INFINITY(z.real) ||
- Py_IS_INFINITY(z.imag));
+ Py_complex z;
+ if (!PyArg_ParseTuple(args, "D:isnan", &z))
+ return NULL;
+ return PyBool_FromLong(Py_IS_INFINITY(z.real) ||
+ Py_IS_INFINITY(z.imag));
}
PyDoc_STRVAR(cmath_isinf_doc,
@@ -1056,169 +1056,169 @@ PyDoc_STRVAR(module_doc,
"functions for complex numbers.");
static PyMethodDef cmath_methods[] = {
- {"acos", cmath_acos, METH_VARARGS, c_acos_doc},
- {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc},
- {"asin", cmath_asin, METH_VARARGS, c_asin_doc},
- {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc},
- {"atan", cmath_atan, METH_VARARGS, c_atan_doc},
- {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc},
- {"cos", cmath_cos, METH_VARARGS, c_cos_doc},
- {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc},
- {"exp", cmath_exp, METH_VARARGS, c_exp_doc},
- {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc},
- {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc},
- {"log", cmath_log, METH_VARARGS, cmath_log_doc},
- {"log10", cmath_log10, METH_VARARGS, c_log10_doc},
- {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc},
- {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc},
- {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc},
- {"sin", cmath_sin, METH_VARARGS, c_sin_doc},
- {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc},
- {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc},
- {"tan", cmath_tan, METH_VARARGS, c_tan_doc},
- {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc},
- {NULL, NULL} /* sentinel */
+ {"acos", cmath_acos, METH_VARARGS, c_acos_doc},
+ {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc},
+ {"asin", cmath_asin, METH_VARARGS, c_asin_doc},
+ {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc},
+ {"atan", cmath_atan, METH_VARARGS, c_atan_doc},
+ {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc},
+ {"cos", cmath_cos, METH_VARARGS, c_cos_doc},
+ {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc},
+ {"exp", cmath_exp, METH_VARARGS, c_exp_doc},
+ {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc},
+ {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc},
+ {"log", cmath_log, METH_VARARGS, cmath_log_doc},
+ {"log10", cmath_log10, METH_VARARGS, c_log10_doc},
+ {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc},
+ {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc},
+ {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc},
+ {"sin", cmath_sin, METH_VARARGS, c_sin_doc},
+ {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc},
+ {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc},
+ {"tan", cmath_tan, METH_VARARGS, c_tan_doc},
+ {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc},
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef cmathmodule = {
- PyModuleDef_HEAD_INIT,
- "cmath",
- module_doc,
- -1,
- cmath_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "cmath",
+ module_doc,
+ -1,
+ cmath_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_cmath(void)
{
- PyObject *m;
+ PyObject *m;
- m = PyModule_Create(&cmathmodule);
- if (m == NULL)
- return NULL;
+ m = PyModule_Create(&cmathmodule);
+ if (m == NULL)
+ return NULL;
- PyModule_AddObject(m, "pi",
- PyFloat_FromDouble(Py_MATH_PI));
- PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
+ PyModule_AddObject(m, "pi",
+ PyFloat_FromDouble(Py_MATH_PI));
+ PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
- /* initialize special value tables */
+ /* initialize special value tables */
#define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY }
#define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p;
- INIT_SPECIAL_VALUES(acos_special_values, {
- C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF)
- C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
- C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
- C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
- C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
- C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF)
- C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(acosh_special_values, {
- C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
- C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(asinh_special_values, {
- C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N)
- C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N)
- C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
- C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(atanh_special_values, {
- C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N)
- C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N)
- C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N)
- C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N)
- C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N)
- C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N)
- C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(cosh_special_values, {
- C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.)
- C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(exp_special_values, {
- C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(log_special_values, {
- C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
- C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(sinh_special_values, {
- C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N)
- C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(sqrt_special_values, {
- C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF)
- C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N)
- C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(tanh_special_values, {
- C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.)
- C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(rect_special_values, {
- C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.)
- C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
- return m;
+ INIT_SPECIAL_VALUES(acos_special_values, {
+ C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF)
+ C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
+ C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
+ C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
+ C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
+ C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF)
+ C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(acosh_special_values, {
+ C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
+ C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(asinh_special_values, {
+ C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N)
+ C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N)
+ C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
+ C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(atanh_special_values, {
+ C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N)
+ C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N)
+ C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N)
+ C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N)
+ C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N)
+ C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N)
+ C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(cosh_special_values, {
+ C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.)
+ C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(exp_special_values, {
+ C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(log_special_values, {
+ C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
+ C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(sinh_special_values, {
+ C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N)
+ C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(sqrt_special_values, {
+ C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF)
+ C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N)
+ C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(tanh_special_values, {
+ C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.)
+ C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(rect_special_values, {
+ C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.)
+ C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+ return m;
}
diff --git a/Modules/cryptmodule.c b/Modules/cryptmodule.c
index d3d9271..d5a42ff 100644
--- a/Modules/cryptmodule.c
+++ b/Modules/cryptmodule.c
@@ -14,17 +14,17 @@
static PyObject *crypt_crypt(PyObject *self, PyObject *args)
{
- char *word, *salt;
+ char *word, *salt;
#ifndef __VMS
- extern char * crypt(const char *, const char *);
+ extern char * crypt(const char *, const char *);
#endif
- if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
- return NULL;
- }
- /* On some platforms (AtheOS) crypt returns NULL for an invalid
- salt. Return None in that case. XXX Maybe raise an exception? */
- return Py_BuildValue("s", crypt(word, salt));
+ if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
+ return NULL;
+ }
+ /* On some platforms (AtheOS) crypt returns NULL for an invalid
+ salt. Return None in that case. XXX Maybe raise an exception? */
+ return Py_BuildValue("s", crypt(word, salt));
}
@@ -38,25 +38,25 @@ the same alphabet as the salt.");
static PyMethodDef crypt_methods[] = {
- {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
- {NULL, NULL} /* sentinel */
+ {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef cryptmodule = {
- PyModuleDef_HEAD_INIT,
- "crypt",
- NULL,
- -1,
- crypt_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "crypt",
+ NULL,
+ -1,
+ crypt_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_crypt(void)
{
- return PyModule_Create(&cryptmodule);
+ return PyModule_Create(&cryptmodule);
}
diff --git a/Modules/datetimemodule.c b/Modules/datetimemodule.c
index d4714bd..29ab906 100644
--- a/Modules/datetimemodule.c
+++ b/Modules/datetimemodule.c
@@ -25,7 +25,7 @@
* final result fits in a C int (this can be an issue on 64-bit boxes).
*/
#if SIZEOF_INT < 4
-# error "datetime.c requires that C int have at least 32 bits"
+# error "datetime.c requires that C int have at least 32 bits"
#endif
#define MINYEAR 1
@@ -39,59 +39,59 @@
#define MAX_DELTA_DAYS 999999999
/* Rename the long macros in datetime.h to more reasonable short names. */
-#define GET_YEAR PyDateTime_GET_YEAR
-#define GET_MONTH PyDateTime_GET_MONTH
-#define GET_DAY PyDateTime_GET_DAY
-#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
-#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
-#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
-#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
+#define GET_YEAR PyDateTime_GET_YEAR
+#define GET_MONTH PyDateTime_GET_MONTH
+#define GET_DAY PyDateTime_GET_DAY
+#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
+#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
+#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
+#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
/* Date accessors for date and datetime. */
-#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
- ((o)->data[1] = ((v) & 0x00ff)))
-#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
-#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
+#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
+ ((o)->data[1] = ((v) & 0x00ff)))
+#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
+#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
/* Date/Time accessors for datetime. */
-#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
-#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
-#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
-#define DATE_SET_MICROSECOND(o, v) \
- (((o)->data[7] = ((v) & 0xff0000) >> 16), \
- ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
- ((o)->data[9] = ((v) & 0x0000ff)))
+#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
+#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
+#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
+#define DATE_SET_MICROSECOND(o, v) \
+ (((o)->data[7] = ((v) & 0xff0000) >> 16), \
+ ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
+ ((o)->data[9] = ((v) & 0x0000ff)))
/* Time accessors for time. */
-#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
-#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
-#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
-#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
-#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
-#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
-#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
-#define TIME_SET_MICROSECOND(o, v) \
- (((o)->data[3] = ((v) & 0xff0000) >> 16), \
- ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
- ((o)->data[5] = ((v) & 0x0000ff)))
+#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
+#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
+#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
+#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
+#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
+#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
+#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
+#define TIME_SET_MICROSECOND(o, v) \
+ (((o)->data[3] = ((v) & 0xff0000) >> 16), \
+ ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
+ ((o)->data[5] = ((v) & 0x0000ff)))
/* Delta accessors for timedelta. */
-#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
-#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
-#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
+#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
+#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
+#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
-#define SET_TD_DAYS(o, v) ((o)->days = (v))
-#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
+#define SET_TD_DAYS(o, v) ((o)->days = (v))
+#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
* p->hastzinfo.
*/
-#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
+#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
/* M is a char or int claiming to be a valid month. The macro is equivalent
* to the two-sided Python test
- * 1 <= M <= 12
+ * 1 <= M <= 12
*/
#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
@@ -111,7 +111,7 @@ static PyTypeObject PyDateTime_TZInfoType;
* iff (k^i)&(k^j) has sign bit set.
*/
#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
- ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
+ ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
/* Compute Python divmod(x, y), returning the quotient and storing the
* remainder into *r. The quotient is the floor of x/y, and that's
@@ -125,17 +125,17 @@ static PyTypeObject PyDateTime_TZInfoType;
static int
divmod(int x, int y, int *r)
{
- int quo;
+ int quo;
- assert(y > 0);
- quo = x / y;
- *r = x - quo * y;
- if (*r < 0) {
- --quo;
- *r += y;
- }
- assert(0 <= *r && *r < y);
- return quo;
+ assert(y > 0);
+ quo = x / y;
+ *r = x - quo * y;
+ if (*r < 0) {
+ --quo;
+ *r += y;
+ }
+ assert(0 <= *r && *r < y);
+ return quo;
}
/* Round a double to the nearest long. |x| must be small enough to fit
@@ -144,11 +144,11 @@ divmod(int x, int y, int *r)
static long
round_to_long(double x)
{
- if (x >= 0.0)
- x = floor(x + 0.5);
- else
- x = ceil(x - 0.5);
- return (long)x;
+ if (x >= 0.0)
+ x = floor(x + 0.5);
+ else
+ x = ceil(x - 0.5);
+ return (long)x;
}
/* ---------------------------------------------------------------------------
@@ -160,52 +160,52 @@ round_to_long(double x)
* are correct for non-leap years only.
*/
static int _days_in_month[] = {
- 0, /* unused; this vector uses 1-based indexing */
- 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+ 0, /* unused; this vector uses 1-based indexing */
+ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static int _days_before_month[] = {
- 0, /* unused; this vector uses 1-based indexing */
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
+ 0, /* unused; this vector uses 1-based indexing */
+ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
/* year -> 1 if leap year, else 0. */
static int
is_leap(int year)
{
- /* Cast year to unsigned. The result is the same either way, but
- * C can generate faster code for unsigned mod than for signed
- * mod (especially for % 4 -- a good compiler should just grab
- * the last 2 bits when the LHS is unsigned).
- */
- const unsigned int ayear = (unsigned int)year;
- return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
+ /* Cast year to unsigned. The result is the same either way, but
+ * C can generate faster code for unsigned mod than for signed
+ * mod (especially for % 4 -- a good compiler should just grab
+ * the last 2 bits when the LHS is unsigned).
+ */
+ const unsigned int ayear = (unsigned int)year;
+ return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
}
/* year, month -> number of days in that month in that year */
static int
days_in_month(int year, int month)
{
- assert(month >= 1);
- assert(month <= 12);
- if (month == 2 && is_leap(year))
- return 29;
- else
- return _days_in_month[month];
+ assert(month >= 1);
+ assert(month <= 12);
+ if (month == 2 && is_leap(year))
+ return 29;
+ else
+ return _days_in_month[month];
}
/* year, month -> number of days in year preceeding first day of month */
static int
days_before_month(int year, int month)
{
- int days;
+ int days;
- assert(month >= 1);
- assert(month <= 12);
- days = _days_before_month[month];
- if (month > 2 && is_leap(year))
- ++days;
- return days;
+ assert(month >= 1);
+ assert(month <= 12);
+ days = _days_before_month[month];
+ if (month > 2 && is_leap(year))
+ ++days;
+ return days;
}
/* year -> number of days before January 1st of year. Remember that we
@@ -214,124 +214,124 @@ days_before_month(int year, int month)
static int
days_before_year(int year)
{
- int y = year - 1;
- /* This is incorrect if year <= 0; we really want the floor
- * here. But so long as MINYEAR is 1, the smallest year this
- * can see is 0 (this can happen in some normalization endcases),
- * so we'll just special-case that.
- */
- assert (year >= 0);
- if (y >= 0)
- return y*365 + y/4 - y/100 + y/400;
- else {
- assert(y == -1);
- return -366;
- }
+ int y = year - 1;
+ /* This is incorrect if year <= 0; we really want the floor
+ * here. But so long as MINYEAR is 1, the smallest year this
+ * can see is 0 (this can happen in some normalization endcases),
+ * so we'll just special-case that.
+ */
+ assert (year >= 0);
+ if (y >= 0)
+ return y*365 + y/4 - y/100 + y/400;
+ else {
+ assert(y == -1);
+ return -366;
+ }
}
/* Number of days in 4, 100, and 400 year cycles. That these have
* the correct values is asserted in the module init function.
*/
-#define DI4Y 1461 /* days_before_year(5); days in 4 years */
-#define DI100Y 36524 /* days_before_year(101); days in 100 years */
-#define DI400Y 146097 /* days_before_year(401); days in 400 years */
+#define DI4Y 1461 /* days_before_year(5); days in 4 years */
+#define DI100Y 36524 /* days_before_year(101); days in 100 years */
+#define DI400Y 146097 /* days_before_year(401); days in 400 years */
/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
static void
ord_to_ymd(int ordinal, int *year, int *month, int *day)
{
- int n, n1, n4, n100, n400, leapyear, preceding;
-
- /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
- * leap years repeats exactly every 400 years. The basic strategy is
- * to find the closest 400-year boundary at or before ordinal, then
- * work with the offset from that boundary to ordinal. Life is much
- * clearer if we subtract 1 from ordinal first -- then the values
- * of ordinal at 400-year boundaries are exactly those divisible
- * by DI400Y:
- *
- * D M Y n n-1
- * -- --- ---- ---------- ----------------
- * 31 Dec -400 -DI400Y -DI400Y -1
- * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
- * ...
- * 30 Dec 000 -1 -2
- * 31 Dec 000 0 -1
- * 1 Jan 001 1 0 400-year boundary
- * 2 Jan 001 2 1
- * 3 Jan 001 3 2
- * ...
- * 31 Dec 400 DI400Y DI400Y -1
- * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
- */
- assert(ordinal >= 1);
- --ordinal;
- n400 = ordinal / DI400Y;
- n = ordinal % DI400Y;
- *year = n400 * 400 + 1;
-
- /* Now n is the (non-negative) offset, in days, from January 1 of
- * year, to the desired date. Now compute how many 100-year cycles
- * precede n.
- * Note that it's possible for n100 to equal 4! In that case 4 full
- * 100-year cycles precede the desired day, which implies the
- * desired day is December 31 at the end of a 400-year cycle.
- */
- n100 = n / DI100Y;
- n = n % DI100Y;
-
- /* Now compute how many 4-year cycles precede it. */
- n4 = n / DI4Y;
- n = n % DI4Y;
-
- /* And now how many single years. Again n1 can be 4, and again
- * meaning that the desired day is December 31 at the end of the
- * 4-year cycle.
- */
- n1 = n / 365;
- n = n % 365;
-
- *year += n100 * 100 + n4 * 4 + n1;
- if (n1 == 4 || n100 == 4) {
- assert(n == 0);
- *year -= 1;
- *month = 12;
- *day = 31;
- return;
- }
-
- /* Now the year is correct, and n is the offset from January 1. We
- * find the month via an estimate that's either exact or one too
- * large.
- */
- leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
- assert(leapyear == is_leap(*year));
- *month = (n + 50) >> 5;
- preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
- if (preceding > n) {
- /* estimate is too large */
- *month -= 1;
- preceding -= days_in_month(*year, *month);
- }
- n -= preceding;
- assert(0 <= n);
- assert(n < days_in_month(*year, *month));
-
- *day = n + 1;
+ int n, n1, n4, n100, n400, leapyear, preceding;
+
+ /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
+ * leap years repeats exactly every 400 years. The basic strategy is
+ * to find the closest 400-year boundary at or before ordinal, then
+ * work with the offset from that boundary to ordinal. Life is much
+ * clearer if we subtract 1 from ordinal first -- then the values
+ * of ordinal at 400-year boundaries are exactly those divisible
+ * by DI400Y:
+ *
+ * D M Y n n-1
+ * -- --- ---- ---------- ----------------
+ * 31 Dec -400 -DI400Y -DI400Y -1
+ * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
+ * ...
+ * 30 Dec 000 -1 -2
+ * 31 Dec 000 0 -1
+ * 1 Jan 001 1 0 400-year boundary
+ * 2 Jan 001 2 1
+ * 3 Jan 001 3 2
+ * ...
+ * 31 Dec 400 DI400Y DI400Y -1
+ * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
+ */
+ assert(ordinal >= 1);
+ --ordinal;
+ n400 = ordinal / DI400Y;
+ n = ordinal % DI400Y;
+ *year = n400 * 400 + 1;
+
+ /* Now n is the (non-negative) offset, in days, from January 1 of
+ * year, to the desired date. Now compute how many 100-year cycles
+ * precede n.
+ * Note that it's possible for n100 to equal 4! In that case 4 full
+ * 100-year cycles precede the desired day, which implies the
+ * desired day is December 31 at the end of a 400-year cycle.
+ */
+ n100 = n / DI100Y;
+ n = n % DI100Y;
+
+ /* Now compute how many 4-year cycles precede it. */
+ n4 = n / DI4Y;
+ n = n % DI4Y;
+
+ /* And now how many single years. Again n1 can be 4, and again
+ * meaning that the desired day is December 31 at the end of the
+ * 4-year cycle.
+ */
+ n1 = n / 365;
+ n = n % 365;
+
+ *year += n100 * 100 + n4 * 4 + n1;
+ if (n1 == 4 || n100 == 4) {
+ assert(n == 0);
+ *year -= 1;
+ *month = 12;
+ *day = 31;
+ return;
+ }
+
+ /* Now the year is correct, and n is the offset from January 1. We
+ * find the month via an estimate that's either exact or one too
+ * large.
+ */
+ leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
+ assert(leapyear == is_leap(*year));
+ *month = (n + 50) >> 5;
+ preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
+ if (preceding > n) {
+ /* estimate is too large */
+ *month -= 1;
+ preceding -= days_in_month(*year, *month);
+ }
+ n -= preceding;
+ assert(0 <= n);
+ assert(n < days_in_month(*year, *month));
+
+ *day = n + 1;
}
/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
static int
ymd_to_ord(int year, int month, int day)
{
- return days_before_year(year) + days_before_month(year, month) + day;
+ return days_before_year(year) + days_before_month(year, month) + day;
}
/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
static int
weekday(int year, int month, int day)
{
- return (ymd_to_ord(year, month, day) + 6) % 7;
+ return (ymd_to_ord(year, month, day) + 6) % 7;
}
/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
@@ -340,15 +340,15 @@ weekday(int year, int month, int day)
static int
iso_week1_monday(int year)
{
- int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
- /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
- int first_weekday = (first_day + 6) % 7;
- /* ordinal of closest Monday at or before 1/1 */
- int week1_monday = first_day - first_weekday;
+ int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
+ /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
+ int first_weekday = (first_day + 6) % 7;
+ /* ordinal of closest Monday at or before 1/1 */
+ int week1_monday = first_day - first_weekday;
- if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
- week1_monday += 7;
- return week1_monday;
+ if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
+ week1_monday += 7;
+ return week1_monday;
}
/* ---------------------------------------------------------------------------
@@ -361,12 +361,12 @@ iso_week1_monday(int year)
static int
check_delta_day_range(int days)
{
- if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
- return 0;
- PyErr_Format(PyExc_OverflowError,
- "days=%d; must have magnitude <= %d",
- days, MAX_DELTA_DAYS);
- return -1;
+ if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
+ return 0;
+ PyErr_Format(PyExc_OverflowError,
+ "days=%d; must have magnitude <= %d",
+ days, MAX_DELTA_DAYS);
+ return -1;
}
/* Check that date arguments are in range. Return 0 if they are. If they
@@ -376,22 +376,22 @@ static int
check_date_args(int year, int month, int day)
{
- if (year < MINYEAR || year > MAXYEAR) {
- PyErr_SetString(PyExc_ValueError,
- "year is out of range");
- return -1;
- }
- if (month < 1 || month > 12) {
- PyErr_SetString(PyExc_ValueError,
- "month must be in 1..12");
- return -1;
- }
- if (day < 1 || day > days_in_month(year, month)) {
- PyErr_SetString(PyExc_ValueError,
- "day is out of range for month");
- return -1;
- }
- return 0;
+ if (year < MINYEAR || year > MAXYEAR) {
+ PyErr_SetString(PyExc_ValueError,
+ "year is out of range");
+ return -1;
+ }
+ if (month < 1 || month > 12) {
+ PyErr_SetString(PyExc_ValueError,
+ "month must be in 1..12");
+ return -1;
+ }
+ if (day < 1 || day > days_in_month(year, month)) {
+ PyErr_SetString(PyExc_ValueError,
+ "day is out of range for month");
+ return -1;
+ }
+ return 0;
}
/* Check that time arguments are in range. Return 0 if they are. If they
@@ -400,27 +400,27 @@ check_date_args(int year, int month, int day)
static int
check_time_args(int h, int m, int s, int us)
{
- if (h < 0 || h > 23) {
- PyErr_SetString(PyExc_ValueError,
- "hour must be in 0..23");
- return -1;
- }
- if (m < 0 || m > 59) {
- PyErr_SetString(PyExc_ValueError,
- "minute must be in 0..59");
- return -1;
- }
- if (s < 0 || s > 59) {
- PyErr_SetString(PyExc_ValueError,
- "second must be in 0..59");
- return -1;
- }
- if (us < 0 || us > 999999) {
- PyErr_SetString(PyExc_ValueError,
- "microsecond must be in 0..999999");
- return -1;
- }
- return 0;
+ if (h < 0 || h > 23) {
+ PyErr_SetString(PyExc_ValueError,
+ "hour must be in 0..23");
+ return -1;
+ }
+ if (m < 0 || m > 59) {
+ PyErr_SetString(PyExc_ValueError,
+ "minute must be in 0..59");
+ return -1;
+ }
+ if (s < 0 || s > 59) {
+ PyErr_SetString(PyExc_ValueError,
+ "second must be in 0..59");
+ return -1;
+ }
+ if (us < 0 || us > 999999) {
+ PyErr_SetString(PyExc_ValueError,
+ "microsecond must be in 0..999999");
+ return -1;
+ }
+ return 0;
}
/* ---------------------------------------------------------------------------
@@ -436,109 +436,109 @@ check_time_args(int h, int m, int s, int us)
static void
normalize_pair(int *hi, int *lo, int factor)
{
- assert(factor > 0);
- assert(lo != hi);
- if (*lo < 0 || *lo >= factor) {
- const int num_hi = divmod(*lo, factor, lo);
- const int new_hi = *hi + num_hi;
- assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
- *hi = new_hi;
- }
- assert(0 <= *lo && *lo < factor);
+ assert(factor > 0);
+ assert(lo != hi);
+ if (*lo < 0 || *lo >= factor) {
+ const int num_hi = divmod(*lo, factor, lo);
+ const int new_hi = *hi + num_hi;
+ assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
+ *hi = new_hi;
+ }
+ assert(0 <= *lo && *lo < factor);
}
/* Fiddle days (d), seconds (s), and microseconds (us) so that
- * 0 <= *s < 24*3600
- * 0 <= *us < 1000000
+ * 0 <= *s < 24*3600
+ * 0 <= *us < 1000000
* The input values must be such that the internals don't overflow.
* The way this routine is used, we don't get close.
*/
static void
normalize_d_s_us(int *d, int *s, int *us)
{
- if (*us < 0 || *us >= 1000000) {
- normalize_pair(s, us, 1000000);
- /* |s| can't be bigger than about
- * |original s| + |original us|/1000000 now.
- */
+ if (*us < 0 || *us >= 1000000) {
+ normalize_pair(s, us, 1000000);
+ /* |s| can't be bigger than about
+ * |original s| + |original us|/1000000 now.
+ */
- }
- if (*s < 0 || *s >= 24*3600) {
- normalize_pair(d, s, 24*3600);
- /* |d| can't be bigger than about
- * |original d| +
- * (|original s| + |original us|/1000000) / (24*3600) now.
- */
- }
- assert(0 <= *s && *s < 24*3600);
- assert(0 <= *us && *us < 1000000);
+ }
+ if (*s < 0 || *s >= 24*3600) {
+ normalize_pair(d, s, 24*3600);
+ /* |d| can't be bigger than about
+ * |original d| +
+ * (|original s| + |original us|/1000000) / (24*3600) now.
+ */
+ }
+ assert(0 <= *s && *s < 24*3600);
+ assert(0 <= *us && *us < 1000000);
}
/* Fiddle years (y), months (m), and days (d) so that
- * 1 <= *m <= 12
- * 1 <= *d <= days_in_month(*y, *m)
+ * 1 <= *m <= 12
+ * 1 <= *d <= days_in_month(*y, *m)
* The input values must be such that the internals don't overflow.
* The way this routine is used, we don't get close.
*/
static void
normalize_y_m_d(int *y, int *m, int *d)
{
- int dim; /* # of days in month */
-
- /* This gets muddy: the proper range for day can't be determined
- * without knowing the correct month and year, but if day is, e.g.,
- * plus or minus a million, the current month and year values make
- * no sense (and may also be out of bounds themselves).
- * Saying 12 months == 1 year should be non-controversial.
- */
- if (*m < 1 || *m > 12) {
- --*m;
- normalize_pair(y, m, 12);
- ++*m;
- /* |y| can't be bigger than about
- * |original y| + |original m|/12 now.
- */
- }
- assert(1 <= *m && *m <= 12);
-
- /* Now only day can be out of bounds (year may also be out of bounds
- * for a datetime object, but we don't care about that here).
- * If day is out of bounds, what to do is arguable, but at least the
- * method here is principled and explainable.
- */
- dim = days_in_month(*y, *m);
- if (*d < 1 || *d > dim) {
- /* Move day-1 days from the first of the month. First try to
- * get off cheap if we're only one day out of range
- * (adjustments for timezone alone can't be worse than that).
- */
- if (*d == 0) {
- --*m;
- if (*m > 0)
- *d = days_in_month(*y, *m);
- else {
- --*y;
- *m = 12;
- *d = 31;
- }
- }
- else if (*d == dim + 1) {
- /* move forward a day */
- ++*m;
- *d = 1;
- if (*m > 12) {
- *m = 1;
- ++*y;
- }
- }
- else {
- int ordinal = ymd_to_ord(*y, *m, 1) +
- *d - 1;
- ord_to_ymd(ordinal, y, m, d);
- }
- }
- assert(*m > 0);
- assert(*d > 0);
+ int dim; /* # of days in month */
+
+ /* This gets muddy: the proper range for day can't be determined
+ * without knowing the correct month and year, but if day is, e.g.,
+ * plus or minus a million, the current month and year values make
+ * no sense (and may also be out of bounds themselves).
+ * Saying 12 months == 1 year should be non-controversial.
+ */
+ if (*m < 1 || *m > 12) {
+ --*m;
+ normalize_pair(y, m, 12);
+ ++*m;
+ /* |y| can't be bigger than about
+ * |original y| + |original m|/12 now.
+ */
+ }
+ assert(1 <= *m && *m <= 12);
+
+ /* Now only day can be out of bounds (year may also be out of bounds
+ * for a datetime object, but we don't care about that here).
+ * If day is out of bounds, what to do is arguable, but at least the
+ * method here is principled and explainable.
+ */
+ dim = days_in_month(*y, *m);
+ if (*d < 1 || *d > dim) {
+ /* Move day-1 days from the first of the month. First try to
+ * get off cheap if we're only one day out of range
+ * (adjustments for timezone alone can't be worse than that).
+ */
+ if (*d == 0) {
+ --*m;
+ if (*m > 0)
+ *d = days_in_month(*y, *m);
+ else {
+ --*y;
+ *m = 12;
+ *d = 31;
+ }
+ }
+ else if (*d == dim + 1) {
+ /* move forward a day */
+ ++*m;
+ *d = 1;
+ if (*m > 12) {
+ *m = 1;
+ ++*y;
+ }
+ }
+ else {
+ int ordinal = ymd_to_ord(*y, *m, 1) +
+ *d - 1;
+ ord_to_ymd(ordinal, y, m, d);
+ }
+ }
+ assert(*m > 0);
+ assert(*d > 0);
}
/* Fiddle out-of-bounds months and days so that the result makes some kind
@@ -548,17 +548,17 @@ normalize_y_m_d(int *y, int *m, int *d)
static int
normalize_date(int *year, int *month, int *day)
{
- int result;
+ int result;
- normalize_y_m_d(year, month, day);
- if (MINYEAR <= *year && *year <= MAXYEAR)
- result = 0;
- else {
- PyErr_SetString(PyExc_OverflowError,
- "date value out of range");
- result = -1;
- }
- return result;
+ normalize_y_m_d(year, month, day);
+ if (MINYEAR <= *year && *year <= MAXYEAR)
+ result = 0;
+ else {
+ PyErr_SetString(PyExc_OverflowError,
+ "date value out of range");
+ result = -1;
+ }
+ return result;
}
/* Force all the datetime fields into range. The parameters are both
@@ -569,11 +569,11 @@ normalize_datetime(int *year, int *month, int *day,
int *hour, int *minute, int *second,
int *microsecond)
{
- normalize_pair(second, microsecond, 1000000);
- normalize_pair(minute, second, 60);
- normalize_pair(hour, minute, 60);
- normalize_pair(day, hour, 24);
- return normalize_date(year, month, day);
+ normalize_pair(second, microsecond, 1000000);
+ normalize_pair(minute, second, 60);
+ normalize_pair(hour, minute, 60);
+ normalize_pair(day, hour, 24);
+ return normalize_date(year, month, day);
}
/* ---------------------------------------------------------------------------
@@ -600,31 +600,31 @@ normalize_datetime(int *year, int *month, int *day,
static PyObject *
time_alloc(PyTypeObject *type, Py_ssize_t aware)
{
- PyObject *self;
+ PyObject *self;
- self = (PyObject *)
- PyObject_MALLOC(aware ?
- sizeof(PyDateTime_Time) :
- sizeof(_PyDateTime_BaseTime));
- if (self == NULL)
- return (PyObject *)PyErr_NoMemory();
- PyObject_INIT(self, type);
- return self;
+ self = (PyObject *)
+ PyObject_MALLOC(aware ?
+ sizeof(PyDateTime_Time) :
+ sizeof(_PyDateTime_BaseTime));
+ if (self == NULL)
+ return (PyObject *)PyErr_NoMemory();
+ PyObject_INIT(self, type);
+ return self;
}
static PyObject *
datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
{
- PyObject *self;
+ PyObject *self;
- self = (PyObject *)
- PyObject_MALLOC(aware ?
- sizeof(PyDateTime_DateTime) :
- sizeof(_PyDateTime_BaseDateTime));
- if (self == NULL)
- return (PyObject *)PyErr_NoMemory();
- PyObject_INIT(self, type);
- return self;
+ self = (PyObject *)
+ PyObject_MALLOC(aware ?
+ sizeof(PyDateTime_DateTime) :
+ sizeof(_PyDateTime_BaseDateTime));
+ if (self == NULL)
+ return (PyObject *)PyErr_NoMemory();
+ PyObject_INIT(self, type);
+ return self;
}
/* ---------------------------------------------------------------------------
@@ -636,10 +636,10 @@ datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
static void
set_date_fields(PyDateTime_Date *self, int y, int m, int d)
{
- self->hashcode = -1;
- SET_YEAR(self, y);
- SET_MONTH(self, m);
- SET_DAY(self, d);
+ self->hashcode = -1;
+ SET_YEAR(self, y);
+ SET_MONTH(self, m);
+ SET_DAY(self, d);
}
/* ---------------------------------------------------------------------------
@@ -650,71 +650,71 @@ set_date_fields(PyDateTime_Date *self, int y, int m, int d)
static PyObject *
new_date_ex(int year, int month, int day, PyTypeObject *type)
{
- PyDateTime_Date *self;
+ PyDateTime_Date *self;
- self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
- if (self != NULL)
- set_date_fields(self, year, month, day);
- return (PyObject *) self;
+ self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
+ if (self != NULL)
+ set_date_fields(self, year, month, day);
+ return (PyObject *) self;
}
#define new_date(year, month, day) \
- new_date_ex(year, month, day, &PyDateTime_DateType)
+ new_date_ex(year, month, day, &PyDateTime_DateType)
/* Create a datetime instance with no range checking. */
static PyObject *
new_datetime_ex(int year, int month, int day, int hour, int minute,
- int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
-{
- PyDateTime_DateTime *self;
- char aware = tzinfo != Py_None;
-
- self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
- if (self != NULL) {
- self->hastzinfo = aware;
- set_date_fields((PyDateTime_Date *)self, year, month, day);
- DATE_SET_HOUR(self, hour);
- DATE_SET_MINUTE(self, minute);
- DATE_SET_SECOND(self, second);
- DATE_SET_MICROSECOND(self, usecond);
- if (aware) {
- Py_INCREF(tzinfo);
- self->tzinfo = tzinfo;
- }
- }
- return (PyObject *)self;
-}
-
-#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
- new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
- &PyDateTime_DateTimeType)
+ int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
+{
+ PyDateTime_DateTime *self;
+ char aware = tzinfo != Py_None;
+
+ self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
+ if (self != NULL) {
+ self->hastzinfo = aware;
+ set_date_fields((PyDateTime_Date *)self, year, month, day);
+ DATE_SET_HOUR(self, hour);
+ DATE_SET_MINUTE(self, minute);
+ DATE_SET_SECOND(self, second);
+ DATE_SET_MICROSECOND(self, usecond);
+ if (aware) {
+ Py_INCREF(tzinfo);
+ self->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)self;
+}
+
+#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
+ new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
+ &PyDateTime_DateTimeType)
/* Create a time instance with no range checking. */
static PyObject *
new_time_ex(int hour, int minute, int second, int usecond,
- PyObject *tzinfo, PyTypeObject *type)
-{
- PyDateTime_Time *self;
- char aware = tzinfo != Py_None;
-
- self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
- if (self != NULL) {
- self->hastzinfo = aware;
- self->hashcode = -1;
- TIME_SET_HOUR(self, hour);
- TIME_SET_MINUTE(self, minute);
- TIME_SET_SECOND(self, second);
- TIME_SET_MICROSECOND(self, usecond);
- if (aware) {
- Py_INCREF(tzinfo);
- self->tzinfo = tzinfo;
- }
- }
- return (PyObject *)self;
-}
-
-#define new_time(hh, mm, ss, us, tzinfo) \
- new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
+ PyObject *tzinfo, PyTypeObject *type)
+{
+ PyDateTime_Time *self;
+ char aware = tzinfo != Py_None;
+
+ self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
+ if (self != NULL) {
+ self->hastzinfo = aware;
+ self->hashcode = -1;
+ TIME_SET_HOUR(self, hour);
+ TIME_SET_MINUTE(self, minute);
+ TIME_SET_SECOND(self, second);
+ TIME_SET_MICROSECOND(self, usecond);
+ if (aware) {
+ Py_INCREF(tzinfo);
+ self->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)self;
+}
+
+#define new_time(hh, mm, ss, us, tzinfo) \
+ new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
/* Create a timedelta instance. Normalize the members iff normalize is
* true. Passing false is a speed optimization, if you know for sure
@@ -724,30 +724,30 @@ new_time_ex(int hour, int minute, int second, int usecond,
*/
static PyObject *
new_delta_ex(int days, int seconds, int microseconds, int normalize,
- PyTypeObject *type)
+ PyTypeObject *type)
{
- PyDateTime_Delta *self;
+ PyDateTime_Delta *self;
- if (normalize)
- normalize_d_s_us(&days, &seconds, &microseconds);
- assert(0 <= seconds && seconds < 24*3600);
- assert(0 <= microseconds && microseconds < 1000000);
+ if (normalize)
+ normalize_d_s_us(&days, &seconds, &microseconds);
+ assert(0 <= seconds && seconds < 24*3600);
+ assert(0 <= microseconds && microseconds < 1000000);
- if (check_delta_day_range(days) < 0)
- return NULL;
+ if (check_delta_day_range(days) < 0)
+ return NULL;
- self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
- if (self != NULL) {
- self->hashcode = -1;
- SET_TD_DAYS(self, days);
- SET_TD_SECONDS(self, seconds);
- SET_TD_MICROSECONDS(self, microseconds);
- }
- return (PyObject *) self;
+ self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
+ if (self != NULL) {
+ self->hashcode = -1;
+ SET_TD_DAYS(self, days);
+ SET_TD_SECONDS(self, seconds);
+ SET_TD_MICROSECONDS(self, microseconds);
+ }
+ return (PyObject *) self;
}
-#define new_delta(d, s, us, normalize) \
- new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
+#define new_delta(d, s, us, normalize) \
+ new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
/* ---------------------------------------------------------------------------
* tzinfo helpers.
@@ -759,13 +759,13 @@ new_delta_ex(int days, int seconds, int microseconds, int normalize,
static int
check_tzinfo_subclass(PyObject *p)
{
- if (p == Py_None || PyTZInfo_Check(p))
- return 0;
- PyErr_Format(PyExc_TypeError,
- "tzinfo argument must be None or of a tzinfo subclass, "
- "not type '%s'",
- Py_TYPE(p)->tp_name);
- return -1;
+ if (p == Py_None || PyTZInfo_Check(p))
+ return 0;
+ PyErr_Format(PyExc_TypeError,
+ "tzinfo argument must be None or of a tzinfo subclass, "
+ "not type '%s'",
+ Py_TYPE(p)->tp_name);
+ return -1;
}
/* Return tzinfo.methname(tzinfoarg), without any checking of results.
@@ -774,17 +774,17 @@ check_tzinfo_subclass(PyObject *p)
static PyObject *
call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
{
- PyObject *result;
+ PyObject *result;
- assert(tzinfo && methname && tzinfoarg);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
- return result;
+ assert(tzinfo && methname && tzinfoarg);
+ assert(check_tzinfo_subclass(tzinfo) >= 0);
+ if (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
+ return result;
}
/* If self has a tzinfo member, return a BORROWED reference to it. Else
@@ -794,14 +794,14 @@ call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
static PyObject *
get_tzinfo_member(PyObject *self)
{
- PyObject *tzinfo = NULL;
+ PyObject *tzinfo = NULL;
- if (PyDateTime_Check(self) && HASTZINFO(self))
- tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
- else if (PyTime_Check(self) && HASTZINFO(self))
- tzinfo = ((PyDateTime_Time *)self)->tzinfo;
+ if (PyDateTime_Check(self) && HASTZINFO(self))
+ tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
+ else if (PyTime_Check(self) && HASTZINFO(self))
+ tzinfo = ((PyDateTime_Time *)self)->tzinfo;
- return tzinfo;
+ return tzinfo;
}
/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
@@ -814,59 +814,59 @@ get_tzinfo_member(PyObject *self)
*/
static int
call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
- int *none)
-{
- PyObject *u;
- int result = -1;
-
- assert(tzinfo != NULL);
- assert(PyTZInfo_Check(tzinfo));
- assert(tzinfoarg != NULL);
-
- *none = 0;
- u = call_tzinfo_method(tzinfo, name, tzinfoarg);
- if (u == NULL)
- return -1;
-
- else if (u == Py_None) {
- result = 0;
- *none = 1;
- }
- else if (PyDelta_Check(u)) {
- const int days = GET_TD_DAYS(u);
- if (days < -1 || days > 0)
- result = 24*60; /* trigger ValueError below */
- else {
- /* next line can't overflow because we know days
- * is -1 or 0 now
- */
- int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
- result = divmod(ss, 60, &ss);
- if (ss || GET_TD_MICROSECONDS(u)) {
- PyErr_Format(PyExc_ValueError,
- "tzinfo.%s() must return a "
- "whole number of minutes",
- name);
- result = -1;
- }
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "tzinfo.%s() must return None or "
- "timedelta, not '%s'",
- name, Py_TYPE(u)->tp_name);
- }
-
- Py_DECREF(u);
- if (result < -1439 || result > 1439) {
- PyErr_Format(PyExc_ValueError,
- "tzinfo.%s() returned %d; must be in "
- "-1439 .. 1439",
- name, result);
- result = -1;
- }
- return result;
+ int *none)
+{
+ PyObject *u;
+ int result = -1;
+
+ assert(tzinfo != NULL);
+ assert(PyTZInfo_Check(tzinfo));
+ assert(tzinfoarg != NULL);
+
+ *none = 0;
+ u = call_tzinfo_method(tzinfo, name, tzinfoarg);
+ if (u == NULL)
+ return -1;
+
+ else if (u == Py_None) {
+ result = 0;
+ *none = 1;
+ }
+ else if (PyDelta_Check(u)) {
+ const int days = GET_TD_DAYS(u);
+ if (days < -1 || days > 0)
+ result = 24*60; /* trigger ValueError below */
+ else {
+ /* next line can't overflow because we know days
+ * is -1 or 0 now
+ */
+ int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
+ result = divmod(ss, 60, &ss);
+ if (ss || GET_TD_MICROSECONDS(u)) {
+ PyErr_Format(PyExc_ValueError,
+ "tzinfo.%s() must return a "
+ "whole number of minutes",
+ name);
+ result = -1;
+ }
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "tzinfo.%s() must return None or "
+ "timedelta, not '%s'",
+ name, Py_TYPE(u)->tp_name);
+ }
+
+ Py_DECREF(u);
+ if (result < -1439 || result > 1439) {
+ PyErr_Format(PyExc_ValueError,
+ "tzinfo.%s() returned %d; must be in "
+ "-1439 .. 1439",
+ name, result);
+ result = -1;
+ }
+ return result;
}
/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
@@ -880,34 +880,34 @@ call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
static int
call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
{
- return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
+ return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
}
/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
*/
static PyObject *
offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
- PyObject *result;
-
- assert(tzinfo && name && tzinfoarg);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else {
- int none;
- int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
- &none);
- if (offset < 0 && PyErr_Occurred())
- return NULL;
- if (none) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = new_delta(0, offset * 60, 0, 1);
- }
- return result;
+ PyObject *result;
+
+ assert(tzinfo && name && tzinfoarg);
+ if (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else {
+ int none;
+ int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
+ &none);
+ if (offset < 0 && PyErr_Occurred())
+ return NULL;
+ if (none) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = new_delta(0, offset * 60, 0, 1);
+ }
+ return result;
}
/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
@@ -921,7 +921,7 @@ offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
static int
call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
{
- return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
+ return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
}
/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
@@ -933,55 +933,55 @@ call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
static PyObject *
call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
{
- PyObject *result;
-
- assert(tzinfo != NULL);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- assert(tzinfoarg != NULL);
-
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
-
- if (result != NULL && result != Py_None) {
- if (!PyUnicode_Check(result)) {
- PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
- "return None or a string, not '%s'",
- Py_TYPE(result)->tp_name);
- Py_DECREF(result);
- result = NULL;
- }
- else if (!PyUnicode_Check(result)) {
- PyObject *temp = PyUnicode_FromObject(result);
- Py_DECREF(result);
- result = temp;
- }
- }
- return result;
+ PyObject *result;
+
+ assert(tzinfo != NULL);
+ assert(check_tzinfo_subclass(tzinfo) >= 0);
+ assert(tzinfoarg != NULL);
+
+ if (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
+
+ if (result != NULL && result != Py_None) {
+ if (!PyUnicode_Check(result)) {
+ PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
+ "return None or a string, not '%s'",
+ Py_TYPE(result)->tp_name);
+ Py_DECREF(result);
+ result = NULL;
+ }
+ else if (!PyUnicode_Check(result)) {
+ PyObject *temp = PyUnicode_FromObject(result);
+ Py_DECREF(result);
+ result = temp;
+ }
+ }
+ return result;
}
typedef enum {
- /* an exception has been set; the caller should pass it on */
- OFFSET_ERROR,
-
- /* type isn't date, datetime, or time subclass */
- OFFSET_UNKNOWN,
-
- /* date,
- * datetime with !hastzinfo
- * datetime with None tzinfo,
- * datetime where utcoffset() returns None
- * time with !hastzinfo
- * time with None tzinfo,
- * time where utcoffset() returns None
- */
- OFFSET_NAIVE,
-
- /* time or datetime where utcoffset() doesn't return None */
- OFFSET_AWARE
+ /* an exception has been set; the caller should pass it on */
+ OFFSET_ERROR,
+
+ /* type isn't date, datetime, or time subclass */
+ OFFSET_UNKNOWN,
+
+ /* date,
+ * datetime with !hastzinfo
+ * datetime with None tzinfo,
+ * datetime where utcoffset() returns None
+ * time with !hastzinfo
+ * time with None tzinfo,
+ * time where utcoffset() returns None
+ */
+ OFFSET_NAIVE,
+
+ /* time or datetime where utcoffset() doesn't return None */
+ OFFSET_AWARE
} naivety;
/* Classify an object as to whether it's naive or offset-aware. See
@@ -993,23 +993,23 @@ typedef enum {
static naivety
classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
{
- int none;
- PyObject *tzinfo;
-
- assert(tzinfoarg != NULL);
- *offset = 0;
- tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
- if (tzinfo == Py_None)
- return OFFSET_NAIVE;
- if (tzinfo == NULL) {
- /* note that a datetime passes the PyDate_Check test */
- return (PyTime_Check(op) || PyDate_Check(op)) ?
- OFFSET_NAIVE : OFFSET_UNKNOWN;
- }
- *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
- if (*offset == -1 && PyErr_Occurred())
- return OFFSET_ERROR;
- return none ? OFFSET_NAIVE : OFFSET_AWARE;
+ int none;
+ PyObject *tzinfo;
+
+ assert(tzinfoarg != NULL);
+ *offset = 0;
+ tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
+ if (tzinfo == Py_None)
+ return OFFSET_NAIVE;
+ if (tzinfo == NULL) {
+ /* note that a datetime passes the PyDate_Check test */
+ return (PyTime_Check(op) || PyDate_Check(op)) ?
+ OFFSET_NAIVE : OFFSET_UNKNOWN;
+ }
+ *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
+ if (*offset == -1 && PyErr_Occurred())
+ return OFFSET_ERROR;
+ return none ? OFFSET_NAIVE : OFFSET_AWARE;
}
/* Classify two objects as to whether they're naive or offset-aware.
@@ -1023,23 +1023,23 @@ classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
*/
static int
classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
- PyObject *tzinfoarg1,
- PyObject *o2, int *offset2, naivety *n2,
- PyObject *tzinfoarg2)
-{
- if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
- *offset1 = *offset2 = 0;
- *n1 = *n2 = OFFSET_NAIVE;
- }
- else {
- *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
- if (*n1 == OFFSET_ERROR)
- return -1;
- *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
- if (*n2 == OFFSET_ERROR)
- return -1;
- }
- return 0;
+ PyObject *tzinfoarg1,
+ PyObject *o2, int *offset2, naivety *n2,
+ PyObject *tzinfoarg2)
+{
+ if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
+ *offset1 = *offset2 = 0;
+ *n1 = *n2 = OFFSET_NAIVE;
+ }
+ else {
+ *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
+ if (*n1 == OFFSET_ERROR)
+ return -1;
+ *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
+ if (*n2 == OFFSET_ERROR)
+ return -1;
+ }
+ return 0;
}
/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
@@ -1050,22 +1050,22 @@ classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
static PyObject *
append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
{
- PyObject *temp;
+ PyObject *temp;
- assert(PyUnicode_Check(repr));
- assert(tzinfo);
- if (tzinfo == Py_None)
- return repr;
- /* Get rid of the trailing ')'. */
- assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
- temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
- PyUnicode_GET_SIZE(repr) - 1);
- Py_DECREF(repr);
- if (temp == NULL)
- return NULL;
- repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
- Py_DECREF(temp);
- return repr;
+ assert(PyUnicode_Check(repr));
+ assert(tzinfo);
+ if (tzinfo == Py_None)
+ return repr;
+ /* Get rid of the trailing ')'. */
+ assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
+ temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
+ PyUnicode_GET_SIZE(repr) - 1);
+ Py_DECREF(repr);
+ if (temp == NULL)
+ return NULL;
+ repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
+ Py_DECREF(temp);
+ return repr;
}
/* ---------------------------------------------------------------------------
@@ -1075,20 +1075,20 @@ append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
static PyObject *
format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
{
- static const char *DayNames[] = {
- "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
- };
- static const char *MonthNames[] = {
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
- };
+ static const char *DayNames[] = {
+ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
+ };
+ static const char *MonthNames[] = {
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+ };
- int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
+ int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
- return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
- DayNames[wday], MonthNames[GET_MONTH(date)-1],
- GET_DAY(date), hours, minutes, seconds,
- GET_YEAR(date));
+ return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
+ DayNames[wday], MonthNames[GET_MONTH(date)-1],
+ GET_DAY(date), hours, minutes, seconds,
+ GET_YEAR(date));
}
/* Add an hours & minutes UTC offset string to buf. buf has no more than
@@ -1103,87 +1103,87 @@ format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
*/
static int
format_utcoffset(char *buf, size_t buflen, const char *sep,
- PyObject *tzinfo, PyObject *tzinfoarg)
-{
- int offset;
- int hours;
- int minutes;
- char sign;
- int none;
-
- assert(buflen >= 1);
-
- offset = call_utcoffset(tzinfo, tzinfoarg, &none);
- if (offset == -1 && PyErr_Occurred())
- return -1;
- if (none) {
- *buf = '\0';
- return 0;
- }
- sign = '+';
- if (offset < 0) {
- sign = '-';
- offset = - offset;
- }
- hours = divmod(offset, 60, &minutes);
- PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
- return 0;
+ PyObject *tzinfo, PyObject *tzinfoarg)
+{
+ int offset;
+ int hours;
+ int minutes;
+ char sign;
+ int none;
+
+ assert(buflen >= 1);
+
+ offset = call_utcoffset(tzinfo, tzinfoarg, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return -1;
+ if (none) {
+ *buf = '\0';
+ return 0;
+ }
+ sign = '+';
+ if (offset < 0) {
+ sign = '-';
+ offset = - offset;
+ }
+ hours = divmod(offset, 60, &minutes);
+ PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
+ return 0;
}
static PyObject *
make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
{
- PyObject *temp;
- PyObject *tzinfo = get_tzinfo_member(object);
- PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
- if (Zreplacement == NULL)
- return NULL;
- if (tzinfo == Py_None || tzinfo == NULL)
- return Zreplacement;
-
- assert(tzinfoarg != NULL);
- temp = call_tzname(tzinfo, tzinfoarg);
- if (temp == NULL)
- goto Error;
- if (temp == Py_None) {
- Py_DECREF(temp);
- return Zreplacement;
- }
-
- assert(PyUnicode_Check(temp));
- /* Since the tzname is getting stuffed into the
- * format, we have to double any % signs so that
- * strftime doesn't treat them as format codes.
- */
- Py_DECREF(Zreplacement);
- Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
- Py_DECREF(temp);
- if (Zreplacement == NULL)
- return NULL;
- if (!PyUnicode_Check(Zreplacement)) {
- PyErr_SetString(PyExc_TypeError,
- "tzname.replace() did not return a string");
- goto Error;
- }
- return Zreplacement;
+ PyObject *temp;
+ PyObject *tzinfo = get_tzinfo_member(object);
+ PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
+ if (Zreplacement == NULL)
+ return NULL;
+ if (tzinfo == Py_None || tzinfo == NULL)
+ return Zreplacement;
+
+ assert(tzinfoarg != NULL);
+ temp = call_tzname(tzinfo, tzinfoarg);
+ if (temp == NULL)
+ goto Error;
+ if (temp == Py_None) {
+ Py_DECREF(temp);
+ return Zreplacement;
+ }
+
+ assert(PyUnicode_Check(temp));
+ /* Since the tzname is getting stuffed into the
+ * format, we have to double any % signs so that
+ * strftime doesn't treat them as format codes.
+ */
+ Py_DECREF(Zreplacement);
+ Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
+ Py_DECREF(temp);
+ if (Zreplacement == NULL)
+ return NULL;
+ if (!PyUnicode_Check(Zreplacement)) {
+ PyErr_SetString(PyExc_TypeError,
+ "tzname.replace() did not return a string");
+ goto Error;
+ }
+ return Zreplacement;
Error:
- Py_DECREF(Zreplacement);
- return NULL;
+ Py_DECREF(Zreplacement);
+ return NULL;
}
static PyObject *
make_freplacement(PyObject *object)
{
- char freplacement[64];
- if (PyTime_Check(object))
- sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
- else if (PyDateTime_Check(object))
- sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
- else
- sprintf(freplacement, "%06d", 0);
+ char freplacement[64];
+ if (PyTime_Check(object))
+ sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
+ else if (PyDateTime_Check(object))
+ sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
+ else
+ sprintf(freplacement, "%06d", 0);
- return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
+ return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
}
/* I sure don't want to reproduce the strftime code from the time module,
@@ -1195,190 +1195,190 @@ make_freplacement(PyObject *object)
*/
static PyObject *
wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
- PyObject *tzinfoarg)
-{
- PyObject *result = NULL; /* guilty until proved innocent */
-
- PyObject *zreplacement = NULL; /* py string, replacement for %z */
- PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
- PyObject *freplacement = NULL; /* py string, replacement for %f */
-
- const char *pin; /* pointer to next char in input format */
- Py_ssize_t flen; /* length of input format */
- char ch; /* next char in input format */
-
- PyObject *newfmt = NULL; /* py string, the output format */
- char *pnew; /* pointer to available byte in output format */
- size_t totalnew; /* number bytes total in output format buffer,
- exclusive of trailing \0 */
- size_t usednew; /* number bytes used so far in output format buffer */
-
- const char *ptoappend; /* ptr to string to append to output buffer */
- Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
-
- assert(object && format && timetuple);
- assert(PyUnicode_Check(format));
- /* Convert the input format to a C string and size */
- pin = _PyUnicode_AsStringAndSize(format, &flen);
- if (!pin)
- return NULL;
-
- /* Give up if the year is before 1900.
- * Python strftime() plays games with the year, and different
- * games depending on whether envar PYTHON2K is set. This makes
- * years before 1900 a nightmare, even if the platform strftime
- * supports them (and not all do).
- * We could get a lot farther here by avoiding Python's strftime
- * wrapper and calling the C strftime() directly, but that isn't
- * an option in the Python implementation of this module.
- */
- {
- long year;
- PyObject *pyyear = PySequence_GetItem(timetuple, 0);
- if (pyyear == NULL) return NULL;
- assert(PyLong_Check(pyyear));
- year = PyLong_AsLong(pyyear);
- Py_DECREF(pyyear);
- if (year < 1900) {
- PyErr_Format(PyExc_ValueError, "year=%ld is before "
- "1900; the datetime strftime() "
- "methods require year >= 1900",
- year);
- return NULL;
- }
- }
-
- /* Scan the input format, looking for %z/%Z/%f escapes, building
- * a new format. Since computing the replacements for those codes
- * is expensive, don't unless they're actually used.
- */
- if (flen > INT_MAX - 1) {
- PyErr_NoMemory();
- goto Done;
- }
-
- totalnew = flen + 1; /* realistic if no %z/%Z */
- newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
- if (newfmt == NULL) goto Done;
- pnew = PyBytes_AsString(newfmt);
- usednew = 0;
-
- while ((ch = *pin++) != '\0') {
- if (ch != '%') {
- ptoappend = pin - 1;
- ntoappend = 1;
- }
- else if ((ch = *pin++) == '\0') {
- /* There's a lone trailing %; doesn't make sense. */
- PyErr_SetString(PyExc_ValueError, "strftime format "
- "ends with raw %");
- goto Done;
- }
- /* A % has been seen and ch is the character after it. */
- else if (ch == 'z') {
- if (zreplacement == NULL) {
- /* format utcoffset */
- char buf[100];
- PyObject *tzinfo = get_tzinfo_member(object);
- zreplacement = PyBytes_FromStringAndSize("", 0);
- if (zreplacement == NULL) goto Done;
- if (tzinfo != Py_None && tzinfo != NULL) {
- assert(tzinfoarg != NULL);
- if (format_utcoffset(buf,
- sizeof(buf),
- "",
- tzinfo,
- tzinfoarg) < 0)
- goto Done;
- Py_DECREF(zreplacement);
- zreplacement =
- PyBytes_FromStringAndSize(buf,
- strlen(buf));
- if (zreplacement == NULL)
- goto Done;
- }
- }
- assert(zreplacement != NULL);
- ptoappend = PyBytes_AS_STRING(zreplacement);
- ntoappend = PyBytes_GET_SIZE(zreplacement);
- }
- else if (ch == 'Z') {
- /* format tzname */
- if (Zreplacement == NULL) {
- Zreplacement = make_Zreplacement(object,
- tzinfoarg);
- if (Zreplacement == NULL)
- goto Done;
- }
- assert(Zreplacement != NULL);
- assert(PyUnicode_Check(Zreplacement));
- ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
- &ntoappend);
- ntoappend = Py_SIZE(Zreplacement);
- }
- else if (ch == 'f') {
- /* format microseconds */
- if (freplacement == NULL) {
- freplacement = make_freplacement(object);
- if (freplacement == NULL)
- goto Done;
- }
- assert(freplacement != NULL);
- assert(PyBytes_Check(freplacement));
- ptoappend = PyBytes_AS_STRING(freplacement);
- ntoappend = PyBytes_GET_SIZE(freplacement);
- }
- else {
- /* percent followed by neither z nor Z */
- ptoappend = pin - 2;
- ntoappend = 2;
- }
-
- /* Append the ntoappend chars starting at ptoappend to
- * the new format.
- */
- if (ntoappend == 0)
- continue;
- assert(ptoappend != NULL);
- assert(ntoappend > 0);
- while (usednew + ntoappend > totalnew) {
- size_t bigger = totalnew << 1;
- if ((bigger >> 1) != totalnew) { /* overflow */
- PyErr_NoMemory();
- goto Done;
- }
- if (_PyBytes_Resize(&newfmt, bigger) < 0)
- goto Done;
- totalnew = bigger;
- pnew = PyBytes_AsString(newfmt) + usednew;
- }
- memcpy(pnew, ptoappend, ntoappend);
- pnew += ntoappend;
- usednew += ntoappend;
- assert(usednew <= totalnew);
- } /* end while() */
-
- if (_PyBytes_Resize(&newfmt, usednew) < 0)
- goto Done;
- {
- PyObject *format;
- PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time == NULL)
- goto Done;
- format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
- if (format != NULL) {
- result = PyObject_CallMethod(time, "strftime", "OO",
- format, timetuple);
- Py_DECREF(format);
- }
- Py_DECREF(time);
- }
+ PyObject *tzinfoarg)
+{
+ PyObject *result = NULL; /* guilty until proved innocent */
+
+ PyObject *zreplacement = NULL; /* py string, replacement for %z */
+ PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
+ PyObject *freplacement = NULL; /* py string, replacement for %f */
+
+ const char *pin; /* pointer to next char in input format */
+ Py_ssize_t flen; /* length of input format */
+ char ch; /* next char in input format */
+
+ PyObject *newfmt = NULL; /* py string, the output format */
+ char *pnew; /* pointer to available byte in output format */
+ size_t totalnew; /* number bytes total in output format buffer,
+ exclusive of trailing \0 */
+ size_t usednew; /* number bytes used so far in output format buffer */
+
+ const char *ptoappend; /* ptr to string to append to output buffer */
+ Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
+
+ assert(object && format && timetuple);
+ assert(PyUnicode_Check(format));
+ /* Convert the input format to a C string and size */
+ pin = _PyUnicode_AsStringAndSize(format, &flen);
+ if (!pin)
+ return NULL;
+
+ /* Give up if the year is before 1900.
+ * Python strftime() plays games with the year, and different
+ * games depending on whether envar PYTHON2K is set. This makes
+ * years before 1900 a nightmare, even if the platform strftime
+ * supports them (and not all do).
+ * We could get a lot farther here by avoiding Python's strftime
+ * wrapper and calling the C strftime() directly, but that isn't
+ * an option in the Python implementation of this module.
+ */
+ {
+ long year;
+ PyObject *pyyear = PySequence_GetItem(timetuple, 0);
+ if (pyyear == NULL) return NULL;
+ assert(PyLong_Check(pyyear));
+ year = PyLong_AsLong(pyyear);
+ Py_DECREF(pyyear);
+ if (year < 1900) {
+ PyErr_Format(PyExc_ValueError, "year=%ld is before "
+ "1900; the datetime strftime() "
+ "methods require year >= 1900",
+ year);
+ return NULL;
+ }
+ }
+
+ /* Scan the input format, looking for %z/%Z/%f escapes, building
+ * a new format. Since computing the replacements for those codes
+ * is expensive, don't unless they're actually used.
+ */
+ if (flen > INT_MAX - 1) {
+ PyErr_NoMemory();
+ goto Done;
+ }
+
+ totalnew = flen + 1; /* realistic if no %z/%Z */
+ newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
+ if (newfmt == NULL) goto Done;
+ pnew = PyBytes_AsString(newfmt);
+ usednew = 0;
+
+ while ((ch = *pin++) != '\0') {
+ if (ch != '%') {
+ ptoappend = pin - 1;
+ ntoappend = 1;
+ }
+ else if ((ch = *pin++) == '\0') {
+ /* There's a lone trailing %; doesn't make sense. */
+ PyErr_SetString(PyExc_ValueError, "strftime format "
+ "ends with raw %");
+ goto Done;
+ }
+ /* A % has been seen and ch is the character after it. */
+ else if (ch == 'z') {
+ if (zreplacement == NULL) {
+ /* format utcoffset */
+ char buf[100];
+ PyObject *tzinfo = get_tzinfo_member(object);
+ zreplacement = PyBytes_FromStringAndSize("", 0);
+ if (zreplacement == NULL) goto Done;
+ if (tzinfo != Py_None && tzinfo != NULL) {
+ assert(tzinfoarg != NULL);
+ if (format_utcoffset(buf,
+ sizeof(buf),
+ "",
+ tzinfo,
+ tzinfoarg) < 0)
+ goto Done;
+ Py_DECREF(zreplacement);
+ zreplacement =
+ PyBytes_FromStringAndSize(buf,
+ strlen(buf));
+ if (zreplacement == NULL)
+ goto Done;
+ }
+ }
+ assert(zreplacement != NULL);
+ ptoappend = PyBytes_AS_STRING(zreplacement);
+ ntoappend = PyBytes_GET_SIZE(zreplacement);
+ }
+ else if (ch == 'Z') {
+ /* format tzname */
+ if (Zreplacement == NULL) {
+ Zreplacement = make_Zreplacement(object,
+ tzinfoarg);
+ if (Zreplacement == NULL)
+ goto Done;
+ }
+ assert(Zreplacement != NULL);
+ assert(PyUnicode_Check(Zreplacement));
+ ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
+ &ntoappend);
+ ntoappend = Py_SIZE(Zreplacement);
+ }
+ else if (ch == 'f') {
+ /* format microseconds */
+ if (freplacement == NULL) {
+ freplacement = make_freplacement(object);
+ if (freplacement == NULL)
+ goto Done;
+ }
+ assert(freplacement != NULL);
+ assert(PyBytes_Check(freplacement));
+ ptoappend = PyBytes_AS_STRING(freplacement);
+ ntoappend = PyBytes_GET_SIZE(freplacement);
+ }
+ else {
+ /* percent followed by neither z nor Z */
+ ptoappend = pin - 2;
+ ntoappend = 2;
+ }
+
+ /* Append the ntoappend chars starting at ptoappend to
+ * the new format.
+ */
+ if (ntoappend == 0)
+ continue;
+ assert(ptoappend != NULL);
+ assert(ntoappend > 0);
+ while (usednew + ntoappend > totalnew) {
+ size_t bigger = totalnew << 1;
+ if ((bigger >> 1) != totalnew) { /* overflow */
+ PyErr_NoMemory();
+ goto Done;
+ }
+ if (_PyBytes_Resize(&newfmt, bigger) < 0)
+ goto Done;
+ totalnew = bigger;
+ pnew = PyBytes_AsString(newfmt) + usednew;
+ }
+ memcpy(pnew, ptoappend, ntoappend);
+ pnew += ntoappend;
+ usednew += ntoappend;
+ assert(usednew <= totalnew);
+ } /* end while() */
+
+ if (_PyBytes_Resize(&newfmt, usednew) < 0)
+ goto Done;
+ {
+ PyObject *format;
+ PyObject *time = PyImport_ImportModuleNoBlock("time");
+ if (time == NULL)
+ goto Done;
+ format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
+ if (format != NULL) {
+ result = PyObject_CallMethod(time, "strftime", "OO",
+ format, timetuple);
+ Py_DECREF(format);
+ }
+ Py_DECREF(time);
+ }
Done:
- Py_XDECREF(freplacement);
- Py_XDECREF(zreplacement);
- Py_XDECREF(Zreplacement);
- Py_XDECREF(newfmt);
- return result;
+ Py_XDECREF(freplacement);
+ Py_XDECREF(zreplacement);
+ Py_XDECREF(Zreplacement);
+ Py_XDECREF(newfmt);
+ return result;
}
/* ---------------------------------------------------------------------------
@@ -1390,14 +1390,14 @@ wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
static PyObject *
time_time(void)
{
- PyObject *result = NULL;
- PyObject *time = PyImport_ImportModuleNoBlock("time");
+ PyObject *result = NULL;
+ PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time != NULL) {
- result = PyObject_CallMethod(time, "time", "()");
- Py_DECREF(time);
- }
- return result;
+ if (time != NULL) {
+ result = PyObject_CallMethod(time, "time", "()");
+ Py_DECREF(time);
+ }
+ return result;
}
/* Build a time.struct_time. The weekday and day number are automatically
@@ -1406,21 +1406,21 @@ time_time(void)
static PyObject *
build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
{
- PyObject *time;
- PyObject *result = NULL;
+ PyObject *time;
+ PyObject *result = NULL;
- time = PyImport_ImportModuleNoBlock("time");
- if (time != NULL) {
- result = PyObject_CallMethod(time, "struct_time",
- "((iiiiiiiii))",
- y, m, d,
- hh, mm, ss,
- weekday(y, m, d),
- days_before_month(y, m) + d,
- dstflag);
- Py_DECREF(time);
- }
- return result;
+ time = PyImport_ImportModuleNoBlock("time");
+ if (time != NULL) {
+ result = PyObject_CallMethod(time, "struct_time",
+ "((iiiiiiiii))",
+ y, m, d,
+ hh, mm, ss,
+ weekday(y, m, d),
+ days_before_month(y, m) + d,
+ dstflag);
+ Py_DECREF(time);
+ }
+ return result;
}
/* ---------------------------------------------------------------------------
@@ -1434,33 +1434,33 @@ build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
static PyObject *
diff_to_bool(int diff, int op)
{
- PyObject *result;
- int istrue;
-
- switch (op) {
- case Py_EQ: istrue = diff == 0; break;
- case Py_NE: istrue = diff != 0; break;
- case Py_LE: istrue = diff <= 0; break;
- case Py_GE: istrue = diff >= 0; break;
- case Py_LT: istrue = diff < 0; break;
- case Py_GT: istrue = diff > 0; break;
- default:
- assert(! "op unknown");
- istrue = 0; /* To shut up compiler */
- }
- result = istrue ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
+ PyObject *result;
+ int istrue;
+
+ switch (op) {
+ case Py_EQ: istrue = diff == 0; break;
+ case Py_NE: istrue = diff != 0; break;
+ case Py_LE: istrue = diff <= 0; break;
+ case Py_GE: istrue = diff >= 0; break;
+ case Py_LT: istrue = diff < 0; break;
+ case Py_GT: istrue = diff > 0; break;
+ default:
+ assert(! "op unknown");
+ istrue = 0; /* To shut up compiler */
+ }
+ result = istrue ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
}
/* Raises a "can't compare" TypeError and returns NULL. */
static PyObject *
cmperror(PyObject *a, PyObject *b)
{
- PyErr_Format(PyExc_TypeError,
- "can't compare %s to %s",
- Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "can't compare %s to %s",
+ Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
+ return NULL;
}
/* ---------------------------------------------------------------------------
@@ -1468,13 +1468,13 @@ cmperror(PyObject *a, PyObject *b)
*/
/* Conversion factors. */
-static PyObject *us_per_us = NULL; /* 1 */
-static PyObject *us_per_ms = NULL; /* 1000 */
-static PyObject *us_per_second = NULL; /* 1000000 */
-static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
-static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
-static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
-static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
+static PyObject *us_per_us = NULL; /* 1 */
+static PyObject *us_per_ms = NULL; /* 1000 */
+static PyObject *us_per_second = NULL; /* 1000000 */
+static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
+static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
+static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
+static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
/* ---------------------------------------------------------------------------
@@ -1486,7 +1486,7 @@ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
*/
/* Convert a timedelta to a number of us,
- * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
+ * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
* as a Python int or long.
* Doing mixed-radix arithmetic by hand instead is excruciating in C,
* due to ubiquitous overflow possibilities.
@@ -1494,49 +1494,49 @@ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
static PyObject *
delta_to_microseconds(PyDateTime_Delta *self)
{
- PyObject *x1 = NULL;
- PyObject *x2 = NULL;
- PyObject *x3 = NULL;
- PyObject *result = NULL;
-
- x1 = PyLong_FromLong(GET_TD_DAYS(self));
- if (x1 == NULL)
- goto Done;
- x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
- if (x2 == NULL)
- goto Done;
- Py_DECREF(x1);
- x1 = NULL;
-
- /* x2 has days in seconds */
- x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
- if (x1 == NULL)
- goto Done;
- x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
- if (x3 == NULL)
- goto Done;
- Py_DECREF(x1);
- Py_DECREF(x2);
- x1 = x2 = NULL;
-
- /* x3 has days+seconds in seconds */
- x1 = PyNumber_Multiply(x3, us_per_second); /* us */
- if (x1 == NULL)
- goto Done;
- Py_DECREF(x3);
- x3 = NULL;
-
- /* x1 has days+seconds in us */
- x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
- if (x2 == NULL)
- goto Done;
- result = PyNumber_Add(x1, x2);
+ PyObject *x1 = NULL;
+ PyObject *x2 = NULL;
+ PyObject *x3 = NULL;
+ PyObject *result = NULL;
+
+ x1 = PyLong_FromLong(GET_TD_DAYS(self));
+ if (x1 == NULL)
+ goto Done;
+ x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
+ if (x2 == NULL)
+ goto Done;
+ Py_DECREF(x1);
+ x1 = NULL;
+
+ /* x2 has days in seconds */
+ x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
+ if (x1 == NULL)
+ goto Done;
+ x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
+ if (x3 == NULL)
+ goto Done;
+ Py_DECREF(x1);
+ Py_DECREF(x2);
+ x1 = x2 = NULL;
+
+ /* x3 has days+seconds in seconds */
+ x1 = PyNumber_Multiply(x3, us_per_second); /* us */
+ if (x1 == NULL)
+ goto Done;
+ Py_DECREF(x3);
+ x3 = NULL;
+
+ /* x1 has days+seconds in us */
+ x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
+ if (x2 == NULL)
+ goto Done;
+ result = PyNumber_Add(x1, x2);
Done:
- Py_XDECREF(x1);
- Py_XDECREF(x2);
- Py_XDECREF(x3);
- return result;
+ Py_XDECREF(x1);
+ Py_XDECREF(x2);
+ Py_XDECREF(x3);
+ return result;
}
/* Convert a number of us (as a Python int or long) to a timedelta.
@@ -1544,270 +1544,270 @@ Done:
static PyObject *
microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
{
- int us;
- int s;
- int d;
- long temp;
-
- PyObject *tuple = NULL;
- PyObject *num = NULL;
- PyObject *result = NULL;
-
- tuple = PyNumber_Divmod(pyus, us_per_second);
- if (tuple == NULL)
- goto Done;
-
- num = PyTuple_GetItem(tuple, 1); /* us */
- if (num == NULL)
- goto Done;
- temp = PyLong_AsLong(num);
- num = NULL;
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- assert(0 <= temp && temp < 1000000);
- us = (int)temp;
- if (us < 0) {
- /* The divisor was positive, so this must be an error. */
- assert(PyErr_Occurred());
- goto Done;
- }
-
- num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
- if (num == NULL)
- goto Done;
- Py_INCREF(num);
- Py_DECREF(tuple);
-
- tuple = PyNumber_Divmod(num, seconds_per_day);
- if (tuple == NULL)
- goto Done;
- Py_DECREF(num);
-
- num = PyTuple_GetItem(tuple, 1); /* seconds */
- if (num == NULL)
- goto Done;
- temp = PyLong_AsLong(num);
- num = NULL;
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- assert(0 <= temp && temp < 24*3600);
- s = (int)temp;
-
- if (s < 0) {
- /* The divisor was positive, so this must be an error. */
- assert(PyErr_Occurred());
- goto Done;
- }
-
- num = PyTuple_GetItem(tuple, 0); /* leftover days */
- if (num == NULL)
- goto Done;
- Py_INCREF(num);
- temp = PyLong_AsLong(num);
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- d = (int)temp;
- if ((long)d != temp) {
- PyErr_SetString(PyExc_OverflowError, "normalized days too "
- "large to fit in a C int");
- goto Done;
- }
- result = new_delta_ex(d, s, us, 0, type);
+ int us;
+ int s;
+ int d;
+ long temp;
+
+ PyObject *tuple = NULL;
+ PyObject *num = NULL;
+ PyObject *result = NULL;
+
+ tuple = PyNumber_Divmod(pyus, us_per_second);
+ if (tuple == NULL)
+ goto Done;
+
+ num = PyTuple_GetItem(tuple, 1); /* us */
+ if (num == NULL)
+ goto Done;
+ temp = PyLong_AsLong(num);
+ num = NULL;
+ if (temp == -1 && PyErr_Occurred())
+ goto Done;
+ assert(0 <= temp && temp < 1000000);
+ us = (int)temp;
+ if (us < 0) {
+ /* The divisor was positive, so this must be an error. */
+ assert(PyErr_Occurred());
+ goto Done;
+ }
+
+ num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
+ if (num == NULL)
+ goto Done;
+ Py_INCREF(num);
+ Py_DECREF(tuple);
+
+ tuple = PyNumber_Divmod(num, seconds_per_day);
+ if (tuple == NULL)
+ goto Done;
+ Py_DECREF(num);
+
+ num = PyTuple_GetItem(tuple, 1); /* seconds */
+ if (num == NULL)
+ goto Done;
+ temp = PyLong_AsLong(num);
+ num = NULL;
+ if (temp == -1 && PyErr_Occurred())
+ goto Done;
+ assert(0 <= temp && temp < 24*3600);
+ s = (int)temp;
+
+ if (s < 0) {
+ /* The divisor was positive, so this must be an error. */
+ assert(PyErr_Occurred());
+ goto Done;
+ }
+
+ num = PyTuple_GetItem(tuple, 0); /* leftover days */
+ if (num == NULL)
+ goto Done;
+ Py_INCREF(num);
+ temp = PyLong_AsLong(num);
+ if (temp == -1 && PyErr_Occurred())
+ goto Done;
+ d = (int)temp;
+ if ((long)d != temp) {
+ PyErr_SetString(PyExc_OverflowError, "normalized days too "
+ "large to fit in a C int");
+ goto Done;
+ }
+ result = new_delta_ex(d, s, us, 0, type);
Done:
- Py_XDECREF(tuple);
- Py_XDECREF(num);
- return result;
+ Py_XDECREF(tuple);
+ Py_XDECREF(num);
+ return result;
}
-#define microseconds_to_delta(pymicros) \
- microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
+#define microseconds_to_delta(pymicros) \
+ microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
static PyObject *
multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
{
- PyObject *pyus_in;
- PyObject *pyus_out;
- PyObject *result;
+ PyObject *pyus_in;
+ PyObject *pyus_out;
+ PyObject *result;
- pyus_in = delta_to_microseconds(delta);
- if (pyus_in == NULL)
- return NULL;
+ pyus_in = delta_to_microseconds(delta);
+ if (pyus_in == NULL)
+ return NULL;
- pyus_out = PyNumber_Multiply(pyus_in, intobj);
- Py_DECREF(pyus_in);
- if (pyus_out == NULL)
- return NULL;
+ pyus_out = PyNumber_Multiply(pyus_in, intobj);
+ Py_DECREF(pyus_in);
+ if (pyus_out == NULL)
+ return NULL;
- result = microseconds_to_delta(pyus_out);
- Py_DECREF(pyus_out);
- return result;
+ result = microseconds_to_delta(pyus_out);
+ Py_DECREF(pyus_out);
+ return result;
}
static PyObject *
divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
{
- PyObject *pyus_in;
- PyObject *pyus_out;
- PyObject *result;
+ PyObject *pyus_in;
+ PyObject *pyus_out;
+ PyObject *result;
- pyus_in = delta_to_microseconds(delta);
- if (pyus_in == NULL)
- return NULL;
+ pyus_in = delta_to_microseconds(delta);
+ if (pyus_in == NULL)
+ return NULL;
- pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
- Py_DECREF(pyus_in);
- if (pyus_out == NULL)
- return NULL;
+ pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
+ Py_DECREF(pyus_in);
+ if (pyus_out == NULL)
+ return NULL;
- result = microseconds_to_delta(pyus_out);
- Py_DECREF(pyus_out);
- return result;
+ result = microseconds_to_delta(pyus_out);
+ Py_DECREF(pyus_out);
+ return result;
}
static PyObject *
divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
{
- PyObject *pyus_left;
- PyObject *pyus_right;
- PyObject *result;
+ PyObject *pyus_left;
+ PyObject *pyus_right;
+ PyObject *result;
- pyus_left = delta_to_microseconds(left);
- if (pyus_left == NULL)
- return NULL;
+ pyus_left = delta_to_microseconds(left);
+ if (pyus_left == NULL)
+ return NULL;
- pyus_right = delta_to_microseconds(right);
- if (pyus_right == NULL) {
- Py_DECREF(pyus_left);
- return NULL;
- }
+ pyus_right = delta_to_microseconds(right);
+ if (pyus_right == NULL) {
+ Py_DECREF(pyus_left);
+ return NULL;
+ }
- result = PyNumber_FloorDivide(pyus_left, pyus_right);
- Py_DECREF(pyus_left);
- Py_DECREF(pyus_right);
- return result;
+ result = PyNumber_FloorDivide(pyus_left, pyus_right);
+ Py_DECREF(pyus_left);
+ Py_DECREF(pyus_right);
+ return result;
}
static PyObject *
truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
{
- PyObject *pyus_left;
- PyObject *pyus_right;
- PyObject *result;
+ PyObject *pyus_left;
+ PyObject *pyus_right;
+ PyObject *result;
- pyus_left = delta_to_microseconds(left);
- if (pyus_left == NULL)
- return NULL;
+ pyus_left = delta_to_microseconds(left);
+ if (pyus_left == NULL)
+ return NULL;
- pyus_right = delta_to_microseconds(right);
- if (pyus_right == NULL) {
- Py_DECREF(pyus_left);
- return NULL;
- }
+ pyus_right = delta_to_microseconds(right);
+ if (pyus_right == NULL) {
+ Py_DECREF(pyus_left);
+ return NULL;
+ }
- result = PyNumber_TrueDivide(pyus_left, pyus_right);
- Py_DECREF(pyus_left);
- Py_DECREF(pyus_right);
- return result;
+ result = PyNumber_TrueDivide(pyus_left, pyus_right);
+ Py_DECREF(pyus_left);
+ Py_DECREF(pyus_right);
+ return result;
}
static PyObject *
delta_add(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left) && PyDelta_Check(right)) {
- /* delta + delta */
- /* The C-level additions can't overflow because of the
- * invariant bounds.
- */
- int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
- int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
- int microseconds = GET_TD_MICROSECONDS(left) +
- GET_TD_MICROSECONDS(right);
- result = new_delta(days, seconds, microseconds, 1);
- }
+ if (PyDelta_Check(left) && PyDelta_Check(right)) {
+ /* delta + delta */
+ /* The C-level additions can't overflow because of the
+ * invariant bounds.
+ */
+ int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
+ int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
+ int microseconds = GET_TD_MICROSECONDS(left) +
+ GET_TD_MICROSECONDS(right);
+ result = new_delta(days, seconds, microseconds, 1);
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_negative(PyDateTime_Delta *self)
{
- return new_delta(-GET_TD_DAYS(self),
- -GET_TD_SECONDS(self),
- -GET_TD_MICROSECONDS(self),
- 1);
+ return new_delta(-GET_TD_DAYS(self),
+ -GET_TD_SECONDS(self),
+ -GET_TD_MICROSECONDS(self),
+ 1);
}
static PyObject *
delta_positive(PyDateTime_Delta *self)
{
- /* Could optimize this (by returning self) if this isn't a
- * subclass -- but who uses unary + ? Approximately nobody.
- */
- return new_delta(GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self),
- 0);
+ /* Could optimize this (by returning self) if this isn't a
+ * subclass -- but who uses unary + ? Approximately nobody.
+ */
+ return new_delta(GET_TD_DAYS(self),
+ GET_TD_SECONDS(self),
+ GET_TD_MICROSECONDS(self),
+ 0);
}
static PyObject *
delta_abs(PyDateTime_Delta *self)
{
- PyObject *result;
+ PyObject *result;
- assert(GET_TD_MICROSECONDS(self) >= 0);
- assert(GET_TD_SECONDS(self) >= 0);
+ assert(GET_TD_MICROSECONDS(self) >= 0);
+ assert(GET_TD_SECONDS(self) >= 0);
- if (GET_TD_DAYS(self) < 0)
- result = delta_negative(self);
- else
- result = delta_positive(self);
+ if (GET_TD_DAYS(self) < 0)
+ result = delta_negative(self);
+ else
+ result = delta_positive(self);
- return result;
+ return result;
}
static PyObject *
delta_subtract(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left) && PyDelta_Check(right)) {
- /* delta - delta */
- PyObject *minus_right = PyNumber_Negative(right);
- if (minus_right) {
- result = delta_add(left, minus_right);
- Py_DECREF(minus_right);
- }
- else
- result = NULL;
- }
+ if (PyDelta_Check(left) && PyDelta_Check(right)) {
+ /* delta - delta */
+ PyObject *minus_right = PyNumber_Negative(right);
+ if (minus_right) {
+ result = delta_add(left, minus_right);
+ Py_DECREF(minus_right);
+ }
+ else
+ result = NULL;
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_richcompare(PyObject *self, PyObject *other, int op)
{
- if (PyDelta_Check(other)) {
- int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
- if (diff == 0) {
- diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
- if (diff == 0)
- diff = GET_TD_MICROSECONDS(self) -
- GET_TD_MICROSECONDS(other);
- }
- return diff_to_bool(diff, op);
- }
- else {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
+ if (PyDelta_Check(other)) {
+ int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
+ if (diff == 0) {
+ diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
+ if (diff == 0)
+ diff = GET_TD_MICROSECONDS(self) -
+ GET_TD_MICROSECONDS(other);
+ }
+ return diff_to_bool(diff, op);
+ }
+ else {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
}
static PyObject *delta_getstate(PyDateTime_Delta *self);
@@ -1815,152 +1815,152 @@ static PyObject *delta_getstate(PyDateTime_Delta *self);
static long
delta_hash(PyDateTime_Delta *self)
{
- if (self->hashcode == -1) {
- PyObject *temp = delta_getstate(self);
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ PyObject *temp = delta_getstate(self);
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
delta_multiply(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left)) {
- /* delta * ??? */
- if (PyLong_Check(right))
- result = multiply_int_timedelta(right,
- (PyDateTime_Delta *) left);
- }
- else if (PyLong_Check(left))
- result = multiply_int_timedelta(left,
- (PyDateTime_Delta *) right);
+ if (PyDelta_Check(left)) {
+ /* delta * ??? */
+ if (PyLong_Check(right))
+ result = multiply_int_timedelta(right,
+ (PyDateTime_Delta *) left);
+ }
+ else if (PyLong_Check(left))
+ result = multiply_int_timedelta(left,
+ (PyDateTime_Delta *) right);
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_divide(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left)) {
- /* delta * ??? */
- if (PyLong_Check(right))
- result = divide_timedelta_int(
- (PyDateTime_Delta *)left,
- right);
- else if (PyDelta_Check(right))
- result = divide_timedelta_timedelta(
- (PyDateTime_Delta *)left,
- (PyDateTime_Delta *)right);
- }
+ if (PyDelta_Check(left)) {
+ /* delta * ??? */
+ if (PyLong_Check(right))
+ result = divide_timedelta_int(
+ (PyDateTime_Delta *)left,
+ right);
+ else if (PyDelta_Check(right))
+ result = divide_timedelta_timedelta(
+ (PyDateTime_Delta *)left,
+ (PyDateTime_Delta *)right);
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_truedivide(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left)) {
- if (PyDelta_Check(right))
- result = truedivide_timedelta_timedelta(
- (PyDateTime_Delta *)left,
- (PyDateTime_Delta *)right);
- }
+ if (PyDelta_Check(left)) {
+ if (PyDelta_Check(right))
+ result = truedivide_timedelta_timedelta(
+ (PyDateTime_Delta *)left,
+ (PyDateTime_Delta *)right);
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_remainder(PyObject *left, PyObject *right)
{
- PyObject *pyus_left;
- PyObject *pyus_right;
- PyObject *pyus_remainder;
- PyObject *remainder;
+ PyObject *pyus_left;
+ PyObject *pyus_right;
+ PyObject *pyus_remainder;
+ PyObject *remainder;
- if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
+ if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
- pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
- if (pyus_left == NULL)
- return NULL;
+ pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
+ if (pyus_left == NULL)
+ return NULL;
- pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
- if (pyus_right == NULL) {
- Py_DECREF(pyus_left);
- return NULL;
- }
+ pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
+ if (pyus_right == NULL) {
+ Py_DECREF(pyus_left);
+ return NULL;
+ }
- pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
- Py_DECREF(pyus_left);
- Py_DECREF(pyus_right);
- if (pyus_remainder == NULL)
- return NULL;
+ pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
+ Py_DECREF(pyus_left);
+ Py_DECREF(pyus_right);
+ if (pyus_remainder == NULL)
+ return NULL;
- remainder = microseconds_to_delta(pyus_remainder);
- Py_DECREF(pyus_remainder);
- if (remainder == NULL)
- return NULL;
+ remainder = microseconds_to_delta(pyus_remainder);
+ Py_DECREF(pyus_remainder);
+ if (remainder == NULL)
+ return NULL;
- return remainder;
+ return remainder;
}
static PyObject *
delta_divmod(PyObject *left, PyObject *right)
{
- PyObject *pyus_left;
- PyObject *pyus_right;
- PyObject *divmod;
- PyObject *delta;
- PyObject *result;
-
- if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
- if (pyus_left == NULL)
- return NULL;
-
- pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
- if (pyus_right == NULL) {
- Py_DECREF(pyus_left);
- return NULL;
- }
-
- divmod = PyNumber_Divmod(pyus_left, pyus_right);
- Py_DECREF(pyus_left);
- Py_DECREF(pyus_right);
- if (divmod == NULL)
- return NULL;
-
- assert(PyTuple_Size(divmod) == 2);
- delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
- if (delta == NULL) {
- Py_DECREF(divmod);
- return NULL;
- }
- result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
- Py_DECREF(delta);
- Py_DECREF(divmod);
- return result;
+ PyObject *pyus_left;
+ PyObject *pyus_right;
+ PyObject *divmod;
+ PyObject *delta;
+ PyObject *result;
+
+ if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
+ if (pyus_left == NULL)
+ return NULL;
+
+ pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
+ if (pyus_right == NULL) {
+ Py_DECREF(pyus_left);
+ return NULL;
+ }
+
+ divmod = PyNumber_Divmod(pyus_left, pyus_right);
+ Py_DECREF(pyus_left);
+ Py_DECREF(pyus_right);
+ if (divmod == NULL)
+ return NULL;
+
+ assert(PyTuple_Size(divmod) == 2);
+ delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
+ if (delta == NULL) {
+ Py_DECREF(divmod);
+ return NULL;
+ }
+ result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
+ Py_DECREF(delta);
+ Py_DECREF(divmod);
+ return result;
}
/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
@@ -1976,166 +1976,166 @@ static PyObject *
accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
double *leftover)
{
- PyObject *prod;
- PyObject *sum;
-
- assert(num != NULL);
-
- if (PyLong_Check(num)) {
- prod = PyNumber_Multiply(num, factor);
- if (prod == NULL)
- return NULL;
- sum = PyNumber_Add(sofar, prod);
- Py_DECREF(prod);
- return sum;
- }
-
- if (PyFloat_Check(num)) {
- double dnum;
- double fracpart;
- double intpart;
- PyObject *x;
- PyObject *y;
-
- /* The Plan: decompose num into an integer part and a
- * fractional part, num = intpart + fracpart.
- * Then num * factor ==
- * intpart * factor + fracpart * factor
- * and the LHS can be computed exactly in long arithmetic.
- * The RHS is again broken into an int part and frac part.
- * and the frac part is added into *leftover.
- */
- dnum = PyFloat_AsDouble(num);
- if (dnum == -1.0 && PyErr_Occurred())
- return NULL;
- fracpart = modf(dnum, &intpart);
- x = PyLong_FromDouble(intpart);
- if (x == NULL)
- return NULL;
-
- prod = PyNumber_Multiply(x, factor);
- Py_DECREF(x);
- if (prod == NULL)
- return NULL;
-
- sum = PyNumber_Add(sofar, prod);
- Py_DECREF(prod);
- if (sum == NULL)
- return NULL;
-
- if (fracpart == 0.0)
- return sum;
- /* So far we've lost no information. Dealing with the
- * fractional part requires float arithmetic, and may
- * lose a little info.
- */
- assert(PyLong_Check(factor));
- dnum = PyLong_AsDouble(factor);
-
- dnum *= fracpart;
- fracpart = modf(dnum, &intpart);
- x = PyLong_FromDouble(intpart);
- if (x == NULL) {
- Py_DECREF(sum);
- return NULL;
- }
-
- y = PyNumber_Add(sum, x);
- Py_DECREF(sum);
- Py_DECREF(x);
- *leftover += fracpart;
- return y;
- }
-
- PyErr_Format(PyExc_TypeError,
- "unsupported type for timedelta %s component: %s",
- tag, Py_TYPE(num)->tp_name);
- return NULL;
+ PyObject *prod;
+ PyObject *sum;
+
+ assert(num != NULL);
+
+ if (PyLong_Check(num)) {
+ prod = PyNumber_Multiply(num, factor);
+ if (prod == NULL)
+ return NULL;
+ sum = PyNumber_Add(sofar, prod);
+ Py_DECREF(prod);
+ return sum;
+ }
+
+ if (PyFloat_Check(num)) {
+ double dnum;
+ double fracpart;
+ double intpart;
+ PyObject *x;
+ PyObject *y;
+
+ /* The Plan: decompose num into an integer part and a
+ * fractional part, num = intpart + fracpart.
+ * Then num * factor ==
+ * intpart * factor + fracpart * factor
+ * and the LHS can be computed exactly in long arithmetic.
+ * The RHS is again broken into an int part and frac part.
+ * and the frac part is added into *leftover.
+ */
+ dnum = PyFloat_AsDouble(num);
+ if (dnum == -1.0 && PyErr_Occurred())
+ return NULL;
+ fracpart = modf(dnum, &intpart);
+ x = PyLong_FromDouble(intpart);
+ if (x == NULL)
+ return NULL;
+
+ prod = PyNumber_Multiply(x, factor);
+ Py_DECREF(x);
+ if (prod == NULL)
+ return NULL;
+
+ sum = PyNumber_Add(sofar, prod);
+ Py_DECREF(prod);
+ if (sum == NULL)
+ return NULL;
+
+ if (fracpart == 0.0)
+ return sum;
+ /* So far we've lost no information. Dealing with the
+ * fractional part requires float arithmetic, and may
+ * lose a little info.
+ */
+ assert(PyLong_Check(factor));
+ dnum = PyLong_AsDouble(factor);
+
+ dnum *= fracpart;
+ fracpart = modf(dnum, &intpart);
+ x = PyLong_FromDouble(intpart);
+ if (x == NULL) {
+ Py_DECREF(sum);
+ return NULL;
+ }
+
+ y = PyNumber_Add(sum, x);
+ Py_DECREF(sum);
+ Py_DECREF(x);
+ *leftover += fracpart;
+ return y;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "unsupported type for timedelta %s component: %s",
+ tag, Py_TYPE(num)->tp_name);
+ return NULL;
}
static PyObject *
delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
-
- /* Argument objects. */
- PyObject *day = NULL;
- PyObject *second = NULL;
- PyObject *us = NULL;
- PyObject *ms = NULL;
- PyObject *minute = NULL;
- PyObject *hour = NULL;
- PyObject *week = NULL;
-
- PyObject *x = NULL; /* running sum of microseconds */
- PyObject *y = NULL; /* temp sum of microseconds */
- double leftover_us = 0.0;
-
- static char *keywords[] = {
- "days", "seconds", "microseconds", "milliseconds",
- "minutes", "hours", "weeks", NULL
- };
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
- keywords,
- &day, &second, &us,
- &ms, &minute, &hour, &week) == 0)
- goto Done;
-
- x = PyLong_FromLong(0);
- if (x == NULL)
- goto Done;
-
-#define CLEANUP \
- Py_DECREF(x); \
- x = y; \
- if (x == NULL) \
- goto Done
-
- if (us) {
- y = accum("microseconds", x, us, us_per_us, &leftover_us);
- CLEANUP;
- }
- if (ms) {
- y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
- CLEANUP;
- }
- if (second) {
- y = accum("seconds", x, second, us_per_second, &leftover_us);
- CLEANUP;
- }
- if (minute) {
- y = accum("minutes", x, minute, us_per_minute, &leftover_us);
- CLEANUP;
- }
- if (hour) {
- y = accum("hours", x, hour, us_per_hour, &leftover_us);
- CLEANUP;
- }
- if (day) {
- y = accum("days", x, day, us_per_day, &leftover_us);
- CLEANUP;
- }
- if (week) {
- y = accum("weeks", x, week, us_per_week, &leftover_us);
- CLEANUP;
- }
- if (leftover_us) {
- /* Round to nearest whole # of us, and add into x. */
- PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
- if (temp == NULL) {
- Py_DECREF(x);
- goto Done;
- }
- y = PyNumber_Add(x, temp);
- Py_DECREF(temp);
- CLEANUP;
- }
-
- self = microseconds_to_delta_ex(x, type);
- Py_DECREF(x);
+ PyObject *self = NULL;
+
+ /* Argument objects. */
+ PyObject *day = NULL;
+ PyObject *second = NULL;
+ PyObject *us = NULL;
+ PyObject *ms = NULL;
+ PyObject *minute = NULL;
+ PyObject *hour = NULL;
+ PyObject *week = NULL;
+
+ PyObject *x = NULL; /* running sum of microseconds */
+ PyObject *y = NULL; /* temp sum of microseconds */
+ double leftover_us = 0.0;
+
+ static char *keywords[] = {
+ "days", "seconds", "microseconds", "milliseconds",
+ "minutes", "hours", "weeks", NULL
+ };
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
+ keywords,
+ &day, &second, &us,
+ &ms, &minute, &hour, &week) == 0)
+ goto Done;
+
+ x = PyLong_FromLong(0);
+ if (x == NULL)
+ goto Done;
+
+#define CLEANUP \
+ Py_DECREF(x); \
+ x = y; \
+ if (x == NULL) \
+ goto Done
+
+ if (us) {
+ y = accum("microseconds", x, us, us_per_us, &leftover_us);
+ CLEANUP;
+ }
+ if (ms) {
+ y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
+ CLEANUP;
+ }
+ if (second) {
+ y = accum("seconds", x, second, us_per_second, &leftover_us);
+ CLEANUP;
+ }
+ if (minute) {
+ y = accum("minutes", x, minute, us_per_minute, &leftover_us);
+ CLEANUP;
+ }
+ if (hour) {
+ y = accum("hours", x, hour, us_per_hour, &leftover_us);
+ CLEANUP;
+ }
+ if (day) {
+ y = accum("days", x, day, us_per_day, &leftover_us);
+ CLEANUP;
+ }
+ if (week) {
+ y = accum("weeks", x, week, us_per_week, &leftover_us);
+ CLEANUP;
+ }
+ if (leftover_us) {
+ /* Round to nearest whole # of us, and add into x. */
+ PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
+ if (temp == NULL) {
+ Py_DECREF(x);
+ goto Done;
+ }
+ y = PyNumber_Add(x, temp);
+ Py_DECREF(temp);
+ CLEANUP;
+ }
+
+ self = microseconds_to_delta_ex(x, type);
+ Py_DECREF(x);
Done:
- return self;
+ return self;
#undef CLEANUP
}
@@ -2143,57 +2143,57 @@ Done:
static int
delta_bool(PyDateTime_Delta *self)
{
- return (GET_TD_DAYS(self) != 0
- || GET_TD_SECONDS(self) != 0
- || GET_TD_MICROSECONDS(self) != 0);
+ return (GET_TD_DAYS(self) != 0
+ || GET_TD_SECONDS(self) != 0
+ || GET_TD_MICROSECONDS(self) != 0);
}
static PyObject *
delta_repr(PyDateTime_Delta *self)
{
- if (GET_TD_MICROSECONDS(self) != 0)
- return PyUnicode_FromFormat("%s(%d, %d, %d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self));
- if (GET_TD_SECONDS(self) != 0)
- return PyUnicode_FromFormat("%s(%d, %d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self),
- GET_TD_SECONDS(self));
+ if (GET_TD_MICROSECONDS(self) != 0)
+ return PyUnicode_FromFormat("%s(%d, %d, %d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self),
+ GET_TD_SECONDS(self),
+ GET_TD_MICROSECONDS(self));
+ if (GET_TD_SECONDS(self) != 0)
+ return PyUnicode_FromFormat("%s(%d, %d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self),
+ GET_TD_SECONDS(self));
- return PyUnicode_FromFormat("%s(%d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self));
+ return PyUnicode_FromFormat("%s(%d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self));
}
static PyObject *
delta_str(PyDateTime_Delta *self)
{
- int us = GET_TD_MICROSECONDS(self);
- int seconds = GET_TD_SECONDS(self);
- int minutes = divmod(seconds, 60, &seconds);
- int hours = divmod(minutes, 60, &minutes);
- int days = GET_TD_DAYS(self);
-
- if (days) {
- if (us)
- return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
- days, (days == 1 || days == -1) ? "" : "s",
- hours, minutes, seconds, us);
- else
- return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
- days, (days == 1 || days == -1) ? "" : "s",
- hours, minutes, seconds);
- } else {
- if (us)
- return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
- hours, minutes, seconds, us);
- else
- return PyUnicode_FromFormat("%d:%02d:%02d",
- hours, minutes, seconds);
- }
+ int us = GET_TD_MICROSECONDS(self);
+ int seconds = GET_TD_SECONDS(self);
+ int minutes = divmod(seconds, 60, &seconds);
+ int hours = divmod(minutes, 60, &minutes);
+ int days = GET_TD_DAYS(self);
+
+ if (days) {
+ if (us)
+ return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
+ days, (days == 1 || days == -1) ? "" : "s",
+ hours, minutes, seconds, us);
+ else
+ return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
+ days, (days == 1 || days == -1) ? "" : "s",
+ hours, minutes, seconds);
+ } else {
+ if (us)
+ return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
+ hours, minutes, seconds, us);
+ else
+ return PyUnicode_FromFormat("%d:%02d:%02d",
+ hours, minutes, seconds);
+ }
}
@@ -2203,145 +2203,145 @@ delta_str(PyDateTime_Delta *self)
static PyObject *
delta_getstate(PyDateTime_Delta *self)
{
- return Py_BuildValue("iii", GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self));
+ return Py_BuildValue("iii", GET_TD_DAYS(self),
+ GET_TD_SECONDS(self),
+ GET_TD_MICROSECONDS(self));
}
static PyObject *
delta_total_seconds(PyObject *self)
{
- PyObject *total_seconds;
- PyObject *total_microseconds;
- PyObject *one_million;
+ PyObject *total_seconds;
+ PyObject *total_microseconds;
+ PyObject *one_million;
- total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
- if (total_microseconds == NULL)
- return NULL;
+ total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
+ if (total_microseconds == NULL)
+ return NULL;
- one_million = PyLong_FromLong(1000000L);
- if (one_million == NULL) {
- Py_DECREF(total_microseconds);
- return NULL;
- }
+ one_million = PyLong_FromLong(1000000L);
+ if (one_million == NULL) {
+ Py_DECREF(total_microseconds);
+ return NULL;
+ }
- total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
+ total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
- Py_DECREF(total_microseconds);
- Py_DECREF(one_million);
- return total_seconds;
+ Py_DECREF(total_microseconds);
+ Py_DECREF(one_million);
+ return total_seconds;
}
static PyObject *
delta_reduce(PyDateTime_Delta* self)
{
- return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
+ return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
}
#define OFFSET(field) offsetof(PyDateTime_Delta, field)
static PyMemberDef delta_members[] = {
- {"days", T_INT, OFFSET(days), READONLY,
- PyDoc_STR("Number of days.")},
+ {"days", T_INT, OFFSET(days), READONLY,
+ PyDoc_STR("Number of days.")},
- {"seconds", T_INT, OFFSET(seconds), READONLY,
- PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
+ {"seconds", T_INT, OFFSET(seconds), READONLY,
+ PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
- {"microseconds", T_INT, OFFSET(microseconds), READONLY,
- PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
- {NULL}
+ {"microseconds", T_INT, OFFSET(microseconds), READONLY,
+ PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
+ {NULL}
};
static PyMethodDef delta_methods[] = {
- {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
- PyDoc_STR("Total seconds in the duration.")},
+ {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
+ PyDoc_STR("Total seconds in the duration.")},
- {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL},
+ {NULL, NULL},
};
static char delta_doc[] =
PyDoc_STR("Difference between two datetime values.");
static PyNumberMethods delta_as_number = {
- delta_add, /* nb_add */
- delta_subtract, /* nb_subtract */
- delta_multiply, /* nb_multiply */
- delta_remainder, /* nb_remainder */
- delta_divmod, /* nb_divmod */
- 0, /* nb_power */
- (unaryfunc)delta_negative, /* nb_negative */
- (unaryfunc)delta_positive, /* nb_positive */
- (unaryfunc)delta_abs, /* nb_absolute */
- (inquiry)delta_bool, /* nb_bool */
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_int*/
- 0, /*nb_reserved*/
- 0, /*nb_float*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- delta_divide, /* nb_floor_divide */
- delta_truedivide, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
+ delta_add, /* nb_add */
+ delta_subtract, /* nb_subtract */
+ delta_multiply, /* nb_multiply */
+ delta_remainder, /* nb_remainder */
+ delta_divmod, /* nb_divmod */
+ 0, /* nb_power */
+ (unaryfunc)delta_negative, /* nb_negative */
+ (unaryfunc)delta_positive, /* nb_positive */
+ (unaryfunc)delta_abs, /* nb_absolute */
+ (inquiry)delta_bool, /* nb_bool */
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ 0, /*nb_and*/
+ 0, /*nb_xor*/
+ 0, /*nb_or*/
+ 0, /*nb_int*/
+ 0, /*nb_reserved*/
+ 0, /*nb_float*/
+ 0, /*nb_inplace_add*/
+ 0, /*nb_inplace_subtract*/
+ 0, /*nb_inplace_multiply*/
+ 0, /*nb_inplace_remainder*/
+ 0, /*nb_inplace_power*/
+ 0, /*nb_inplace_lshift*/
+ 0, /*nb_inplace_rshift*/
+ 0, /*nb_inplace_and*/
+ 0, /*nb_inplace_xor*/
+ 0, /*nb_inplace_or*/
+ delta_divide, /* nb_floor_divide */
+ delta_truedivide, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
};
static PyTypeObject PyDateTime_DeltaType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.timedelta", /* tp_name */
- sizeof(PyDateTime_Delta), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)delta_repr, /* tp_repr */
- &delta_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)delta_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)delta_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- delta_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- delta_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- delta_methods, /* tp_methods */
- delta_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- delta_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.timedelta", /* tp_name */
+ sizeof(PyDateTime_Delta), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)delta_repr, /* tp_repr */
+ &delta_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)delta_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)delta_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ delta_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ delta_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ delta_methods, /* tp_methods */
+ delta_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ delta_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -2353,26 +2353,26 @@ static PyTypeObject PyDateTime_DeltaType = {
static PyObject *
date_year(PyDateTime_Date *self, void *unused)
{
- return PyLong_FromLong(GET_YEAR(self));
+ return PyLong_FromLong(GET_YEAR(self));
}
static PyObject *
date_month(PyDateTime_Date *self, void *unused)
{
- return PyLong_FromLong(GET_MONTH(self));
+ return PyLong_FromLong(GET_MONTH(self));
}
static PyObject *
date_day(PyDateTime_Date *self, void *unused)
{
- return PyLong_FromLong(GET_DAY(self));
+ return PyLong_FromLong(GET_DAY(self));
}
static PyGetSetDef date_getset[] = {
- {"year", (getter)date_year},
- {"month", (getter)date_month},
- {"day", (getter)date_day},
- {NULL}
+ {"year", (getter)date_year},
+ {"month", (getter)date_month},
+ {"day", (getter)date_day},
+ {NULL}
};
/* Constructors. */
@@ -2382,60 +2382,60 @@ static char *date_kws[] = {"year", "month", "day", NULL};
static PyObject *
date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
- PyObject *state;
- int year;
- int month;
- int day;
-
- /* Check for invocation from pickle with __getstate__ state */
- if (PyTuple_GET_SIZE(args) == 1 &&
- PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
- MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
- {
- PyDateTime_Date *me;
-
- me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
- if (me != NULL) {
- char *pdata = PyBytes_AS_STRING(state);
- memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
- me->hashcode = -1;
- }
- return (PyObject *)me;
- }
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
- &year, &month, &day)) {
- if (check_date_args(year, month, day) < 0)
- return NULL;
- self = new_date_ex(year, month, day, type);
- }
- return self;
+ PyObject *self = NULL;
+ PyObject *state;
+ int year;
+ int month;
+ int day;
+
+ /* Check for invocation from pickle with __getstate__ state */
+ if (PyTuple_GET_SIZE(args) == 1 &&
+ PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
+ MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
+ {
+ PyDateTime_Date *me;
+
+ me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
+ if (me != NULL) {
+ char *pdata = PyBytes_AS_STRING(state);
+ memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
+ me->hashcode = -1;
+ }
+ return (PyObject *)me;
+ }
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
+ &year, &month, &day)) {
+ if (check_date_args(year, month, day) < 0)
+ return NULL;
+ self = new_date_ex(year, month, day, type);
+ }
+ return self;
}
/* Return new date from localtime(t). */
static PyObject *
date_local_from_time_t(PyObject *cls, double ts)
{
- struct tm *tm;
- time_t t;
- PyObject *result = NULL;
-
- t = _PyTime_DoubleToTimet(ts);
- if (t == (time_t)-1 && PyErr_Occurred())
- return NULL;
- tm = localtime(&t);
- if (tm)
- result = PyObject_CallFunction(cls, "iii",
- tm->tm_year + 1900,
- tm->tm_mon + 1,
- tm->tm_mday);
- else
- PyErr_SetString(PyExc_ValueError,
- "timestamp out of range for "
- "platform localtime() function");
- return result;
+ struct tm *tm;
+ time_t t;
+ PyObject *result = NULL;
+
+ t = _PyTime_DoubleToTimet(ts);
+ if (t == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ tm = localtime(&t);
+ if (tm)
+ result = PyObject_CallFunction(cls, "iii",
+ tm->tm_year + 1900,
+ tm->tm_mon + 1,
+ tm->tm_mday);
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "timestamp out of range for "
+ "platform localtime() function");
+ return result;
}
/* Return new date from current time.
@@ -2446,34 +2446,34 @@ date_local_from_time_t(PyObject *cls, double ts)
static PyObject *
date_today(PyObject *cls, PyObject *dummy)
{
- PyObject *time;
- PyObject *result;
+ PyObject *time;
+ PyObject *result;
- time = time_time();
- if (time == NULL)
- return NULL;
+ time = time_time();
+ if (time == NULL)
+ return NULL;
- /* Note well: today() is a class method, so this may not call
- * date.fromtimestamp. For example, it may call
- * datetime.fromtimestamp. That's why we need all the accuracy
- * time.time() delivers; if someone were gonzo about optimization,
- * date.today() could get away with plain C time().
- */
- result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
- Py_DECREF(time);
- return result;
+ /* Note well: today() is a class method, so this may not call
+ * date.fromtimestamp. For example, it may call
+ * datetime.fromtimestamp. That's why we need all the accuracy
+ * time.time() delivers; if someone were gonzo about optimization,
+ * date.today() could get away with plain C time().
+ */
+ result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
+ Py_DECREF(time);
+ return result;
}
/* Return new date from given timestamp (Python timestamp -- a double). */
static PyObject *
date_fromtimestamp(PyObject *cls, PyObject *args)
{
- double timestamp;
- PyObject *result = NULL;
+ double timestamp;
+ PyObject *result = NULL;
- if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
- result = date_local_from_time_t(cls, timestamp);
- return result;
+ if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
+ result = date_local_from_time_t(cls, timestamp);
+ return result;
}
/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
@@ -2482,24 +2482,24 @@ date_fromtimestamp(PyObject *cls, PyObject *args)
static PyObject *
date_fromordinal(PyObject *cls, PyObject *args)
{
- PyObject *result = NULL;
- int ordinal;
+ PyObject *result = NULL;
+ int ordinal;
- if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
- int year;
- int month;
- int day;
+ if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
+ int year;
+ int month;
+ int day;
- if (ordinal < 1)
- PyErr_SetString(PyExc_ValueError, "ordinal must be "
- ">= 1");
- else {
- ord_to_ymd(ordinal, &year, &month, &day);
- result = PyObject_CallFunction(cls, "iii",
- year, month, day);
- }
- }
- return result;
+ if (ordinal < 1)
+ PyErr_SetString(PyExc_ValueError, "ordinal must be "
+ ">= 1");
+ else {
+ ord_to_ymd(ordinal, &year, &month, &day);
+ result = PyObject_CallFunction(cls, "iii",
+ year, month, day);
+ }
+ }
+ return result;
}
/*
@@ -2512,74 +2512,74 @@ date_fromordinal(PyObject *cls, PyObject *args)
static PyObject *
add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
{
- PyObject *result = NULL;
- int year = GET_YEAR(date);
- int month = GET_MONTH(date);
- int deltadays = GET_TD_DAYS(delta);
- /* C-level overflow is impossible because |deltadays| < 1e9. */
- int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
+ PyObject *result = NULL;
+ int year = GET_YEAR(date);
+ int month = GET_MONTH(date);
+ int deltadays = GET_TD_DAYS(delta);
+ /* C-level overflow is impossible because |deltadays| < 1e9. */
+ int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
- if (normalize_date(&year, &month, &day) >= 0)
- result = new_date(year, month, day);
- return result;
+ if (normalize_date(&year, &month, &day) >= 0)
+ result = new_date(year, month, day);
+ return result;
}
static PyObject *
date_add(PyObject *left, PyObject *right)
{
- if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (PyDate_Check(left)) {
- /* date + ??? */
- if (PyDelta_Check(right))
- /* date + delta */
- return add_date_timedelta((PyDateTime_Date *) left,
- (PyDateTime_Delta *) right,
- 0);
- }
- else {
- /* ??? + date
- * 'right' must be one of us, or we wouldn't have been called
- */
- if (PyDelta_Check(left))
- /* delta + date */
- return add_date_timedelta((PyDateTime_Date *) right,
- (PyDateTime_Delta *) left,
- 0);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (PyDate_Check(left)) {
+ /* date + ??? */
+ if (PyDelta_Check(right))
+ /* date + delta */
+ return add_date_timedelta((PyDateTime_Date *) left,
+ (PyDateTime_Delta *) right,
+ 0);
+ }
+ else {
+ /* ??? + date
+ * 'right' must be one of us, or we wouldn't have been called
+ */
+ if (PyDelta_Check(left))
+ /* delta + date */
+ return add_date_timedelta((PyDateTime_Date *) right,
+ (PyDateTime_Delta *) left,
+ 0);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyObject *
date_subtract(PyObject *left, PyObject *right)
{
- if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (PyDate_Check(left)) {
- if (PyDate_Check(right)) {
- /* date - date */
- int left_ord = ymd_to_ord(GET_YEAR(left),
- GET_MONTH(left),
- GET_DAY(left));
- int right_ord = ymd_to_ord(GET_YEAR(right),
- GET_MONTH(right),
- GET_DAY(right));
- return new_delta(left_ord - right_ord, 0, 0, 0);
- }
- if (PyDelta_Check(right)) {
- /* date - delta */
- return add_date_timedelta((PyDateTime_Date *) left,
- (PyDateTime_Delta *) right,
- 1);
- }
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (PyDate_Check(left)) {
+ if (PyDate_Check(right)) {
+ /* date - date */
+ int left_ord = ymd_to_ord(GET_YEAR(left),
+ GET_MONTH(left),
+ GET_DAY(left));
+ int right_ord = ymd_to_ord(GET_YEAR(right),
+ GET_MONTH(right),
+ GET_DAY(right));
+ return new_delta(left_ord - right_ord, 0, 0, 0);
+ }
+ if (PyDelta_Check(right)) {
+ /* date - delta */
+ return add_date_timedelta((PyDateTime_Date *) left,
+ (PyDateTime_Delta *) right,
+ 1);
+ }
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
@@ -2588,69 +2588,69 @@ date_subtract(PyObject *left, PyObject *right)
static PyObject *
date_repr(PyDateTime_Date *self)
{
- return PyUnicode_FromFormat("%s(%d, %d, %d)",
- Py_TYPE(self)->tp_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ return PyUnicode_FromFormat("%s(%d, %d, %d)",
+ Py_TYPE(self)->tp_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
}
static PyObject *
date_isoformat(PyDateTime_Date *self)
{
- return PyUnicode_FromFormat("%04d-%02d-%02d",
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ return PyUnicode_FromFormat("%04d-%02d-%02d",
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
}
/* str() calls the appropriate isoformat() method. */
static PyObject *
date_str(PyDateTime_Date *self)
{
- return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
+ return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
}
static PyObject *
date_ctime(PyDateTime_Date *self)
{
- return format_ctime(self, 0, 0, 0);
+ return format_ctime(self, 0, 0, 0);
}
static PyObject *
date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
{
- /* This method can be inherited, and needs to call the
- * timetuple() method appropriate to self's class.
- */
- PyObject *result;
- PyObject *tuple;
- PyObject *format;
- static char *keywords[] = {"format", NULL};
+ /* This method can be inherited, and needs to call the
+ * timetuple() method appropriate to self's class.
+ */
+ PyObject *result;
+ PyObject *tuple;
+ PyObject *format;
+ static char *keywords[] = {"format", NULL};
- if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
- &format))
- return NULL;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
+ &format))
+ return NULL;
- tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
- if (tuple == NULL)
- return NULL;
- result = wrap_strftime((PyObject *)self, format, tuple,
- (PyObject *)self);
- Py_DECREF(tuple);
- return result;
+ tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
+ if (tuple == NULL)
+ return NULL;
+ result = wrap_strftime((PyObject *)self, format, tuple,
+ (PyObject *)self);
+ Py_DECREF(tuple);
+ return result;
}
static PyObject *
date_format(PyDateTime_Date *self, PyObject *args)
{
- PyObject *format;
+ PyObject *format;
- if (!PyArg_ParseTuple(args, "U:__format__", &format))
- return NULL;
+ if (!PyArg_ParseTuple(args, "U:__format__", &format))
+ return NULL;
- /* if the format is zero length, return str(self) */
- if (PyUnicode_GetSize(format) == 0)
- return PyObject_Str((PyObject *)self);
+ /* if the format is zero length, return str(self) */
+ if (PyUnicode_GetSize(format) == 0)
+ return PyObject_Str((PyObject *)self);
- return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
+ return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
}
/* ISO methods. */
@@ -2658,31 +2658,31 @@ date_format(PyDateTime_Date *self, PyObject *args)
static PyObject *
date_isoweekday(PyDateTime_Date *self)
{
- int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
- return PyLong_FromLong(dow + 1);
+ return PyLong_FromLong(dow + 1);
}
static PyObject *
date_isocalendar(PyDateTime_Date *self)
{
- int year = GET_YEAR(self);
- int week1_monday = iso_week1_monday(year);
- int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
- int week;
- int day;
-
- week = divmod(today - week1_monday, 7, &day);
- if (week < 0) {
- --year;
- week1_monday = iso_week1_monday(year);
- week = divmod(today - week1_monday, 7, &day);
- }
- else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
- ++year;
- week = 0;
- }
- return Py_BuildValue("iii", year, week + 1, day + 1);
+ int year = GET_YEAR(self);
+ int week1_monday = iso_week1_monday(year);
+ int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
+ int week;
+ int day;
+
+ week = divmod(today - week1_monday, 7, &day);
+ if (week < 0) {
+ --year;
+ week1_monday = iso_week1_monday(year);
+ week = divmod(today - week1_monday, 7, &day);
+ }
+ else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
+ ++year;
+ week = 0;
+ }
+ return Py_BuildValue("iii", year, week + 1, day + 1);
}
/* Miscellaneous methods. */
@@ -2690,65 +2690,65 @@ date_isocalendar(PyDateTime_Date *self)
static PyObject *
date_richcompare(PyObject *self, PyObject *other, int op)
{
- if (PyDate_Check(other)) {
- int diff = memcmp(((PyDateTime_Date *)self)->data,
- ((PyDateTime_Date *)other)->data,
- _PyDateTime_DATE_DATASIZE);
- return diff_to_bool(diff, op);
- }
- else {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
+ if (PyDate_Check(other)) {
+ int diff = memcmp(((PyDateTime_Date *)self)->data,
+ ((PyDateTime_Date *)other)->data,
+ _PyDateTime_DATE_DATASIZE);
+ return diff_to_bool(diff, op);
+ }
+ else {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
}
static PyObject *
date_timetuple(PyDateTime_Date *self)
{
- return build_struct_time(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self),
- 0, 0, 0, -1);
+ return build_struct_time(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self),
+ 0, 0, 0, -1);
}
static PyObject *
date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
{
- PyObject *clone;
- PyObject *tuple;
- int year = GET_YEAR(self);
- int month = GET_MONTH(self);
- int day = GET_DAY(self);
+ PyObject *clone;
+ PyObject *tuple;
+ int year = GET_YEAR(self);
+ int month = GET_MONTH(self);
+ int day = GET_DAY(self);
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
- &year, &month, &day))
- return NULL;
- tuple = Py_BuildValue("iii", year, month, day);
- if (tuple == NULL)
- return NULL;
- clone = date_new(Py_TYPE(self), tuple, NULL);
- Py_DECREF(tuple);
- return clone;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
+ &year, &month, &day))
+ return NULL;
+ tuple = Py_BuildValue("iii", year, month, day);
+ if (tuple == NULL)
+ return NULL;
+ clone = date_new(Py_TYPE(self), tuple, NULL);
+ Py_DECREF(tuple);
+ return clone;
}
/*
- Borrowed from stringobject.c, originally it was string_hash()
+ Borrowed from stringobject.c, originally it was string_hash()
*/
static long
generic_hash(unsigned char *data, int len)
{
- register unsigned char *p;
- register long x;
+ register unsigned char *p;
+ register long x;
- p = (unsigned char *) data;
- x = *p << 7;
- while (--len >= 0)
- x = (1000003*x) ^ *p++;
- x ^= len;
- if (x == -1)
- x = -2;
+ p = (unsigned char *) data;
+ x = *p << 7;
+ while (--len >= 0)
+ x = (1000003*x) ^ *p++;
+ x ^= len;
+ if (x == -1)
+ x = -2;
- return x;
+ return x;
}
@@ -2757,26 +2757,26 @@ static PyObject *date_getstate(PyDateTime_Date *self);
static long
date_hash(PyDateTime_Date *self)
{
- if (self->hashcode == -1)
- self->hashcode = generic_hash(
- (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
+ if (self->hashcode == -1)
+ self->hashcode = generic_hash(
+ (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
- return self->hashcode;
+ return self->hashcode;
}
static PyObject *
date_toordinal(PyDateTime_Date *self)
{
- return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
- GET_DAY(self)));
+ return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
+ GET_DAY(self)));
}
static PyObject *
date_weekday(PyDateTime_Date *self)
{
- int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
- return PyLong_FromLong(dow);
+ return PyLong_FromLong(dow);
}
/* Pickle support, a simple use of __reduce__. */
@@ -2785,134 +2785,134 @@ date_weekday(PyDateTime_Date *self)
static PyObject *
date_getstate(PyDateTime_Date *self)
{
- PyObject* field;
- field = PyBytes_FromStringAndSize((char*)self->data,
- _PyDateTime_DATE_DATASIZE);
- return Py_BuildValue("(N)", field);
+ PyObject* field;
+ field = PyBytes_FromStringAndSize((char*)self->data,
+ _PyDateTime_DATE_DATASIZE);
+ return Py_BuildValue("(N)", field);
}
static PyObject *
date_reduce(PyDateTime_Date *self, PyObject *arg)
{
- return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
+ return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
}
static PyMethodDef date_methods[] = {
- /* Class methods: */
+ /* Class methods: */
- {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
- METH_CLASS,
- PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
- "time.time()).")},
+ {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
+ METH_CLASS,
+ PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
+ "time.time()).")},
- {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
- METH_CLASS,
- PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
- "ordinal.")},
+ {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
+ METH_CLASS,
+ PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
+ "ordinal.")},
- {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
- PyDoc_STR("Current date or datetime: same as "
- "self.__class__.fromtimestamp(time.time()).")},
+ {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
+ PyDoc_STR("Current date or datetime: same as "
+ "self.__class__.fromtimestamp(time.time()).")},
- /* Instance methods: */
+ /* Instance methods: */
- {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
- PyDoc_STR("Return ctime() style string.")},
+ {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
+ PyDoc_STR("Return ctime() style string.")},
- {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("format -> strftime() style string.")},
+ {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("format -> strftime() style string.")},
- {"__format__", (PyCFunction)date_format, METH_VARARGS,
- PyDoc_STR("Formats self with strftime.")},
+ {"__format__", (PyCFunction)date_format, METH_VARARGS,
+ PyDoc_STR("Formats self with strftime.")},
- {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
- PyDoc_STR("Return time tuple, compatible with time.localtime().")},
+ {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
+ PyDoc_STR("Return time tuple, compatible with time.localtime().")},
- {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
- PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
- "weekday.")},
+ {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
+ PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
+ "weekday.")},
- {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
- PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
+ {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
+ PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
- {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
- PyDoc_STR("Return the day of the week represented by the date.\n"
- "Monday == 1 ... Sunday == 7")},
+ {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
+ PyDoc_STR("Return the day of the week represented by the date.\n"
+ "Monday == 1 ... Sunday == 7")},
- {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
- PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
- "1 is day 1.")},
+ {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
+ PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
+ "1 is day 1.")},
- {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
- PyDoc_STR("Return the day of the week represented by the date.\n"
- "Monday == 0 ... Sunday == 6")},
+ {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
+ PyDoc_STR("Return the day of the week represented by the date.\n"
+ "Monday == 0 ... Sunday == 6")},
- {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("Return date with new specified fields.")},
+ {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("Return date with new specified fields.")},
- {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char date_doc[] =
PyDoc_STR("date(year, month, day) --> date object");
static PyNumberMethods date_as_number = {
- date_add, /* nb_add */
- date_subtract, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_bool */
+ date_add, /* nb_add */
+ date_subtract, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_bool */
};
static PyTypeObject PyDateTime_DateType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.date", /* tp_name */
- sizeof(PyDateTime_Date), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)date_repr, /* tp_repr */
- &date_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)date_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)date_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- date_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- date_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- date_methods, /* tp_methods */
- 0, /* tp_members */
- date_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- date_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.date", /* tp_name */
+ sizeof(PyDateTime_Date), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)date_repr, /* tp_repr */
+ &date_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)date_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)date_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ date_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ date_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ date_methods, /* tp_methods */
+ 0, /* tp_members */
+ date_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ date_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -2935,10 +2935,10 @@ static PyTypeObject PyDateTime_DateType = {
static PyObject *
tzinfo_nogo(const char* methodname)
{
- PyErr_Format(PyExc_NotImplementedError,
- "a tzinfo subclass must implement %s()",
- methodname);
- return NULL;
+ PyErr_Format(PyExc_NotImplementedError,
+ "a tzinfo subclass must implement %s()",
+ methodname);
+ return NULL;
}
/* Methods. A subclass must implement these. */
@@ -2946,101 +2946,101 @@ tzinfo_nogo(const char* methodname)
static PyObject *
tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
{
- return tzinfo_nogo("tzname");
+ return tzinfo_nogo("tzname");
}
static PyObject *
tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
{
- return tzinfo_nogo("utcoffset");
+ return tzinfo_nogo("utcoffset");
}
static PyObject *
tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
{
- return tzinfo_nogo("dst");
+ return tzinfo_nogo("dst");
}
static PyObject *
tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
{
- int y, m, d, hh, mm, ss, us;
-
- PyObject *result;
- int off, dst;
- int none;
- int delta;
-
- if (! PyDateTime_Check(dt)) {
- PyErr_SetString(PyExc_TypeError,
- "fromutc: argument must be a datetime");
- return NULL;
- }
- if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
- PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
- "is not self");
- return NULL;
- }
-
- off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
- if (off == -1 && PyErr_Occurred())
- return NULL;
- if (none) {
- PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
- "utcoffset() result required");
- return NULL;
- }
-
- dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
- if (dst == -1 && PyErr_Occurred())
- return NULL;
- if (none) {
- PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
- "dst() result required");
- return NULL;
- }
-
- y = GET_YEAR(dt);
- m = GET_MONTH(dt);
- d = GET_DAY(dt);
- hh = DATE_GET_HOUR(dt);
- mm = DATE_GET_MINUTE(dt);
- ss = DATE_GET_SECOND(dt);
- us = DATE_GET_MICROSECOND(dt);
-
- delta = off - dst;
- mm += delta;
- if ((mm < 0 || mm >= 60) &&
- normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
- return NULL;
- result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
- if (result == NULL)
- return result;
-
- dst = call_dst(dt->tzinfo, result, &none);
- if (dst == -1 && PyErr_Occurred())
- goto Fail;
- if (none)
- goto Inconsistent;
- if (dst == 0)
- return result;
-
- mm += dst;
- if ((mm < 0 || mm >= 60) &&
- normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
- goto Fail;
- Py_DECREF(result);
- result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
- return result;
+ int y, m, d, hh, mm, ss, us;
+
+ PyObject *result;
+ int off, dst;
+ int none;
+ int delta;
+
+ if (! PyDateTime_Check(dt)) {
+ PyErr_SetString(PyExc_TypeError,
+ "fromutc: argument must be a datetime");
+ return NULL;
+ }
+ if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
+ PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
+ "is not self");
+ return NULL;
+ }
+
+ off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
+ if (off == -1 && PyErr_Occurred())
+ return NULL;
+ if (none) {
+ PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
+ "utcoffset() result required");
+ return NULL;
+ }
+
+ dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
+ if (dst == -1 && PyErr_Occurred())
+ return NULL;
+ if (none) {
+ PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
+ "dst() result required");
+ return NULL;
+ }
+
+ y = GET_YEAR(dt);
+ m = GET_MONTH(dt);
+ d = GET_DAY(dt);
+ hh = DATE_GET_HOUR(dt);
+ mm = DATE_GET_MINUTE(dt);
+ ss = DATE_GET_SECOND(dt);
+ us = DATE_GET_MICROSECOND(dt);
+
+ delta = off - dst;
+ mm += delta;
+ if ((mm < 0 || mm >= 60) &&
+ normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+ return NULL;
+ result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
+ if (result == NULL)
+ return result;
+
+ dst = call_dst(dt->tzinfo, result, &none);
+ if (dst == -1 && PyErr_Occurred())
+ goto Fail;
+ if (none)
+ goto Inconsistent;
+ if (dst == 0)
+ return result;
+
+ mm += dst;
+ if ((mm < 0 || mm >= 60) &&
+ normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+ goto Fail;
+ Py_DECREF(result);
+ result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
+ return result;
Inconsistent:
- PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
- "inconsistent results; cannot convert");
+ PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
+ "inconsistent results; cannot convert");
- /* fall thru to failure */
+ /* fall thru to failure */
Fail:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
/*
@@ -3051,122 +3051,122 @@ Fail:
static PyObject *
tzinfo_reduce(PyObject *self)
{
- PyObject *args, *state, *tmp;
- PyObject *getinitargs, *getstate;
-
- tmp = PyTuple_New(0);
- if (tmp == NULL)
- return NULL;
-
- getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
- if (getinitargs != NULL) {
- args = PyObject_CallObject(getinitargs, tmp);
- Py_DECREF(getinitargs);
- if (args == NULL) {
- Py_DECREF(tmp);
- return NULL;
- }
- }
- else {
- PyErr_Clear();
- args = tmp;
- Py_INCREF(args);
- }
-
- getstate = PyObject_GetAttrString(self, "__getstate__");
- if (getstate != NULL) {
- state = PyObject_CallObject(getstate, tmp);
- Py_DECREF(getstate);
- if (state == NULL) {
- Py_DECREF(args);
- Py_DECREF(tmp);
- return NULL;
- }
- }
- else {
- PyObject **dictptr;
- PyErr_Clear();
- state = Py_None;
- dictptr = _PyObject_GetDictPtr(self);
- if (dictptr && *dictptr && PyDict_Size(*dictptr))
- state = *dictptr;
- Py_INCREF(state);
- }
-
- Py_DECREF(tmp);
-
- if (state == Py_None) {
- Py_DECREF(state);
- return Py_BuildValue("(ON)", Py_TYPE(self), args);
- }
- else
- return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
+ PyObject *args, *state, *tmp;
+ PyObject *getinitargs, *getstate;
+
+ tmp = PyTuple_New(0);
+ if (tmp == NULL)
+ return NULL;
+
+ getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
+ if (getinitargs != NULL) {
+ args = PyObject_CallObject(getinitargs, tmp);
+ Py_DECREF(getinitargs);
+ if (args == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Clear();
+ args = tmp;
+ Py_INCREF(args);
+ }
+
+ getstate = PyObject_GetAttrString(self, "__getstate__");
+ if (getstate != NULL) {
+ state = PyObject_CallObject(getstate, tmp);
+ Py_DECREF(getstate);
+ if (state == NULL) {
+ Py_DECREF(args);
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ }
+ else {
+ PyObject **dictptr;
+ PyErr_Clear();
+ state = Py_None;
+ dictptr = _PyObject_GetDictPtr(self);
+ if (dictptr && *dictptr && PyDict_Size(*dictptr))
+ state = *dictptr;
+ Py_INCREF(state);
+ }
+
+ Py_DECREF(tmp);
+
+ if (state == Py_None) {
+ Py_DECREF(state);
+ return Py_BuildValue("(ON)", Py_TYPE(self), args);
+ }
+ else
+ return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
}
static PyMethodDef tzinfo_methods[] = {
- {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
- PyDoc_STR("datetime -> string name of time zone.")},
+ {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
+ PyDoc_STR("datetime -> string name of time zone.")},
- {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
- PyDoc_STR("datetime -> minutes east of UTC (negative for "
- "west of UTC).")},
+ {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
+ PyDoc_STR("datetime -> minutes east of UTC (negative for "
+ "west of UTC).")},
- {"dst", (PyCFunction)tzinfo_dst, METH_O,
- PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
+ {"dst", (PyCFunction)tzinfo_dst, METH_O,
+ PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
- {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
- PyDoc_STR("datetime in UTC -> datetime in local time.")},
+ {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
+ PyDoc_STR("datetime in UTC -> datetime in local time.")},
- {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
- PyDoc_STR("-> (cls, state)")},
+ {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
+ PyDoc_STR("-> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char tzinfo_doc[] =
PyDoc_STR("Abstract base class for time zone info objects.");
static PyTypeObject PyDateTime_TZInfoType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.tzinfo", /* tp_name */
- sizeof(PyDateTime_TZInfo), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- tzinfo_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- tzinfo_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.tzinfo", /* tp_name */
+ sizeof(PyDateTime_TZInfo), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ tzinfo_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ tzinfo_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -3179,43 +3179,43 @@ static PyTypeObject PyDateTime_TZInfoType = {
static PyObject *
time_hour(PyDateTime_Time *self, void *unused)
{
- return PyLong_FromLong(TIME_GET_HOUR(self));
+ return PyLong_FromLong(TIME_GET_HOUR(self));
}
static PyObject *
time_minute(PyDateTime_Time *self, void *unused)
{
- return PyLong_FromLong(TIME_GET_MINUTE(self));
+ return PyLong_FromLong(TIME_GET_MINUTE(self));
}
/* The name time_second conflicted with some platform header file. */
static PyObject *
py_time_second(PyDateTime_Time *self, void *unused)
{
- return PyLong_FromLong(TIME_GET_SECOND(self));
+ return PyLong_FromLong(TIME_GET_SECOND(self));
}
static PyObject *
time_microsecond(PyDateTime_Time *self, void *unused)
{
- return PyLong_FromLong(TIME_GET_MICROSECOND(self));
+ return PyLong_FromLong(TIME_GET_MICROSECOND(self));
}
static PyObject *
time_tzinfo(PyDateTime_Time *self, void *unused)
{
- PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
- Py_INCREF(result);
- return result;
+ PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
+ Py_INCREF(result);
+ return result;
}
static PyGetSetDef time_getset[] = {
- {"hour", (getter)time_hour},
- {"minute", (getter)time_minute},
- {"second", (getter)py_time_second},
- {"microsecond", (getter)time_microsecond},
- {"tzinfo", (getter)time_tzinfo},
- {NULL}
+ {"hour", (getter)time_hour},
+ {"minute", (getter)time_minute},
+ {"second", (getter)py_time_second},
+ {"microsecond", (getter)time_microsecond},
+ {"tzinfo", (getter)time_tzinfo},
+ {NULL}
};
/*
@@ -3223,64 +3223,64 @@ static PyGetSetDef time_getset[] = {
*/
static char *time_kws[] = {"hour", "minute", "second", "microsecond",
- "tzinfo", NULL};
+ "tzinfo", NULL};
static PyObject *
time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
- PyObject *state;
- int hour = 0;
- int minute = 0;
- int second = 0;
- int usecond = 0;
- PyObject *tzinfo = Py_None;
-
- /* Check for invocation from pickle with __getstate__ state */
- if (PyTuple_GET_SIZE(args) >= 1 &&
- PyTuple_GET_SIZE(args) <= 2 &&
- PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
- ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
- {
- PyDateTime_Time *me;
- char aware;
-
- if (PyTuple_GET_SIZE(args) == 2) {
- tzinfo = PyTuple_GET_ITEM(args, 1);
- if (check_tzinfo_subclass(tzinfo) < 0) {
- PyErr_SetString(PyExc_TypeError, "bad "
- "tzinfo state arg");
- return NULL;
- }
- }
- aware = (char)(tzinfo != Py_None);
- me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
- if (me != NULL) {
- char *pdata = PyBytes_AS_STRING(state);
-
- memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
- me->hashcode = -1;
- me->hastzinfo = aware;
- if (aware) {
- Py_INCREF(tzinfo);
- me->tzinfo = tzinfo;
- }
- }
- return (PyObject *)me;
- }
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
- &hour, &minute, &second, &usecond,
- &tzinfo)) {
- if (check_time_args(hour, minute, second, usecond) < 0)
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
- self = new_time_ex(hour, minute, second, usecond, tzinfo,
- type);
- }
- return self;
+ PyObject *self = NULL;
+ PyObject *state;
+ int hour = 0;
+ int minute = 0;
+ int second = 0;
+ int usecond = 0;
+ PyObject *tzinfo = Py_None;
+
+ /* Check for invocation from pickle with __getstate__ state */
+ if (PyTuple_GET_SIZE(args) >= 1 &&
+ PyTuple_GET_SIZE(args) <= 2 &&
+ PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
+ ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
+ {
+ PyDateTime_Time *me;
+ char aware;
+
+ if (PyTuple_GET_SIZE(args) == 2) {
+ tzinfo = PyTuple_GET_ITEM(args, 1);
+ if (check_tzinfo_subclass(tzinfo) < 0) {
+ PyErr_SetString(PyExc_TypeError, "bad "
+ "tzinfo state arg");
+ return NULL;
+ }
+ }
+ aware = (char)(tzinfo != Py_None);
+ me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
+ if (me != NULL) {
+ char *pdata = PyBytes_AS_STRING(state);
+
+ memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
+ me->hashcode = -1;
+ me->hastzinfo = aware;
+ if (aware) {
+ Py_INCREF(tzinfo);
+ me->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)me;
+ }
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
+ &hour, &minute, &second, &usecond,
+ &tzinfo)) {
+ if (check_time_args(hour, minute, second, usecond) < 0)
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
+ self = new_time_ex(hour, minute, second, usecond, tzinfo,
+ type);
+ }
+ return self;
}
/*
@@ -3290,10 +3290,10 @@ time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
static void
time_dealloc(PyDateTime_Time *self)
{
- if (HASTZINFO(self)) {
- Py_XDECREF(self->tzinfo);
- }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ if (HASTZINFO(self)) {
+ Py_XDECREF(self->tzinfo);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
/*
@@ -3303,20 +3303,20 @@ time_dealloc(PyDateTime_Time *self)
/* These are all METH_NOARGS, so don't need to check the arglist. */
static PyObject *
time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "utcoffset", Py_None);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "utcoffset", Py_None);
}
static PyObject *
time_dst(PyDateTime_Time *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "dst", Py_None);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "dst", Py_None);
}
static PyObject *
time_tzname(PyDateTime_Time *self, PyObject *unused) {
- return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
- Py_None);
+ return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
+ Py_None);
}
/*
@@ -3326,93 +3326,93 @@ time_tzname(PyDateTime_Time *self, PyObject *unused) {
static PyObject *
time_repr(PyDateTime_Time *self)
{
- const char *type_name = Py_TYPE(self)->tp_name;
- int h = TIME_GET_HOUR(self);
- int m = TIME_GET_MINUTE(self);
- int s = TIME_GET_SECOND(self);
- int us = TIME_GET_MICROSECOND(self);
- PyObject *result = NULL;
-
- if (us)
- result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
- type_name, h, m, s, us);
- else if (s)
- result = PyUnicode_FromFormat("%s(%d, %d, %d)",
- type_name, h, m, s);
- else
- result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
- if (result != NULL && HASTZINFO(self))
- result = append_keyword_tzinfo(result, self->tzinfo);
- return result;
+ const char *type_name = Py_TYPE(self)->tp_name;
+ int h = TIME_GET_HOUR(self);
+ int m = TIME_GET_MINUTE(self);
+ int s = TIME_GET_SECOND(self);
+ int us = TIME_GET_MICROSECOND(self);
+ PyObject *result = NULL;
+
+ if (us)
+ result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
+ type_name, h, m, s, us);
+ else if (s)
+ result = PyUnicode_FromFormat("%s(%d, %d, %d)",
+ type_name, h, m, s);
+ else
+ result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
+ if (result != NULL && HASTZINFO(self))
+ result = append_keyword_tzinfo(result, self->tzinfo);
+ return result;
}
static PyObject *
time_str(PyDateTime_Time *self)
{
- return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
+ return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
}
static PyObject *
time_isoformat(PyDateTime_Time *self, PyObject *unused)
{
- char buf[100];
- PyObject *result;
- int us = TIME_GET_MICROSECOND(self);;
-
- if (us)
- result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
- TIME_GET_HOUR(self),
- TIME_GET_MINUTE(self),
- TIME_GET_SECOND(self),
- us);
- else
- result = PyUnicode_FromFormat("%02d:%02d:%02d",
- TIME_GET_HOUR(self),
- TIME_GET_MINUTE(self),
- TIME_GET_SECOND(self));
-
- if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
- return result;
-
- /* We need to append the UTC offset. */
- if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
- Py_None) < 0) {
- Py_DECREF(result);
- return NULL;
- }
- PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
- return result;
+ char buf[100];
+ PyObject *result;
+ int us = TIME_GET_MICROSECOND(self);;
+
+ if (us)
+ result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
+ TIME_GET_HOUR(self),
+ TIME_GET_MINUTE(self),
+ TIME_GET_SECOND(self),
+ us);
+ else
+ result = PyUnicode_FromFormat("%02d:%02d:%02d",
+ TIME_GET_HOUR(self),
+ TIME_GET_MINUTE(self),
+ TIME_GET_SECOND(self));
+
+ if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
+ return result;
+
+ /* We need to append the UTC offset. */
+ if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
+ Py_None) < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
+ return result;
}
static PyObject *
time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
{
- PyObject *result;
- PyObject *tuple;
- PyObject *format;
- static char *keywords[] = {"format", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
- &format))
- return NULL;
-
- /* Python's strftime does insane things with the year part of the
- * timetuple. The year is forced to (the otherwise nonsensical)
- * 1900 to worm around that.
- */
- tuple = Py_BuildValue("iiiiiiiii",
- 1900, 1, 1, /* year, month, day */
- TIME_GET_HOUR(self),
- TIME_GET_MINUTE(self),
- TIME_GET_SECOND(self),
- 0, 1, -1); /* weekday, daynum, dst */
- if (tuple == NULL)
- return NULL;
- assert(PyTuple_Size(tuple) == 9);
- result = wrap_strftime((PyObject *)self, format, tuple,
- Py_None);
- Py_DECREF(tuple);
- return result;
+ PyObject *result;
+ PyObject *tuple;
+ PyObject *format;
+ static char *keywords[] = {"format", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
+ &format))
+ return NULL;
+
+ /* Python's strftime does insane things with the year part of the
+ * timetuple. The year is forced to (the otherwise nonsensical)
+ * 1900 to worm around that.
+ */
+ tuple = Py_BuildValue("iiiiiiiii",
+ 1900, 1, 1, /* year, month, day */
+ TIME_GET_HOUR(self),
+ TIME_GET_MINUTE(self),
+ TIME_GET_SECOND(self),
+ 0, 1, -1); /* weekday, daynum, dst */
+ if (tuple == NULL)
+ return NULL;
+ assert(PyTuple_Size(tuple) == 9);
+ result = wrap_strftime((PyObject *)self, format, tuple,
+ Py_None);
+ Py_DECREF(tuple);
+ return result;
}
/*
@@ -3422,144 +3422,144 @@ time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
static PyObject *
time_richcompare(PyObject *self, PyObject *other, int op)
{
- int diff;
- naivety n1, n2;
- int offset1, offset2;
-
- if (! PyTime_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
- other, &offset2, &n2, Py_None) < 0)
- return NULL;
- assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
- /* If they're both naive, or both aware and have the same offsets,
- * we get off cheap. Note that if they're both naive, offset1 ==
- * offset2 == 0 at this point.
- */
- if (n1 == n2 && offset1 == offset2) {
- diff = memcmp(((PyDateTime_Time *)self)->data,
- ((PyDateTime_Time *)other)->data,
- _PyDateTime_TIME_DATASIZE);
- return diff_to_bool(diff, op);
- }
-
- if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
- assert(offset1 != offset2); /* else last "if" handled it */
- /* Convert everything except microseconds to seconds. These
- * can't overflow (no more than the # of seconds in 2 days).
- */
- offset1 = TIME_GET_HOUR(self) * 3600 +
- (TIME_GET_MINUTE(self) - offset1) * 60 +
- TIME_GET_SECOND(self);
- offset2 = TIME_GET_HOUR(other) * 3600 +
- (TIME_GET_MINUTE(other) - offset2) * 60 +
- TIME_GET_SECOND(other);
- diff = offset1 - offset2;
- if (diff == 0)
- diff = TIME_GET_MICROSECOND(self) -
- TIME_GET_MICROSECOND(other);
- return diff_to_bool(diff, op);
- }
-
- assert(n1 != n2);
- PyErr_SetString(PyExc_TypeError,
- "can't compare offset-naive and "
- "offset-aware times");
- return NULL;
+ int diff;
+ naivety n1, n2;
+ int offset1, offset2;
+
+ if (! PyTime_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
+ other, &offset2, &n2, Py_None) < 0)
+ return NULL;
+ assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+ /* If they're both naive, or both aware and have the same offsets,
+ * we get off cheap. Note that if they're both naive, offset1 ==
+ * offset2 == 0 at this point.
+ */
+ if (n1 == n2 && offset1 == offset2) {
+ diff = memcmp(((PyDateTime_Time *)self)->data,
+ ((PyDateTime_Time *)other)->data,
+ _PyDateTime_TIME_DATASIZE);
+ return diff_to_bool(diff, op);
+ }
+
+ if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
+ assert(offset1 != offset2); /* else last "if" handled it */
+ /* Convert everything except microseconds to seconds. These
+ * can't overflow (no more than the # of seconds in 2 days).
+ */
+ offset1 = TIME_GET_HOUR(self) * 3600 +
+ (TIME_GET_MINUTE(self) - offset1) * 60 +
+ TIME_GET_SECOND(self);
+ offset2 = TIME_GET_HOUR(other) * 3600 +
+ (TIME_GET_MINUTE(other) - offset2) * 60 +
+ TIME_GET_SECOND(other);
+ diff = offset1 - offset2;
+ if (diff == 0)
+ diff = TIME_GET_MICROSECOND(self) -
+ TIME_GET_MICROSECOND(other);
+ return diff_to_bool(diff, op);
+ }
+
+ assert(n1 != n2);
+ PyErr_SetString(PyExc_TypeError,
+ "can't compare offset-naive and "
+ "offset-aware times");
+ return NULL;
}
static long
time_hash(PyDateTime_Time *self)
{
- if (self->hashcode == -1) {
- naivety n;
- int offset;
- PyObject *temp;
-
- n = classify_utcoffset((PyObject *)self, Py_None, &offset);
- assert(n != OFFSET_UNKNOWN);
- if (n == OFFSET_ERROR)
- return -1;
-
- /* Reduce this to a hash of another object. */
- if (offset == 0) {
- self->hashcode = generic_hash(
- (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
- return self->hashcode;
- }
- else {
- int hour;
- int minute;
-
- assert(n == OFFSET_AWARE);
- assert(HASTZINFO(self));
- hour = divmod(TIME_GET_HOUR(self) * 60 +
- TIME_GET_MINUTE(self) - offset,
- 60,
- &minute);
- if (0 <= hour && hour < 24)
- temp = new_time(hour, minute,
- TIME_GET_SECOND(self),
- TIME_GET_MICROSECOND(self),
- Py_None);
- else
- temp = Py_BuildValue("iiii",
- hour, minute,
- TIME_GET_SECOND(self),
- TIME_GET_MICROSECOND(self));
- }
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ naivety n;
+ int offset;
+ PyObject *temp;
+
+ n = classify_utcoffset((PyObject *)self, Py_None, &offset);
+ assert(n != OFFSET_UNKNOWN);
+ if (n == OFFSET_ERROR)
+ return -1;
+
+ /* Reduce this to a hash of another object. */
+ if (offset == 0) {
+ self->hashcode = generic_hash(
+ (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
+ return self->hashcode;
+ }
+ else {
+ int hour;
+ int minute;
+
+ assert(n == OFFSET_AWARE);
+ assert(HASTZINFO(self));
+ hour = divmod(TIME_GET_HOUR(self) * 60 +
+ TIME_GET_MINUTE(self) - offset,
+ 60,
+ &minute);
+ if (0 <= hour && hour < 24)
+ temp = new_time(hour, minute,
+ TIME_GET_SECOND(self),
+ TIME_GET_MICROSECOND(self),
+ Py_None);
+ else
+ temp = Py_BuildValue("iiii",
+ hour, minute,
+ TIME_GET_SECOND(self),
+ TIME_GET_MICROSECOND(self));
+ }
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
{
- PyObject *clone;
- PyObject *tuple;
- int hh = TIME_GET_HOUR(self);
- int mm = TIME_GET_MINUTE(self);
- int ss = TIME_GET_SECOND(self);
- int us = TIME_GET_MICROSECOND(self);
- PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
- time_kws,
- &hh, &mm, &ss, &us, &tzinfo))
- return NULL;
- tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
- if (tuple == NULL)
- return NULL;
- clone = time_new(Py_TYPE(self), tuple, NULL);
- Py_DECREF(tuple);
- return clone;
+ PyObject *clone;
+ PyObject *tuple;
+ int hh = TIME_GET_HOUR(self);
+ int mm = TIME_GET_MINUTE(self);
+ int ss = TIME_GET_SECOND(self);
+ int us = TIME_GET_MICROSECOND(self);
+ PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
+ time_kws,
+ &hh, &mm, &ss, &us, &tzinfo))
+ return NULL;
+ tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
+ if (tuple == NULL)
+ return NULL;
+ clone = time_new(Py_TYPE(self), tuple, NULL);
+ Py_DECREF(tuple);
+ return clone;
}
static int
time_bool(PyDateTime_Time *self)
{
- int offset;
- int none;
-
- if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
- /* Since utcoffset is in whole minutes, nothing can
- * alter the conclusion that this is nonzero.
- */
- return 1;
- }
- offset = 0;
- if (HASTZINFO(self) && self->tzinfo != Py_None) {
- offset = call_utcoffset(self->tzinfo, Py_None, &none);
- if (offset == -1 && PyErr_Occurred())
- return -1;
- }
- return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
+ int offset;
+ int none;
+
+ if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
+ /* Since utcoffset is in whole minutes, nothing can
+ * alter the conclusion that this is nonzero.
+ */
+ return 1;
+ }
+ offset = 0;
+ if (HASTZINFO(self) && self->tzinfo != Py_None) {
+ offset = call_utcoffset(self->tzinfo, Py_None, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return -1;
+ }
+ return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
}
/* Pickle support, a simple use of __reduce__. */
@@ -3572,55 +3572,55 @@ time_bool(PyDateTime_Time *self)
static PyObject *
time_getstate(PyDateTime_Time *self)
{
- PyObject *basestate;
- PyObject *result = NULL;
+ PyObject *basestate;
+ PyObject *result = NULL;
- basestate = PyBytes_FromStringAndSize((char *)self->data,
- _PyDateTime_TIME_DATASIZE);
- if (basestate != NULL) {
- if (! HASTZINFO(self) || self->tzinfo == Py_None)
- result = PyTuple_Pack(1, basestate);
- else
- result = PyTuple_Pack(2, basestate, self->tzinfo);
- Py_DECREF(basestate);
- }
- return result;
+ basestate = PyBytes_FromStringAndSize((char *)self->data,
+ _PyDateTime_TIME_DATASIZE);
+ if (basestate != NULL) {
+ if (! HASTZINFO(self) || self->tzinfo == Py_None)
+ result = PyTuple_Pack(1, basestate);
+ else
+ result = PyTuple_Pack(2, basestate, self->tzinfo);
+ Py_DECREF(basestate);
+ }
+ return result;
}
static PyObject *
time_reduce(PyDateTime_Time *self, PyObject *arg)
{
- return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
+ return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
}
static PyMethodDef time_methods[] = {
- {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
- PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
- "[+HH:MM].")},
+ {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
+ PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
+ "[+HH:MM].")},
- {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("format -> strftime() style string.")},
+ {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("format -> strftime() style string.")},
- {"__format__", (PyCFunction)date_format, METH_VARARGS,
- PyDoc_STR("Formats self with strftime.")},
+ {"__format__", (PyCFunction)date_format, METH_VARARGS,
+ PyDoc_STR("Formats self with strftime.")},
- {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
+ {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
- {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.tzname(self).")},
+ {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.tzname(self).")},
- {"dst", (PyCFunction)time_dst, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.dst(self).")},
+ {"dst", (PyCFunction)time_dst, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.dst(self).")},
- {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("Return time with new specified fields.")},
+ {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("Return time with new specified fields.")},
- {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char time_doc[] =
@@ -3630,58 +3630,58 @@ All arguments are optional. tzinfo may be None, or an instance of\n\
a tzinfo subclass. The remaining arguments may be ints or longs.\n");
static PyNumberMethods time_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)time_bool, /* nb_bool */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)time_bool, /* nb_bool */
};
static PyTypeObject PyDateTime_TimeType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.time", /* tp_name */
- sizeof(PyDateTime_Time), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)time_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)time_repr, /* tp_repr */
- &time_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)time_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)time_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- time_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- time_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- time_methods, /* tp_methods */
- 0, /* tp_members */
- time_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- time_alloc, /* tp_alloc */
- time_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.time", /* tp_name */
+ sizeof(PyDateTime_Time), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)time_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)time_repr, /* tp_repr */
+ &time_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)time_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)time_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ time_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ time_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ time_methods, /* tp_methods */
+ 0, /* tp_members */
+ time_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ time_alloc, /* tp_alloc */
+ time_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -3695,42 +3695,42 @@ static PyTypeObject PyDateTime_TimeType = {
static PyObject *
datetime_hour(PyDateTime_DateTime *self, void *unused)
{
- return PyLong_FromLong(DATE_GET_HOUR(self));
+ return PyLong_FromLong(DATE_GET_HOUR(self));
}
static PyObject *
datetime_minute(PyDateTime_DateTime *self, void *unused)
{
- return PyLong_FromLong(DATE_GET_MINUTE(self));
+ return PyLong_FromLong(DATE_GET_MINUTE(self));
}
static PyObject *
datetime_second(PyDateTime_DateTime *self, void *unused)
{
- return PyLong_FromLong(DATE_GET_SECOND(self));
+ return PyLong_FromLong(DATE_GET_SECOND(self));
}
static PyObject *
datetime_microsecond(PyDateTime_DateTime *self, void *unused)
{
- return PyLong_FromLong(DATE_GET_MICROSECOND(self));
+ return PyLong_FromLong(DATE_GET_MICROSECOND(self));
}
static PyObject *
datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
{
- PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
- Py_INCREF(result);
- return result;
+ PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
+ Py_INCREF(result);
+ return result;
}
static PyGetSetDef datetime_getset[] = {
- {"hour", (getter)datetime_hour},
- {"minute", (getter)datetime_minute},
- {"second", (getter)datetime_second},
- {"microsecond", (getter)datetime_microsecond},
- {"tzinfo", (getter)datetime_tzinfo},
- {NULL}
+ {"hour", (getter)datetime_hour},
+ {"minute", (getter)datetime_minute},
+ {"second", (getter)datetime_second},
+ {"microsecond", (getter)datetime_microsecond},
+ {"tzinfo", (getter)datetime_tzinfo},
+ {NULL}
};
/*
@@ -3738,72 +3738,72 @@ static PyGetSetDef datetime_getset[] = {
*/
static char *datetime_kws[] = {
- "year", "month", "day", "hour", "minute", "second",
- "microsecond", "tzinfo", NULL
+ "year", "month", "day", "hour", "minute", "second",
+ "microsecond", "tzinfo", NULL
};
static PyObject *
datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
- PyObject *state;
- int year;
- int month;
- int day;
- int hour = 0;
- int minute = 0;
- int second = 0;
- int usecond = 0;
- PyObject *tzinfo = Py_None;
-
- /* Check for invocation from pickle with __getstate__ state */
- if (PyTuple_GET_SIZE(args) >= 1 &&
- PyTuple_GET_SIZE(args) <= 2 &&
- PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
- MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
- {
- PyDateTime_DateTime *me;
- char aware;
-
- if (PyTuple_GET_SIZE(args) == 2) {
- tzinfo = PyTuple_GET_ITEM(args, 1);
- if (check_tzinfo_subclass(tzinfo) < 0) {
- PyErr_SetString(PyExc_TypeError, "bad "
- "tzinfo state arg");
- return NULL;
- }
- }
- aware = (char)(tzinfo != Py_None);
- me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
- if (me != NULL) {
- char *pdata = PyBytes_AS_STRING(state);
-
- memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
- me->hashcode = -1;
- me->hastzinfo = aware;
- if (aware) {
- Py_INCREF(tzinfo);
- me->tzinfo = tzinfo;
- }
- }
- return (PyObject *)me;
- }
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
- &year, &month, &day, &hour, &minute,
- &second, &usecond, &tzinfo)) {
- if (check_date_args(year, month, day) < 0)
- return NULL;
- if (check_time_args(hour, minute, second, usecond) < 0)
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
- self = new_datetime_ex(year, month, day,
- hour, minute, second, usecond,
- tzinfo, type);
- }
- return self;
+ PyObject *self = NULL;
+ PyObject *state;
+ int year;
+ int month;
+ int day;
+ int hour = 0;
+ int minute = 0;
+ int second = 0;
+ int usecond = 0;
+ PyObject *tzinfo = Py_None;
+
+ /* Check for invocation from pickle with __getstate__ state */
+ if (PyTuple_GET_SIZE(args) >= 1 &&
+ PyTuple_GET_SIZE(args) <= 2 &&
+ PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
+ MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
+ {
+ PyDateTime_DateTime *me;
+ char aware;
+
+ if (PyTuple_GET_SIZE(args) == 2) {
+ tzinfo = PyTuple_GET_ITEM(args, 1);
+ if (check_tzinfo_subclass(tzinfo) < 0) {
+ PyErr_SetString(PyExc_TypeError, "bad "
+ "tzinfo state arg");
+ return NULL;
+ }
+ }
+ aware = (char)(tzinfo != Py_None);
+ me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
+ if (me != NULL) {
+ char *pdata = PyBytes_AS_STRING(state);
+
+ memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
+ me->hashcode = -1;
+ me->hastzinfo = aware;
+ if (aware) {
+ Py_INCREF(tzinfo);
+ me->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)me;
+ }
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
+ &year, &month, &day, &hour, &minute,
+ &second, &usecond, &tzinfo)) {
+ if (check_date_args(year, month, day) < 0)
+ return NULL;
+ if (check_time_args(hour, minute, second, usecond) < 0)
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
+ self = new_datetime_ex(year, month, day,
+ hour, minute, second, usecond,
+ tzinfo, type);
+ }
+ return self;
}
/* TM_FUNC is the shared type of localtime() and gmtime(). */
@@ -3815,36 +3815,36 @@ typedef struct tm *(*TM_FUNC)(const time_t *timer);
*/
static PyObject *
datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
- PyObject *tzinfo)
-{
- struct tm *tm;
- PyObject *result = NULL;
-
- tm = f(&timet);
- if (tm) {
- /* The platform localtime/gmtime may insert leap seconds,
- * indicated by tm->tm_sec > 59. We don't care about them,
- * except to the extent that passing them on to the datetime
- * constructor would raise ValueError for a reason that
- * made no sense to the user.
- */
- if (tm->tm_sec > 59)
- tm->tm_sec = 59;
- result = PyObject_CallFunction(cls, "iiiiiiiO",
- tm->tm_year + 1900,
- tm->tm_mon + 1,
- tm->tm_mday,
- tm->tm_hour,
- tm->tm_min,
- tm->tm_sec,
- us,
- tzinfo);
- }
- else
- PyErr_SetString(PyExc_ValueError,
- "timestamp out of range for "
- "platform localtime()/gmtime() function");
- return result;
+ PyObject *tzinfo)
+{
+ struct tm *tm;
+ PyObject *result = NULL;
+
+ tm = f(&timet);
+ if (tm) {
+ /* The platform localtime/gmtime may insert leap seconds,
+ * indicated by tm->tm_sec > 59. We don't care about them,
+ * except to the extent that passing them on to the datetime
+ * constructor would raise ValueError for a reason that
+ * made no sense to the user.
+ */
+ if (tm->tm_sec > 59)
+ tm->tm_sec = 59;
+ result = PyObject_CallFunction(cls, "iiiiiiiO",
+ tm->tm_year + 1900,
+ tm->tm_mon + 1,
+ tm->tm_mday,
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec,
+ us,
+ tzinfo);
+ }
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "timestamp out of range for "
+ "platform localtime()/gmtime() function");
+ return result;
}
/* Internal helper.
@@ -3856,31 +3856,31 @@ datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
*/
static PyObject *
datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
- PyObject *tzinfo)
-{
- time_t timet;
- double fraction;
- int us;
-
- timet = _PyTime_DoubleToTimet(timestamp);
- if (timet == (time_t)-1 && PyErr_Occurred())
- return NULL;
- fraction = timestamp - (double)timet;
- us = (int)round_to_long(fraction * 1e6);
- if (us < 0) {
- /* Truncation towards zero is not what we wanted
- for negative numbers (Python's mod semantics) */
- timet -= 1;
- us += 1000000;
- }
- /* If timestamp is less than one microsecond smaller than a
- * full second, round up. Otherwise, ValueErrors are raised
- * for some floats. */
- if (us == 1000000) {
- timet += 1;
- us = 0;
- }
- return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
+ PyObject *tzinfo)
+{
+ time_t timet;
+ double fraction;
+ int us;
+
+ timet = _PyTime_DoubleToTimet(timestamp);
+ if (timet == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ fraction = timestamp - (double)timet;
+ us = (int)round_to_long(fraction * 1e6);
+ if (us < 0) {
+ /* Truncation towards zero is not what we wanted
+ for negative numbers (Python's mod semantics) */
+ timet -= 1;
+ us += 1000000;
+ }
+ /* If timestamp is less than one microsecond smaller than a
+ * full second, round up. Otherwise, ValueErrors are raised
+ * for some floats. */
+ if (us == 1000000) {
+ timet += 1;
+ us = 0;
+ }
+ return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
}
/* Internal helper.
@@ -3891,36 +3891,36 @@ static PyObject *
datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
{
#ifdef HAVE_GETTIMEOFDAY
- struct timeval t;
+ struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
- gettimeofday(&t);
+ gettimeofday(&t);
#else
- gettimeofday(&t, (struct timezone *)NULL);
+ gettimeofday(&t, (struct timezone *)NULL);
#endif
- return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
- tzinfo);
-
-#else /* ! HAVE_GETTIMEOFDAY */
- /* No flavor of gettimeofday exists on this platform. Python's
- * time.time() does a lot of other platform tricks to get the
- * best time it can on the platform, and we're not going to do
- * better than that (if we could, the better code would belong
- * in time.time()!) We're limited by the precision of a double,
- * though.
- */
- PyObject *time;
- double dtime;
-
- time = time_time();
- if (time == NULL)
- return NULL;
- dtime = PyFloat_AsDouble(time);
- Py_DECREF(time);
- if (dtime == -1.0 && PyErr_Occurred())
- return NULL;
- return datetime_from_timestamp(cls, f, dtime, tzinfo);
-#endif /* ! HAVE_GETTIMEOFDAY */
+ return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
+ tzinfo);
+
+#else /* ! HAVE_GETTIMEOFDAY */
+ /* No flavor of gettimeofday exists on this platform. Python's
+ * time.time() does a lot of other platform tricks to get the
+ * best time it can on the platform, and we're not going to do
+ * better than that (if we could, the better code would belong
+ * in time.time()!) We're limited by the precision of a double,
+ * though.
+ */
+ PyObject *time;
+ double dtime;
+
+ time = time_time();
+ if (time == NULL)
+ return NULL;
+ dtime = PyFloat_AsDouble(time);
+ Py_DECREF(time);
+ if (dtime == -1.0 && PyErr_Occurred())
+ return NULL;
+ return datetime_from_timestamp(cls, f, dtime, tzinfo);
+#endif /* ! HAVE_GETTIMEOFDAY */
}
/* Return best possible local time -- this isn't constrained by the
@@ -3929,26 +3929,26 @@ datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
static PyObject *
datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
{
- PyObject *self;
- PyObject *tzinfo = Py_None;
- static char *keywords[] = {"tz", NULL};
+ PyObject *self;
+ PyObject *tzinfo = Py_None;
+ static char *keywords[] = {"tz", NULL};
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
- &tzinfo))
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
+ &tzinfo))
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
- self = datetime_best_possible(cls,
- tzinfo == Py_None ? localtime : gmtime,
- tzinfo);
- if (self != NULL && tzinfo != Py_None) {
- /* Convert UTC to tzinfo's zone. */
- PyObject *temp = self;
- self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
- Py_DECREF(temp);
- }
- return self;
+ self = datetime_best_possible(cls,
+ tzinfo == Py_None ? localtime : gmtime,
+ tzinfo);
+ if (self != NULL && tzinfo != Py_None) {
+ /* Convert UTC to tzinfo's zone. */
+ PyObject *temp = self;
+ self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
+ Py_DECREF(temp);
+ }
+ return self;
}
/* Return best possible UTC time -- this isn't constrained by the
@@ -3957,155 +3957,155 @@ datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
static PyObject *
datetime_utcnow(PyObject *cls, PyObject *dummy)
{
- return datetime_best_possible(cls, gmtime, Py_None);
+ return datetime_best_possible(cls, gmtime, Py_None);
}
/* Return new local datetime from timestamp (Python timestamp -- a double). */
static PyObject *
datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
{
- PyObject *self;
- double timestamp;
- PyObject *tzinfo = Py_None;
- static char *keywords[] = {"timestamp", "tz", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
- keywords, &timestamp, &tzinfo))
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
-
- self = datetime_from_timestamp(cls,
- tzinfo == Py_None ? localtime : gmtime,
- timestamp,
- tzinfo);
- if (self != NULL && tzinfo != Py_None) {
- /* Convert UTC to tzinfo's zone. */
- PyObject *temp = self;
- self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
- Py_DECREF(temp);
- }
- return self;
+ PyObject *self;
+ double timestamp;
+ PyObject *tzinfo = Py_None;
+ static char *keywords[] = {"timestamp", "tz", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
+ keywords, &timestamp, &tzinfo))
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
+
+ self = datetime_from_timestamp(cls,
+ tzinfo == Py_None ? localtime : gmtime,
+ timestamp,
+ tzinfo);
+ if (self != NULL && tzinfo != Py_None) {
+ /* Convert UTC to tzinfo's zone. */
+ PyObject *temp = self;
+ self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
+ Py_DECREF(temp);
+ }
+ return self;
}
/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
static PyObject *
datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
{
- double timestamp;
- PyObject *result = NULL;
+ double timestamp;
+ PyObject *result = NULL;
- if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
- result = datetime_from_timestamp(cls, gmtime, timestamp,
- Py_None);
- return result;
+ if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
+ result = datetime_from_timestamp(cls, gmtime, timestamp,
+ Py_None);
+ return result;
}
/* Return new datetime from time.strptime(). */
static PyObject *
datetime_strptime(PyObject *cls, PyObject *args)
{
- static PyObject *module = NULL;
- PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
- const Py_UNICODE *string, *format;
-
- if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
- return NULL;
-
- if (module == NULL &&
- (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
- return NULL;
-
- /* _strptime._strptime returns a two-element tuple. The first
- element is a time.struct_time object. The second is the
- microseconds (which are not defined for time.struct_time). */
- obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
- if (obj != NULL) {
- int i, good_timetuple = 1;
- long int ia[7];
- if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
- st = PySequence_GetItem(obj, 0);
- frac = PySequence_GetItem(obj, 1);
- if (st == NULL || frac == NULL)
- good_timetuple = 0;
- /* copy y/m/d/h/m/s values out of the
- time.struct_time */
- if (good_timetuple &&
- PySequence_Check(st) &&
- PySequence_Size(st) >= 6) {
- for (i=0; i < 6; i++) {
- PyObject *p = PySequence_GetItem(st, i);
- if (p == NULL) {
- good_timetuple = 0;
- break;
- }
- if (PyLong_Check(p))
- ia[i] = PyLong_AsLong(p);
- else
- good_timetuple = 0;
- Py_DECREF(p);
- }
-/* if (PyLong_CheckExact(p)) {
- ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
- if (overflow)
- good_timetuple = 0;
- }
- else
- good_timetuple = 0;
- Py_DECREF(p);
-*/ }
- else
- good_timetuple = 0;
- /* follow that up with a little dose of microseconds */
- if (PyLong_Check(frac))
- ia[6] = PyLong_AsLong(frac);
- else
- good_timetuple = 0;
- }
- else
- good_timetuple = 0;
- if (good_timetuple)
- result = PyObject_CallFunction(cls, "iiiiiii",
- ia[0], ia[1], ia[2],
- ia[3], ia[4], ia[5],
- ia[6]);
- else
- PyErr_SetString(PyExc_ValueError,
- "unexpected value from _strptime._strptime");
- }
- Py_XDECREF(obj);
- Py_XDECREF(st);
- Py_XDECREF(frac);
- return result;
+ static PyObject *module = NULL;
+ PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
+ const Py_UNICODE *string, *format;
+
+ if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
+ return NULL;
+
+ if (module == NULL &&
+ (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
+ return NULL;
+
+ /* _strptime._strptime returns a two-element tuple. The first
+ element is a time.struct_time object. The second is the
+ microseconds (which are not defined for time.struct_time). */
+ obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
+ if (obj != NULL) {
+ int i, good_timetuple = 1;
+ long int ia[7];
+ if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
+ st = PySequence_GetItem(obj, 0);
+ frac = PySequence_GetItem(obj, 1);
+ if (st == NULL || frac == NULL)
+ good_timetuple = 0;
+ /* copy y/m/d/h/m/s values out of the
+ time.struct_time */
+ if (good_timetuple &&
+ PySequence_Check(st) &&
+ PySequence_Size(st) >= 6) {
+ for (i=0; i < 6; i++) {
+ PyObject *p = PySequence_GetItem(st, i);
+ if (p == NULL) {
+ good_timetuple = 0;
+ break;
+ }
+ if (PyLong_Check(p))
+ ia[i] = PyLong_AsLong(p);
+ else
+ good_timetuple = 0;
+ Py_DECREF(p);
+ }
+/* if (PyLong_CheckExact(p)) {
+ ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
+ if (overflow)
+ good_timetuple = 0;
+ }
+ else
+ good_timetuple = 0;
+ Py_DECREF(p);
+*/ }
+ else
+ good_timetuple = 0;
+ /* follow that up with a little dose of microseconds */
+ if (PyLong_Check(frac))
+ ia[6] = PyLong_AsLong(frac);
+ else
+ good_timetuple = 0;
+ }
+ else
+ good_timetuple = 0;
+ if (good_timetuple)
+ result = PyObject_CallFunction(cls, "iiiiiii",
+ ia[0], ia[1], ia[2],
+ ia[3], ia[4], ia[5],
+ ia[6]);
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "unexpected value from _strptime._strptime");
+ }
+ Py_XDECREF(obj);
+ Py_XDECREF(st);
+ Py_XDECREF(frac);
+ return result;
}
/* Return new datetime from date/datetime and time arguments. */
static PyObject *
datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
{
- static char *keywords[] = {"date", "time", NULL};
- PyObject *date;
- PyObject *time;
- PyObject *result = NULL;
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
- &PyDateTime_DateType, &date,
- &PyDateTime_TimeType, &time)) {
- PyObject *tzinfo = Py_None;
-
- if (HASTZINFO(time))
- tzinfo = ((PyDateTime_Time *)time)->tzinfo;
- result = PyObject_CallFunction(cls, "iiiiiiiO",
- GET_YEAR(date),
- GET_MONTH(date),
- GET_DAY(date),
- TIME_GET_HOUR(time),
- TIME_GET_MINUTE(time),
- TIME_GET_SECOND(time),
- TIME_GET_MICROSECOND(time),
- tzinfo);
- }
- return result;
+ static char *keywords[] = {"date", "time", NULL};
+ PyObject *date;
+ PyObject *time;
+ PyObject *result = NULL;
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
+ &PyDateTime_DateType, &date,
+ &PyDateTime_TimeType, &time)) {
+ PyObject *tzinfo = Py_None;
+
+ if (HASTZINFO(time))
+ tzinfo = ((PyDateTime_Time *)time)->tzinfo;
+ result = PyObject_CallFunction(cls, "iiiiiiiO",
+ GET_YEAR(date),
+ GET_MONTH(date),
+ GET_DAY(date),
+ TIME_GET_HOUR(time),
+ TIME_GET_MINUTE(time),
+ TIME_GET_SECOND(time),
+ TIME_GET_MICROSECOND(time),
+ tzinfo);
+ }
+ return result;
}
/*
@@ -4115,10 +4115,10 @@ datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
static void
datetime_dealloc(PyDateTime_DateTime *self)
{
- if (HASTZINFO(self)) {
- Py_XDECREF(self->tzinfo);
- }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ if (HASTZINFO(self)) {
+ Py_XDECREF(self->tzinfo);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
/*
@@ -4128,20 +4128,20 @@ datetime_dealloc(PyDateTime_DateTime *self)
/* These are all METH_NOARGS, so don't need to check the arglist. */
static PyObject *
datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "utcoffset", (PyObject *)self);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "utcoffset", (PyObject *)self);
}
static PyObject *
datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "dst", (PyObject *)self);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "dst", (PyObject *)self);
}
static PyObject *
datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
- return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
- (PyObject *)self);
+ return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
+ (PyObject *)self);
}
/*
@@ -4153,112 +4153,112 @@ datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
*/
static PyObject *
add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
- int factor)
-{
- /* Note that the C-level additions can't overflow, because of
- * invariant bounds on the member values.
- */
- int year = GET_YEAR(date);
- int month = GET_MONTH(date);
- int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
- int hour = DATE_GET_HOUR(date);
- int minute = DATE_GET_MINUTE(date);
- int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
- int microsecond = DATE_GET_MICROSECOND(date) +
- GET_TD_MICROSECONDS(delta) * factor;
-
- assert(factor == 1 || factor == -1);
- if (normalize_datetime(&year, &month, &day,
- &hour, &minute, &second, &microsecond) < 0)
- return NULL;
- else
- return new_datetime(year, month, day,
- hour, minute, second, microsecond,
- HASTZINFO(date) ? date->tzinfo : Py_None);
+ int factor)
+{
+ /* Note that the C-level additions can't overflow, because of
+ * invariant bounds on the member values.
+ */
+ int year = GET_YEAR(date);
+ int month = GET_MONTH(date);
+ int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
+ int hour = DATE_GET_HOUR(date);
+ int minute = DATE_GET_MINUTE(date);
+ int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
+ int microsecond = DATE_GET_MICROSECOND(date) +
+ GET_TD_MICROSECONDS(delta) * factor;
+
+ assert(factor == 1 || factor == -1);
+ if (normalize_datetime(&year, &month, &day,
+ &hour, &minute, &second, &microsecond) < 0)
+ return NULL;
+ else
+ return new_datetime(year, month, day,
+ hour, minute, second, microsecond,
+ HASTZINFO(date) ? date->tzinfo : Py_None);
}
static PyObject *
datetime_add(PyObject *left, PyObject *right)
{
- if (PyDateTime_Check(left)) {
- /* datetime + ??? */
- if (PyDelta_Check(right))
- /* datetime + delta */
- return add_datetime_timedelta(
- (PyDateTime_DateTime *)left,
- (PyDateTime_Delta *)right,
- 1);
- }
- else if (PyDelta_Check(left)) {
- /* delta + datetime */
- return add_datetime_timedelta((PyDateTime_DateTime *) right,
- (PyDateTime_Delta *) left,
- 1);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (PyDateTime_Check(left)) {
+ /* datetime + ??? */
+ if (PyDelta_Check(right))
+ /* datetime + delta */
+ return add_datetime_timedelta(
+ (PyDateTime_DateTime *)left,
+ (PyDateTime_Delta *)right,
+ 1);
+ }
+ else if (PyDelta_Check(left)) {
+ /* delta + datetime */
+ return add_datetime_timedelta((PyDateTime_DateTime *) right,
+ (PyDateTime_Delta *) left,
+ 1);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyObject *
datetime_subtract(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
-
- if (PyDateTime_Check(left)) {
- /* datetime - ??? */
- if (PyDateTime_Check(right)) {
- /* datetime - datetime */
- naivety n1, n2;
- int offset1, offset2;
- int delta_d, delta_s, delta_us;
-
- if (classify_two_utcoffsets(left, &offset1, &n1, left,
- right, &offset2, &n2,
- right) < 0)
- return NULL;
- assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
- if (n1 != n2) {
- PyErr_SetString(PyExc_TypeError,
- "can't subtract offset-naive and "
- "offset-aware datetimes");
- return NULL;
- }
- delta_d = ymd_to_ord(GET_YEAR(left),
- GET_MONTH(left),
- GET_DAY(left)) -
- ymd_to_ord(GET_YEAR(right),
- GET_MONTH(right),
- GET_DAY(right));
- /* These can't overflow, since the values are
- * normalized. At most this gives the number of
- * seconds in one day.
- */
- delta_s = (DATE_GET_HOUR(left) -
- DATE_GET_HOUR(right)) * 3600 +
- (DATE_GET_MINUTE(left) -
- DATE_GET_MINUTE(right)) * 60 +
- (DATE_GET_SECOND(left) -
- DATE_GET_SECOND(right));
- delta_us = DATE_GET_MICROSECOND(left) -
- DATE_GET_MICROSECOND(right);
- /* (left - offset1) - (right - offset2) =
- * (left - right) + (offset2 - offset1)
- */
- delta_s += (offset2 - offset1) * 60;
- result = new_delta(delta_d, delta_s, delta_us, 1);
- }
- else if (PyDelta_Check(right)) {
- /* datetime - delta */
- result = add_datetime_timedelta(
- (PyDateTime_DateTime *)left,
- (PyDateTime_Delta *)right,
- -1);
- }
- }
-
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ PyObject *result = Py_NotImplemented;
+
+ if (PyDateTime_Check(left)) {
+ /* datetime - ??? */
+ if (PyDateTime_Check(right)) {
+ /* datetime - datetime */
+ naivety n1, n2;
+ int offset1, offset2;
+ int delta_d, delta_s, delta_us;
+
+ if (classify_two_utcoffsets(left, &offset1, &n1, left,
+ right, &offset2, &n2,
+ right) < 0)
+ return NULL;
+ assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+ if (n1 != n2) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't subtract offset-naive and "
+ "offset-aware datetimes");
+ return NULL;
+ }
+ delta_d = ymd_to_ord(GET_YEAR(left),
+ GET_MONTH(left),
+ GET_DAY(left)) -
+ ymd_to_ord(GET_YEAR(right),
+ GET_MONTH(right),
+ GET_DAY(right));
+ /* These can't overflow, since the values are
+ * normalized. At most this gives the number of
+ * seconds in one day.
+ */
+ delta_s = (DATE_GET_HOUR(left) -
+ DATE_GET_HOUR(right)) * 3600 +
+ (DATE_GET_MINUTE(left) -
+ DATE_GET_MINUTE(right)) * 60 +
+ (DATE_GET_SECOND(left) -
+ DATE_GET_SECOND(right));
+ delta_us = DATE_GET_MICROSECOND(left) -
+ DATE_GET_MICROSECOND(right);
+ /* (left - offset1) - (right - offset2) =
+ * (left - right) + (offset2 - offset1)
+ */
+ delta_s += (offset2 - offset1) * 60;
+ result = new_delta(delta_d, delta_s, delta_us, 1);
+ }
+ else if (PyDelta_Check(right)) {
+ /* datetime - delta */
+ result = add_datetime_timedelta(
+ (PyDateTime_DateTime *)left,
+ (PyDateTime_Delta *)right,
+ -1);
+ }
+ }
+
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
/* Various ways to turn a datetime into a string. */
@@ -4266,88 +4266,88 @@ datetime_subtract(PyObject *left, PyObject *right)
static PyObject *
datetime_repr(PyDateTime_DateTime *self)
{
- const char *type_name = Py_TYPE(self)->tp_name;
- PyObject *baserepr;
-
- if (DATE_GET_MICROSECOND(self)) {
- baserepr = PyUnicode_FromFormat(
- "%s(%d, %d, %d, %d, %d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- DATE_GET_MICROSECOND(self));
- }
- else if (DATE_GET_SECOND(self)) {
- baserepr = PyUnicode_FromFormat(
- "%s(%d, %d, %d, %d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self));
- }
- else {
- baserepr = PyUnicode_FromFormat(
- "%s(%d, %d, %d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
- }
- if (baserepr == NULL || ! HASTZINFO(self))
- return baserepr;
- return append_keyword_tzinfo(baserepr, self->tzinfo);
+ const char *type_name = Py_TYPE(self)->tp_name;
+ PyObject *baserepr;
+
+ if (DATE_GET_MICROSECOND(self)) {
+ baserepr = PyUnicode_FromFormat(
+ "%s(%d, %d, %d, %d, %d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ DATE_GET_MICROSECOND(self));
+ }
+ else if (DATE_GET_SECOND(self)) {
+ baserepr = PyUnicode_FromFormat(
+ "%s(%d, %d, %d, %d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self));
+ }
+ else {
+ baserepr = PyUnicode_FromFormat(
+ "%s(%d, %d, %d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
+ }
+ if (baserepr == NULL || ! HASTZINFO(self))
+ return baserepr;
+ return append_keyword_tzinfo(baserepr, self->tzinfo);
}
static PyObject *
datetime_str(PyDateTime_DateTime *self)
{
- return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
+ return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
}
static PyObject *
datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
{
- int sep = 'T';
- static char *keywords[] = {"sep", NULL};
- char buffer[100];
- PyObject *result;
- int us = DATE_GET_MICROSECOND(self);
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
- return NULL;
- if (us)
- result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
- GET_YEAR(self), GET_MONTH(self),
- GET_DAY(self), (int)sep,
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self), us);
- else
- result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
- GET_YEAR(self), GET_MONTH(self),
- GET_DAY(self), (int)sep,
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self));
-
- if (!result || !HASTZINFO(self))
- return result;
-
- /* We need to append the UTC offset. */
- if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
- (PyObject *)self) < 0) {
- Py_DECREF(result);
- return NULL;
- }
- PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
- return result;
+ int sep = 'T';
+ static char *keywords[] = {"sep", NULL};
+ char buffer[100];
+ PyObject *result;
+ int us = DATE_GET_MICROSECOND(self);
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
+ return NULL;
+ if (us)
+ result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
+ GET_YEAR(self), GET_MONTH(self),
+ GET_DAY(self), (int)sep,
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self), us);
+ else
+ result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
+ GET_YEAR(self), GET_MONTH(self),
+ GET_DAY(self), (int)sep,
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self));
+
+ if (!result || !HASTZINFO(self))
+ return result;
+
+ /* We need to append the UTC offset. */
+ if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
+ (PyObject *)self) < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
+ return result;
}
static PyObject *
datetime_ctime(PyDateTime_DateTime *self)
{
- return format_ctime((PyDateTime_Date *)self,
- DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self));
+ return format_ctime((PyDateTime_Date *)self,
+ DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self));
}
/* Miscellaneous methods. */
@@ -4355,292 +4355,292 @@ datetime_ctime(PyDateTime_DateTime *self)
static PyObject *
datetime_richcompare(PyObject *self, PyObject *other, int op)
{
- int diff;
- naivety n1, n2;
- int offset1, offset2;
-
- if (! PyDateTime_Check(other)) {
- if (PyDate_Check(other)) {
- /* Prevent invocation of date_richcompare. We want to
- return NotImplemented here to give the other object
- a chance. But since DateTime is a subclass of
- Date, if the other object is a Date, it would
- compute an ordering based on the date part alone,
- and we don't want that. So force unequal or
- uncomparable here in that case. */
- if (op == Py_EQ)
- Py_RETURN_FALSE;
- if (op == Py_NE)
- Py_RETURN_TRUE;
- return cmperror(self, other);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- if (classify_two_utcoffsets(self, &offset1, &n1, self,
- other, &offset2, &n2, other) < 0)
- return NULL;
- assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
- /* If they're both naive, or both aware and have the same offsets,
- * we get off cheap. Note that if they're both naive, offset1 ==
- * offset2 == 0 at this point.
- */
- if (n1 == n2 && offset1 == offset2) {
- diff = memcmp(((PyDateTime_DateTime *)self)->data,
- ((PyDateTime_DateTime *)other)->data,
- _PyDateTime_DATETIME_DATASIZE);
- return diff_to_bool(diff, op);
- }
-
- if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
- PyDateTime_Delta *delta;
-
- assert(offset1 != offset2); /* else last "if" handled it */
- delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
- other);
- if (delta == NULL)
- return NULL;
- diff = GET_TD_DAYS(delta);
- if (diff == 0)
- diff = GET_TD_SECONDS(delta) |
- GET_TD_MICROSECONDS(delta);
- Py_DECREF(delta);
- return diff_to_bool(diff, op);
- }
-
- assert(n1 != n2);
- PyErr_SetString(PyExc_TypeError,
- "can't compare offset-naive and "
- "offset-aware datetimes");
- return NULL;
+ int diff;
+ naivety n1, n2;
+ int offset1, offset2;
+
+ if (! PyDateTime_Check(other)) {
+ if (PyDate_Check(other)) {
+ /* Prevent invocation of date_richcompare. We want to
+ return NotImplemented here to give the other object
+ a chance. But since DateTime is a subclass of
+ Date, if the other object is a Date, it would
+ compute an ordering based on the date part alone,
+ and we don't want that. So force unequal or
+ uncomparable here in that case. */
+ if (op == Py_EQ)
+ Py_RETURN_FALSE;
+ if (op == Py_NE)
+ Py_RETURN_TRUE;
+ return cmperror(self, other);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ if (classify_two_utcoffsets(self, &offset1, &n1, self,
+ other, &offset2, &n2, other) < 0)
+ return NULL;
+ assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+ /* If they're both naive, or both aware and have the same offsets,
+ * we get off cheap. Note that if they're both naive, offset1 ==
+ * offset2 == 0 at this point.
+ */
+ if (n1 == n2 && offset1 == offset2) {
+ diff = memcmp(((PyDateTime_DateTime *)self)->data,
+ ((PyDateTime_DateTime *)other)->data,
+ _PyDateTime_DATETIME_DATASIZE);
+ return diff_to_bool(diff, op);
+ }
+
+ if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
+ PyDateTime_Delta *delta;
+
+ assert(offset1 != offset2); /* else last "if" handled it */
+ delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
+ other);
+ if (delta == NULL)
+ return NULL;
+ diff = GET_TD_DAYS(delta);
+ if (diff == 0)
+ diff = GET_TD_SECONDS(delta) |
+ GET_TD_MICROSECONDS(delta);
+ Py_DECREF(delta);
+ return diff_to_bool(diff, op);
+ }
+
+ assert(n1 != n2);
+ PyErr_SetString(PyExc_TypeError,
+ "can't compare offset-naive and "
+ "offset-aware datetimes");
+ return NULL;
}
static long
datetime_hash(PyDateTime_DateTime *self)
{
- if (self->hashcode == -1) {
- naivety n;
- int offset;
- PyObject *temp;
-
- n = classify_utcoffset((PyObject *)self, (PyObject *)self,
- &offset);
- assert(n != OFFSET_UNKNOWN);
- if (n == OFFSET_ERROR)
- return -1;
-
- /* Reduce this to a hash of another object. */
- if (n == OFFSET_NAIVE) {
- self->hashcode = generic_hash(
- (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
- return self->hashcode;
- }
- else {
- int days;
- int seconds;
-
- assert(n == OFFSET_AWARE);
- assert(HASTZINFO(self));
- days = ymd_to_ord(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self));
- seconds = DATE_GET_HOUR(self) * 3600 +
- (DATE_GET_MINUTE(self) - offset) * 60 +
- DATE_GET_SECOND(self);
- temp = new_delta(days,
- seconds,
- DATE_GET_MICROSECOND(self),
- 1);
- }
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ naivety n;
+ int offset;
+ PyObject *temp;
+
+ n = classify_utcoffset((PyObject *)self, (PyObject *)self,
+ &offset);
+ assert(n != OFFSET_UNKNOWN);
+ if (n == OFFSET_ERROR)
+ return -1;
+
+ /* Reduce this to a hash of another object. */
+ if (n == OFFSET_NAIVE) {
+ self->hashcode = generic_hash(
+ (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
+ return self->hashcode;
+ }
+ else {
+ int days;
+ int seconds;
+
+ assert(n == OFFSET_AWARE);
+ assert(HASTZINFO(self));
+ days = ymd_to_ord(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self));
+ seconds = DATE_GET_HOUR(self) * 3600 +
+ (DATE_GET_MINUTE(self) - offset) * 60 +
+ DATE_GET_SECOND(self);
+ temp = new_delta(days,
+ seconds,
+ DATE_GET_MICROSECOND(self),
+ 1);
+ }
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
{
- PyObject *clone;
- PyObject *tuple;
- int y = GET_YEAR(self);
- int m = GET_MONTH(self);
- int d = GET_DAY(self);
- int hh = DATE_GET_HOUR(self);
- int mm = DATE_GET_MINUTE(self);
- int ss = DATE_GET_SECOND(self);
- int us = DATE_GET_MICROSECOND(self);
- PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
- datetime_kws,
- &y, &m, &d, &hh, &mm, &ss, &us,
- &tzinfo))
- return NULL;
- tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
- if (tuple == NULL)
- return NULL;
- clone = datetime_new(Py_TYPE(self), tuple, NULL);
- Py_DECREF(tuple);
- return clone;
+ PyObject *clone;
+ PyObject *tuple;
+ int y = GET_YEAR(self);
+ int m = GET_MONTH(self);
+ int d = GET_DAY(self);
+ int hh = DATE_GET_HOUR(self);
+ int mm = DATE_GET_MINUTE(self);
+ int ss = DATE_GET_SECOND(self);
+ int us = DATE_GET_MICROSECOND(self);
+ PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
+ datetime_kws,
+ &y, &m, &d, &hh, &mm, &ss, &us,
+ &tzinfo))
+ return NULL;
+ tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
+ if (tuple == NULL)
+ return NULL;
+ clone = datetime_new(Py_TYPE(self), tuple, NULL);
+ Py_DECREF(tuple);
+ return clone;
}
static PyObject *
datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
{
- int y, m, d, hh, mm, ss, us;
- PyObject *result;
- int offset, none;
-
- PyObject *tzinfo;
- static char *keywords[] = {"tz", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
- &PyDateTime_TZInfoType, &tzinfo))
- return NULL;
-
- if (!HASTZINFO(self) || self->tzinfo == Py_None)
- goto NeedAware;
-
- /* Conversion to self's own time zone is a NOP. */
- if (self->tzinfo == tzinfo) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
-
- /* Convert self to UTC. */
- offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
- if (none)
- goto NeedAware;
-
- y = GET_YEAR(self);
- m = GET_MONTH(self);
- d = GET_DAY(self);
- hh = DATE_GET_HOUR(self);
- mm = DATE_GET_MINUTE(self);
- ss = DATE_GET_SECOND(self);
- us = DATE_GET_MICROSECOND(self);
-
- mm -= offset;
- if ((mm < 0 || mm >= 60) &&
- normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
- return NULL;
-
- /* Attach new tzinfo and let fromutc() do the rest. */
- result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
- if (result != NULL) {
- PyObject *temp = result;
-
- result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
- Py_DECREF(temp);
- }
- return result;
+ int y, m, d, hh, mm, ss, us;
+ PyObject *result;
+ int offset, none;
+
+ PyObject *tzinfo;
+ static char *keywords[] = {"tz", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
+ &PyDateTime_TZInfoType, &tzinfo))
+ return NULL;
+
+ if (!HASTZINFO(self) || self->tzinfo == Py_None)
+ goto NeedAware;
+
+ /* Conversion to self's own time zone is a NOP. */
+ if (self->tzinfo == tzinfo) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+
+ /* Convert self to UTC. */
+ offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+ if (none)
+ goto NeedAware;
+
+ y = GET_YEAR(self);
+ m = GET_MONTH(self);
+ d = GET_DAY(self);
+ hh = DATE_GET_HOUR(self);
+ mm = DATE_GET_MINUTE(self);
+ ss = DATE_GET_SECOND(self);
+ us = DATE_GET_MICROSECOND(self);
+
+ mm -= offset;
+ if ((mm < 0 || mm >= 60) &&
+ normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+ return NULL;
+
+ /* Attach new tzinfo and let fromutc() do the rest. */
+ result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
+ if (result != NULL) {
+ PyObject *temp = result;
+
+ result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
+ Py_DECREF(temp);
+ }
+ return result;
NeedAware:
- PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
- "a naive datetime");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
+ "a naive datetime");
+ return NULL;
}
static PyObject *
datetime_timetuple(PyDateTime_DateTime *self)
{
- int dstflag = -1;
+ int dstflag = -1;
- if (HASTZINFO(self) && self->tzinfo != Py_None) {
- int none;
+ if (HASTZINFO(self) && self->tzinfo != Py_None) {
+ int none;
- dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
- if (dstflag == -1 && PyErr_Occurred())
- return NULL;
+ dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
+ if (dstflag == -1 && PyErr_Occurred())
+ return NULL;
- if (none)
- dstflag = -1;
- else if (dstflag != 0)
- dstflag = 1;
+ if (none)
+ dstflag = -1;
+ else if (dstflag != 0)
+ dstflag = 1;
- }
- return build_struct_time(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self),
- DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- dstflag);
+ }
+ return build_struct_time(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self),
+ DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ dstflag);
}
static PyObject *
datetime_getdate(PyDateTime_DateTime *self)
{
- return new_date(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self));
+ return new_date(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self));
}
static PyObject *
datetime_gettime(PyDateTime_DateTime *self)
{
- return new_time(DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- DATE_GET_MICROSECOND(self),
- Py_None);
+ return new_time(DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ DATE_GET_MICROSECOND(self),
+ Py_None);
}
static PyObject *
datetime_gettimetz(PyDateTime_DateTime *self)
{
- return new_time(DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- DATE_GET_MICROSECOND(self),
- HASTZINFO(self) ? self->tzinfo : Py_None);
+ return new_time(DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ DATE_GET_MICROSECOND(self),
+ HASTZINFO(self) ? self->tzinfo : Py_None);
}
static PyObject *
datetime_utctimetuple(PyDateTime_DateTime *self)
{
- int y = GET_YEAR(self);
- int m = GET_MONTH(self);
- int d = GET_DAY(self);
- int hh = DATE_GET_HOUR(self);
- int mm = DATE_GET_MINUTE(self);
- int ss = DATE_GET_SECOND(self);
- int us = 0; /* microseconds are ignored in a timetuple */
- int offset = 0;
-
- if (HASTZINFO(self) && self->tzinfo != Py_None) {
- int none;
-
- offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
- }
- /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
- * 0 in a UTC timetuple regardless of what dst() says.
- */
- if (offset) {
- /* Subtract offset minutes & normalize. */
- int stat;
-
- mm -= offset;
- stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
- if (stat < 0) {
- /* At the edges, it's possible we overflowed
- * beyond MINYEAR or MAXYEAR.
- */
- if (PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_Clear();
- else
- return NULL;
- }
- }
- return build_struct_time(y, m, d, hh, mm, ss, 0);
+ int y = GET_YEAR(self);
+ int m = GET_MONTH(self);
+ int d = GET_DAY(self);
+ int hh = DATE_GET_HOUR(self);
+ int mm = DATE_GET_MINUTE(self);
+ int ss = DATE_GET_SECOND(self);
+ int us = 0; /* microseconds are ignored in a timetuple */
+ int offset = 0;
+
+ if (HASTZINFO(self) && self->tzinfo != Py_None) {
+ int none;
+
+ offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
+ * 0 in a UTC timetuple regardless of what dst() says.
+ */
+ if (offset) {
+ /* Subtract offset minutes & normalize. */
+ int stat;
+
+ mm -= offset;
+ stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
+ if (stat < 0) {
+ /* At the edges, it's possible we overflowed
+ * beyond MINYEAR or MAXYEAR.
+ */
+ if (PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ }
+ return build_struct_time(y, m, d, hh, mm, ss, 0);
}
/* Pickle support, a simple use of __reduce__. */
@@ -4653,102 +4653,102 @@ datetime_utctimetuple(PyDateTime_DateTime *self)
static PyObject *
datetime_getstate(PyDateTime_DateTime *self)
{
- PyObject *basestate;
- PyObject *result = NULL;
+ PyObject *basestate;
+ PyObject *result = NULL;
- basestate = PyBytes_FromStringAndSize((char *)self->data,
- _PyDateTime_DATETIME_DATASIZE);
- if (basestate != NULL) {
- if (! HASTZINFO(self) || self->tzinfo == Py_None)
- result = PyTuple_Pack(1, basestate);
- else
- result = PyTuple_Pack(2, basestate, self->tzinfo);
- Py_DECREF(basestate);
- }
- return result;
+ basestate = PyBytes_FromStringAndSize((char *)self->data,
+ _PyDateTime_DATETIME_DATASIZE);
+ if (basestate != NULL) {
+ if (! HASTZINFO(self) || self->tzinfo == Py_None)
+ result = PyTuple_Pack(1, basestate);
+ else
+ result = PyTuple_Pack(2, basestate, self->tzinfo);
+ Py_DECREF(basestate);
+ }
+ return result;
}
static PyObject *
datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
{
- return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
+ return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
}
static PyMethodDef datetime_methods[] = {
- /* Class methods: */
+ /* Class methods: */
- {"now", (PyCFunction)datetime_now,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
+ {"now", (PyCFunction)datetime_now,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
- {"utcnow", (PyCFunction)datetime_utcnow,
- METH_NOARGS | METH_CLASS,
- PyDoc_STR("Return a new datetime representing UTC day and time.")},
+ {"utcnow", (PyCFunction)datetime_utcnow,
+ METH_NOARGS | METH_CLASS,
+ PyDoc_STR("Return a new datetime representing UTC day and time.")},
- {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
+ {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
- {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
- METH_VARARGS | METH_CLASS,
- PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
- "(like time.time()).")},
+ {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
+ METH_VARARGS | METH_CLASS,
+ PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
+ "(like time.time()).")},
- {"strptime", (PyCFunction)datetime_strptime,
- METH_VARARGS | METH_CLASS,
- PyDoc_STR("string, format -> new datetime parsed from a string "
- "(like time.strptime()).")},
+ {"strptime", (PyCFunction)datetime_strptime,
+ METH_VARARGS | METH_CLASS,
+ PyDoc_STR("string, format -> new datetime parsed from a string "
+ "(like time.strptime()).")},
- {"combine", (PyCFunction)datetime_combine,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("date, time -> datetime with same date and time fields")},
+ {"combine", (PyCFunction)datetime_combine,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("date, time -> datetime with same date and time fields")},
- /* Instance methods: */
+ /* Instance methods: */
- {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
- PyDoc_STR("Return date object with same year, month and day.")},
+ {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
+ PyDoc_STR("Return date object with same year, month and day.")},
- {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
- PyDoc_STR("Return time object with same time but with tzinfo=None.")},
+ {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
+ PyDoc_STR("Return time object with same time but with tzinfo=None.")},
- {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
- PyDoc_STR("Return time object with same time and tzinfo.")},
+ {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
+ PyDoc_STR("Return time object with same time and tzinfo.")},
- {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
- PyDoc_STR("Return ctime() style string.")},
+ {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
+ PyDoc_STR("Return ctime() style string.")},
- {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
- PyDoc_STR("Return time tuple, compatible with time.localtime().")},
+ {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
+ PyDoc_STR("Return time tuple, compatible with time.localtime().")},
- {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
- PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
+ {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
+ PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
- {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("[sep] -> string in ISO 8601 format, "
- "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
- "sep is used to separate the year from the time, and "
- "defaults to 'T'.")},
+ {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("[sep] -> string in ISO 8601 format, "
+ "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
+ "sep is used to separate the year from the time, and "
+ "defaults to 'T'.")},
- {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
+ {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
- {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.tzname(self).")},
+ {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.tzname(self).")},
- {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.dst(self).")},
+ {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.dst(self).")},
- {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("Return datetime with new specified fields.")},
+ {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("Return datetime with new specified fields.")},
- {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
+ {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
- {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char datetime_doc[] =
@@ -4758,58 +4758,58 @@ The year, month and day arguments are required. tzinfo may be None, or an\n\
instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
static PyNumberMethods datetime_as_number = {
- datetime_add, /* nb_add */
- datetime_subtract, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_bool */
+ datetime_add, /* nb_add */
+ datetime_subtract, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_bool */
};
static PyTypeObject PyDateTime_DateTimeType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.datetime", /* tp_name */
- sizeof(PyDateTime_DateTime), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)datetime_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)datetime_repr, /* tp_repr */
- &datetime_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)datetime_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)datetime_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- datetime_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- datetime_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- datetime_methods, /* tp_methods */
- 0, /* tp_members */
- datetime_getset, /* tp_getset */
- &PyDateTime_DateType, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- datetime_alloc, /* tp_alloc */
- datetime_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.datetime", /* tp_name */
+ sizeof(PyDateTime_DateTime), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)datetime_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)datetime_repr, /* tp_repr */
+ &datetime_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)datetime_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)datetime_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ datetime_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ datetime_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ datetime_methods, /* tp_methods */
+ 0, /* tp_members */
+ datetime_getset, /* tp_getset */
+ &PyDateTime_DateType, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ datetime_alloc, /* tp_alloc */
+ datetime_new, /* tp_new */
+ 0, /* tp_free */
};
/* ---------------------------------------------------------------------------
@@ -4817,204 +4817,204 @@ static PyTypeObject PyDateTime_DateTimeType = {
*/
static PyMethodDef module_methods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
/* C API. Clients get at this via PyDateTime_IMPORT, defined in
* datetime.h.
*/
static PyDateTime_CAPI CAPI = {
- &PyDateTime_DateType,
- &PyDateTime_DateTimeType,
- &PyDateTime_TimeType,
- &PyDateTime_DeltaType,
- &PyDateTime_TZInfoType,
- new_date_ex,
- new_datetime_ex,
- new_time_ex,
- new_delta_ex,
- datetime_fromtimestamp,
- date_fromtimestamp
+ &PyDateTime_DateType,
+ &PyDateTime_DateTimeType,
+ &PyDateTime_TimeType,
+ &PyDateTime_DeltaType,
+ &PyDateTime_TZInfoType,
+ new_date_ex,
+ new_datetime_ex,
+ new_time_ex,
+ new_delta_ex,
+ datetime_fromtimestamp,
+ date_fromtimestamp
};
static struct PyModuleDef datetimemodule = {
- PyModuleDef_HEAD_INIT,
- "datetime",
- "Fast implementation of the datetime type.",
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "datetime",
+ "Fast implementation of the datetime type.",
+ -1,
+ module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_datetime(void)
{
- PyObject *m; /* a module object */
- PyObject *d; /* its dict */
- PyObject *x;
-
- m = PyModule_Create(&datetimemodule);
- if (m == NULL)
- return NULL;
-
- if (PyType_Ready(&PyDateTime_DateType) < 0)
- return NULL;
- if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
- return NULL;
- if (PyType_Ready(&PyDateTime_DeltaType) < 0)
- return NULL;
- if (PyType_Ready(&PyDateTime_TimeType) < 0)
- return NULL;
- if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
- return NULL;
-
- /* timedelta values */
- d = PyDateTime_DeltaType.tp_dict;
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- /* date values */
- d = PyDateTime_DateType.tp_dict;
-
- x = new_date(1, 1, 1);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_date(MAXYEAR, 12, 31);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_delta(1, 0, 0, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- /* time values */
- d = PyDateTime_TimeType.tp_dict;
-
- x = new_time(0, 0, 0, 0, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_time(23, 59, 59, 999999, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- /* datetime values */
- d = PyDateTime_DateTimeType.tp_dict;
-
- x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return NULL;
- Py_DECREF(x);
-
- /* module initialization */
- PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
- PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
-
- Py_INCREF(&PyDateTime_DateType);
- PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
-
- Py_INCREF(&PyDateTime_DateTimeType);
- PyModule_AddObject(m, "datetime",
- (PyObject *)&PyDateTime_DateTimeType);
-
- Py_INCREF(&PyDateTime_TimeType);
- PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
-
- Py_INCREF(&PyDateTime_DeltaType);
- PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
-
- Py_INCREF(&PyDateTime_TZInfoType);
- PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
-
- x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
- if (x == NULL)
- return NULL;
- PyModule_AddObject(m, "datetime_CAPI", x);
-
- /* A 4-year cycle has an extra leap day over what we'd get from
- * pasting together 4 single years.
- */
- assert(DI4Y == 4 * 365 + 1);
- assert(DI4Y == days_before_year(4+1));
-
- /* Similarly, a 400-year cycle has an extra leap day over what we'd
- * get from pasting together 4 100-year cycles.
- */
- assert(DI400Y == 4 * DI100Y + 1);
- assert(DI400Y == days_before_year(400+1));
-
- /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
- * pasting together 25 4-year cycles.
- */
- assert(DI100Y == 25 * DI4Y - 1);
- assert(DI100Y == days_before_year(100+1));
-
- us_per_us = PyLong_FromLong(1);
- us_per_ms = PyLong_FromLong(1000);
- us_per_second = PyLong_FromLong(1000000);
- us_per_minute = PyLong_FromLong(60000000);
- seconds_per_day = PyLong_FromLong(24 * 3600);
- if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
- us_per_minute == NULL || seconds_per_day == NULL)
- return NULL;
-
- /* The rest are too big for 32-bit ints, but even
- * us_per_week fits in 40 bits, so doubles should be exact.
- */
- us_per_hour = PyLong_FromDouble(3600000000.0);
- us_per_day = PyLong_FromDouble(86400000000.0);
- us_per_week = PyLong_FromDouble(604800000000.0);
- if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
- return NULL;
- return m;
+ PyObject *m; /* a module object */
+ PyObject *d; /* its dict */
+ PyObject *x;
+
+ m = PyModule_Create(&datetimemodule);
+ if (m == NULL)
+ return NULL;
+
+ if (PyType_Ready(&PyDateTime_DateType) < 0)
+ return NULL;
+ if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
+ return NULL;
+ if (PyType_Ready(&PyDateTime_DeltaType) < 0)
+ return NULL;
+ if (PyType_Ready(&PyDateTime_TimeType) < 0)
+ return NULL;
+ if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
+ return NULL;
+
+ /* timedelta values */
+ d = PyDateTime_DeltaType.tp_dict;
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ /* date values */
+ d = PyDateTime_DateType.tp_dict;
+
+ x = new_date(1, 1, 1);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_date(MAXYEAR, 12, 31);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_delta(1, 0, 0, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ /* time values */
+ d = PyDateTime_TimeType.tp_dict;
+
+ x = new_time(0, 0, 0, 0, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_time(23, 59, 59, 999999, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ /* datetime values */
+ d = PyDateTime_DateTimeType.tp_dict;
+
+ x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return NULL;
+ Py_DECREF(x);
+
+ /* module initialization */
+ PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
+ PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
+
+ Py_INCREF(&PyDateTime_DateType);
+ PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
+
+ Py_INCREF(&PyDateTime_DateTimeType);
+ PyModule_AddObject(m, "datetime",
+ (PyObject *)&PyDateTime_DateTimeType);
+
+ Py_INCREF(&PyDateTime_TimeType);
+ PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
+
+ Py_INCREF(&PyDateTime_DeltaType);
+ PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
+
+ Py_INCREF(&PyDateTime_TZInfoType);
+ PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
+
+ x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
+ if (x == NULL)
+ return NULL;
+ PyModule_AddObject(m, "datetime_CAPI", x);
+
+ /* A 4-year cycle has an extra leap day over what we'd get from
+ * pasting together 4 single years.
+ */
+ assert(DI4Y == 4 * 365 + 1);
+ assert(DI4Y == days_before_year(4+1));
+
+ /* Similarly, a 400-year cycle has an extra leap day over what we'd
+ * get from pasting together 4 100-year cycles.
+ */
+ assert(DI400Y == 4 * DI100Y + 1);
+ assert(DI400Y == days_before_year(400+1));
+
+ /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
+ * pasting together 25 4-year cycles.
+ */
+ assert(DI100Y == 25 * DI4Y - 1);
+ assert(DI100Y == days_before_year(100+1));
+
+ us_per_us = PyLong_FromLong(1);
+ us_per_ms = PyLong_FromLong(1000);
+ us_per_second = PyLong_FromLong(1000000);
+ us_per_minute = PyLong_FromLong(60000000);
+ seconds_per_day = PyLong_FromLong(24 * 3600);
+ if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
+ us_per_minute == NULL || seconds_per_day == NULL)
+ return NULL;
+
+ /* The rest are too big for 32-bit ints, but even
+ * us_per_week fits in 40 bits, so doubles should be exact.
+ */
+ us_per_hour = PyLong_FromDouble(3600000000.0);
+ us_per_day = PyLong_FromDouble(86400000000.0);
+ us_per_week = PyLong_FromDouble(604800000000.0);
+ if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
+ return NULL;
+ return m;
}
/* ---------------------------------------------------------------------------
Some time zone algebra. For a datetime x, let
x.n = x stripped of its timezone -- its naive time.
x.o = x.utcoffset(), and assuming that doesn't raise an exception or
- return None
+ return None
x.d = x.dst(), and assuming that doesn't raise an exception or
- return None
+ return None
x.s = x's standard offset, x.o - x.d
Now some derived rules, where k is a duration (timedelta).
@@ -5136,13 +5136,13 @@ the justifications for the kinds of substitutions we've done several times
already):
diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
- x.n - (z.n + diff - z'.o) = replacing diff via [6]
- x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
- x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
- - z.n + z.n - z.o + z'.o = cancel z.n
- - z.o + z'.o = #1 twice
- -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
- z'.d - z.d
+ x.n - (z.n + diff - z'.o) = replacing diff via [6]
+ x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
+ x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
+ - z.n + z.n - z.o + z'.o = cancel z.n
+ - z.o + z'.o = #1 twice
+ -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
+ z'.d - z.d
So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
we've found the UTC-equivalent so are done. In fact, we stop with [7] and
diff --git a/Modules/errnomodule.c b/Modules/errnomodule.c
index d5fe460..03c65f7 100644
--- a/Modules/errnomodule.c
+++ b/Modules/errnomodule.c
@@ -11,10 +11,10 @@
/*
* Pull in the system error definitions
- */
+ */
static PyMethodDef errno_methods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
/* Helper function doing the dictionary inserting */
@@ -22,21 +22,21 @@ static PyMethodDef errno_methods[] = {
static void
_inscode(PyObject *d, PyObject *de, const char *name, int code)
{
- PyObject *u = PyUnicode_FromString(name);
- PyObject *v = PyLong_FromLong((long) code);
+ PyObject *u = PyUnicode_FromString(name);
+ PyObject *v = PyLong_FromLong((long) code);
- /* Don't bother checking for errors; they'll be caught at the end
- * of the module initialization function by the caller of
- * initerrno().
- */
- if (u && v) {
- /* insert in modules dict */
- PyDict_SetItem(d, u, v);
- /* insert in errorcode dict */
- PyDict_SetItem(de, v, u);
- }
- Py_XDECREF(u);
- Py_XDECREF(v);
+ /* Don't bother checking for errors; they'll be caught at the end
+ * of the module initialization function by the caller of
+ * initerrno().
+ */
+ if (u && v) {
+ /* insert in modules dict */
+ PyDict_SetItem(d, u, v);
+ /* insert in errorcode dict */
+ PyDict_SetItem(de, v, u);
+ }
+ Py_XDECREF(u);
+ Py_XDECREF(v);
}
PyDoc_STRVAR(errno__doc__,
@@ -54,749 +54,749 @@ To map error codes to error messages, use the function os.strerror(),\n\
e.g. os.strerror(2) could return 'No such file or directory'.");
static struct PyModuleDef errnomodule = {
- PyModuleDef_HEAD_INIT,
- "errno",
- errno__doc__,
- -1,
- errno_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "errno",
+ errno__doc__,
+ -1,
+ errno_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_errno(void)
{
- PyObject *m, *d, *de;
- m = PyModule_Create(&errnomodule);
- if (m == NULL)
- return NULL;
- d = PyModule_GetDict(m);
- de = PyDict_New();
- if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
- return NULL;
+ PyObject *m, *d, *de;
+ m = PyModule_Create(&errnomodule);
+ if (m == NULL)
+ return NULL;
+ d = PyModule_GetDict(m);
+ de = PyDict_New();
+ if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
+ return NULL;
/* Macro so I don't have to edit each and every line below... */
#define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code)
- /*
- * The names and comments are borrowed from linux/include/errno.h,
- * which should be pretty all-inclusive
- */
+ /*
+ * The names and comments are borrowed from linux/include/errno.h,
+ * which should be pretty all-inclusive
+ */
#ifdef ENODEV
- inscode(d, ds, de, "ENODEV", ENODEV, "No such device");
+ inscode(d, ds, de, "ENODEV", ENODEV, "No such device");
#endif
#ifdef ENOCSI
- inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available");
+ inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available");
#endif
#ifdef EHOSTUNREACH
- inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host");
+ inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host");
#else
#ifdef WSAEHOSTUNREACH
- inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
+ inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
#endif
#endif
#ifdef ENOMSG
- inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type");
+ inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type");
#endif
#ifdef EUCLEAN
- inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning");
+ inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning");
#endif
#ifdef EL2NSYNC
- inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized");
+ inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized");
#endif
#ifdef EL2HLT
- inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted");
+ inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted");
#endif
#ifdef ENODATA
- inscode(d, ds, de, "ENODATA", ENODATA, "No data available");
+ inscode(d, ds, de, "ENODATA", ENODATA, "No data available");
#endif
#ifdef ENOTBLK
- inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required");
+ inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required");
#endif
#ifdef ENOSYS
- inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented");
+ inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented");
#endif
#ifdef EPIPE
- inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe");
+ inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe");
#endif
#ifdef EINVAL
- inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument");
+ inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument");
#else
#ifdef WSAEINVAL
- inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument");
+ inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument");
#endif
#endif
#ifdef EOVERFLOW
- inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type");
+ inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type");
#endif
#ifdef EADV
- inscode(d, ds, de, "EADV", EADV, "Advertise error");
+ inscode(d, ds, de, "EADV", EADV, "Advertise error");
#endif
#ifdef EINTR
- inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call");
+ inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call");
#else
#ifdef WSAEINTR
- inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call");
+ inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call");
#endif
#endif
#ifdef EUSERS
- inscode(d, ds, de, "EUSERS", EUSERS, "Too many users");
+ inscode(d, ds, de, "EUSERS", EUSERS, "Too many users");
#else
#ifdef WSAEUSERS
- inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users");
+ inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users");
#endif
#endif
#ifdef ENOTEMPTY
- inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty");
+ inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty");
#else
#ifdef WSAENOTEMPTY
- inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
+ inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
#endif
#endif
#ifdef ENOBUFS
- inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available");
+ inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available");
#else
#ifdef WSAENOBUFS
- inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available");
+ inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available");
#endif
#endif
#ifdef EPROTO
- inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error");
+ inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error");
#endif
#ifdef EREMOTE
- inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote");
+ inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote");
#else
#ifdef WSAEREMOTE
- inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote");
+ inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote");
#endif
#endif
#ifdef ENAVAIL
- inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available");
+ inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available");
#endif
#ifdef ECHILD
- inscode(d, ds, de, "ECHILD", ECHILD, "No child processes");
+ inscode(d, ds, de, "ECHILD", ECHILD, "No child processes");
#endif
#ifdef ELOOP
- inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered");
+ inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered");
#else
#ifdef WSAELOOP
- inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered");
+ inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered");
#endif
#endif
#ifdef EXDEV
- inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link");
+ inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link");
#endif
#ifdef E2BIG
- inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long");
+ inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long");
#endif
#ifdef ESRCH
- inscode(d, ds, de, "ESRCH", ESRCH, "No such process");
+ inscode(d, ds, de, "ESRCH", ESRCH, "No such process");
#endif
#ifdef EMSGSIZE
- inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long");
+ inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long");
#else
#ifdef WSAEMSGSIZE
- inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long");
+ inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long");
#endif
#endif
#ifdef EAFNOSUPPORT
- inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol");
+ inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol");
#else
#ifdef WSAEAFNOSUPPORT
- inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
+ inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
#endif
#endif
#ifdef EBADR
- inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor");
+ inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor");
#endif
#ifdef EHOSTDOWN
- inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down");
+ inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down");
#else
#ifdef WSAEHOSTDOWN
- inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down");
+ inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down");
#endif
#endif
#ifdef EPFNOSUPPORT
- inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported");
+ inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported");
#else
#ifdef WSAEPFNOSUPPORT
- inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
+ inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
#endif
#endif
#ifdef ENOPROTOOPT
- inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available");
+ inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available");
#else
#ifdef WSAENOPROTOOPT
- inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
+ inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
#endif
#endif
#ifdef EBUSY
- inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy");
+ inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy");
#endif
#ifdef EWOULDBLOCK
- inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block");
+ inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block");
#else
#ifdef WSAEWOULDBLOCK
- inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
+ inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
#endif
#endif
#ifdef EBADFD
- inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state");
+ inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state");
#endif
#ifdef EDOTDOT
- inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error");
+ inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error");
#endif
#ifdef EISCONN
- inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected");
+ inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected");
#else
#ifdef WSAEISCONN
- inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected");
+ inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected");
#endif
#endif
#ifdef ENOANO
- inscode(d, ds, de, "ENOANO", ENOANO, "No anode");
+ inscode(d, ds, de, "ENOANO", ENOANO, "No anode");
#endif
#ifdef ESHUTDOWN
- inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown");
+ inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown");
#else
#ifdef WSAESHUTDOWN
- inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
+ inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
#endif
#endif
#ifdef ECHRNG
- inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range");
+ inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range");
#endif
#ifdef ELIBBAD
- inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library");
+ inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library");
#endif
#ifdef ENONET
- inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network");
+ inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network");
#endif
#ifdef EBADE
- inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange");
+ inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange");
#endif
#ifdef EBADF
- inscode(d, ds, de, "EBADF", EBADF, "Bad file number");
+ inscode(d, ds, de, "EBADF", EBADF, "Bad file number");
#else
#ifdef WSAEBADF
- inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number");
+ inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number");
#endif
#endif
#ifdef EMULTIHOP
- inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted");
+ inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted");
#endif
#ifdef EIO
- inscode(d, ds, de, "EIO", EIO, "I/O error");
+ inscode(d, ds, de, "EIO", EIO, "I/O error");
#endif
#ifdef EUNATCH
- inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached");
+ inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached");
#endif
#ifdef EPROTOTYPE
- inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket");
+ inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket");
#else
#ifdef WSAEPROTOTYPE
- inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
+ inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
#endif
#endif
#ifdef ENOSPC
- inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device");
+ inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device");
#endif
#ifdef ENOEXEC
- inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error");
+ inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error");
#endif
#ifdef EALREADY
- inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress");
+ inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress");
#else
#ifdef WSAEALREADY
- inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress");
+ inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress");
#endif
#endif
#ifdef ENETDOWN
- inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down");
+ inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down");
#else
#ifdef WSAENETDOWN
- inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down");
+ inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down");
#endif
#endif
#ifdef ENOTNAM
- inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file");
+ inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file");
#endif
#ifdef EACCES
- inscode(d, ds, de, "EACCES", EACCES, "Permission denied");
+ inscode(d, ds, de, "EACCES", EACCES, "Permission denied");
#else
#ifdef WSAEACCES
- inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied");
+ inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied");
#endif
#endif
#ifdef ELNRNG
- inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range");
+ inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range");
#endif
#ifdef EILSEQ
- inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence");
+ inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence");
#endif
#ifdef ENOTDIR
- inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory");
+ inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory");
#endif
#ifdef ENOTUNIQ
- inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network");
+ inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network");
#endif
#ifdef EPERM
- inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted");
+ inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted");
#endif
#ifdef EDOM
- inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func");
+ inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func");
#endif
#ifdef EXFULL
- inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full");
+ inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full");
#endif
#ifdef ECONNREFUSED
- inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused");
+ inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused");
#else
#ifdef WSAECONNREFUSED
- inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused");
+ inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused");
#endif
#endif
#ifdef EISDIR
- inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory");
+ inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory");
#endif
#ifdef EPROTONOSUPPORT
- inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported");
+ inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported");
#else
#ifdef WSAEPROTONOSUPPORT
- inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
+ inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
#endif
#endif
#ifdef EROFS
- inscode(d, ds, de, "EROFS", EROFS, "Read-only file system");
+ inscode(d, ds, de, "EROFS", EROFS, "Read-only file system");
#endif
#ifdef EADDRNOTAVAIL
- inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address");
+ inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address");
#else
#ifdef WSAEADDRNOTAVAIL
- inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
+ inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
#endif
#endif
#ifdef EIDRM
- inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed");
+ inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed");
#endif
#ifdef ECOMM
- inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send");
+ inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send");
#endif
#ifdef ESRMNT
- inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error");
+ inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error");
#endif
#ifdef EREMOTEIO
- inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error");
+ inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error");
#endif
#ifdef EL3RST
- inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset");
+ inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset");
#endif
#ifdef EBADMSG
- inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message");
+ inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message");
#endif
#ifdef ENFILE
- inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow");
+ inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow");
#endif
#ifdef ELIBMAX
- inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries");
+ inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries");
#endif
#ifdef ESPIPE
- inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek");
+ inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek");
#endif
#ifdef ENOLINK
- inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed");
+ inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed");
#endif
#ifdef ENETRESET
- inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset");
+ inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset");
#else
#ifdef WSAENETRESET
- inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset");
+ inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset");
#endif
#endif
#ifdef ETIMEDOUT
- inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out");
+ inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out");
#else
#ifdef WSAETIMEDOUT
- inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
+ inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
#endif
#endif
#ifdef ENOENT
- inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");
+ inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");
#endif
#ifdef EEXIST
- inscode(d, ds, de, "EEXIST", EEXIST, "File exists");
+ inscode(d, ds, de, "EEXIST", EEXIST, "File exists");
#endif
#ifdef EDQUOT
- inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded");
+ inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded");
#else
#ifdef WSAEDQUOT
- inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded");
+ inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded");
#endif
#endif
#ifdef ENOSTR
- inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream");
+ inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream");
#endif
#ifdef EBADSLT
- inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot");
+ inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot");
#endif
#ifdef EBADRQC
- inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code");
+ inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code");
#endif
#ifdef ELIBACC
- inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library");
+ inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library");
#endif
#ifdef EFAULT
- inscode(d, ds, de, "EFAULT", EFAULT, "Bad address");
+ inscode(d, ds, de, "EFAULT", EFAULT, "Bad address");
#else
#ifdef WSAEFAULT
- inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address");
+ inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address");
#endif
#endif
#ifdef EFBIG
- inscode(d, ds, de, "EFBIG", EFBIG, "File too large");
+ inscode(d, ds, de, "EFBIG", EFBIG, "File too large");
#endif
#ifdef EDEADLK
- inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur");
+ inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur");
#endif
#ifdef ENOTCONN
- inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected");
+ inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected");
#else
#ifdef WSAENOTCONN
- inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
+ inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
#endif
#endif
#ifdef EDESTADDRREQ
- inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required");
+ inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required");
#else
#ifdef WSAEDESTADDRREQ
- inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
+ inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
#endif
#endif
#ifdef ELIBSCN
- inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted");
+ inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted");
#endif
#ifdef ENOLCK
- inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available");
+ inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available");
#endif
#ifdef EISNAM
- inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file");
+ inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file");
#endif
#ifdef ECONNABORTED
- inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort");
+ inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort");
#else
#ifdef WSAECONNABORTED
- inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
+ inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
#endif
#endif
#ifdef ENETUNREACH
- inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable");
+ inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable");
#else
#ifdef WSAENETUNREACH
- inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable");
+ inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable");
#endif
#endif
#ifdef ESTALE
- inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle");
+ inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle");
#else
#ifdef WSAESTALE
- inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle");
+ inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle");
#endif
#endif
#ifdef ENOSR
- inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources");
+ inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources");
#endif
#ifdef ENOMEM
- inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory");
+ inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory");
#endif
#ifdef ENOTSOCK
- inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket");
+ inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket");
#else
#ifdef WSAENOTSOCK
- inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
+ inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
#endif
#endif
#ifdef ESTRPIPE
- inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error");
+ inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error");
#endif
#ifdef EMLINK
- inscode(d, ds, de, "EMLINK", EMLINK, "Too many links");
+ inscode(d, ds, de, "EMLINK", EMLINK, "Too many links");
#endif
#ifdef ERANGE
- inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable");
+ inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable");
#endif
#ifdef ELIBEXEC
- inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly");
+ inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly");
#endif
#ifdef EL3HLT
- inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted");
+ inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted");
#endif
#ifdef ECONNRESET
- inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer");
+ inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer");
#else
#ifdef WSAECONNRESET
- inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer");
+ inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer");
#endif
#endif
#ifdef EADDRINUSE
- inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use");
+ inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use");
#else
#ifdef WSAEADDRINUSE
- inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use");
+ inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use");
#endif
#endif
#ifdef EOPNOTSUPP
- inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint");
+ inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint");
#else
#ifdef WSAEOPNOTSUPP
- inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
+ inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
#endif
#endif
#ifdef EREMCHG
- inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed");
+ inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed");
#endif
#ifdef EAGAIN
- inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again");
+ inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again");
#endif
#ifdef ENAMETOOLONG
- inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long");
+ inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long");
#else
#ifdef WSAENAMETOOLONG
- inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
+ inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
#endif
#endif
#ifdef ENOTTY
- inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter");
+ inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter");
#endif
#ifdef ERESTART
- inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted");
+ inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted");
#endif
#ifdef ESOCKTNOSUPPORT
- inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported");
+ inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported");
#else
#ifdef WSAESOCKTNOSUPPORT
- inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
+ inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
#endif
#endif
#ifdef ETIME
- inscode(d, ds, de, "ETIME", ETIME, "Timer expired");
+ inscode(d, ds, de, "ETIME", ETIME, "Timer expired");
#endif
#ifdef EBFONT
- inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format");
+ inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format");
#endif
#ifdef EDEADLOCK
- inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK");
+ inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK");
#endif
#ifdef ETOOMANYREFS
- inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice");
+ inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice");
#else
#ifdef WSAETOOMANYREFS
- inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
+ inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
#endif
#endif
#ifdef EMFILE
- inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files");
+ inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files");
#else
#ifdef WSAEMFILE
- inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files");
+ inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files");
#endif
#endif
#ifdef ETXTBSY
- inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy");
+ inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy");
#endif
#ifdef EINPROGRESS
- inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress");
+ inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress");
#else
#ifdef WSAEINPROGRESS
- inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
+ inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
#endif
#endif
#ifdef ENXIO
- inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address");
+ inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address");
#endif
#ifdef ENOPKG
- inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed");
+ inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed");
#endif
#ifdef WSASY
- inscode(d, ds, de, "WSASY", WSASY, "Error WSASY");
+ inscode(d, ds, de, "WSASY", WSASY, "Error WSASY");
#endif
#ifdef WSAEHOSTDOWN
- inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down");
+ inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down");
#endif
#ifdef WSAENETDOWN
- inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down");
+ inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down");
#endif
#ifdef WSAENOTSOCK
- inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
+ inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
#endif
#ifdef WSAEHOSTUNREACH
- inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
+ inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
#endif
#ifdef WSAELOOP
- inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered");
+ inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered");
#endif
#ifdef WSAEMFILE
- inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files");
+ inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files");
#endif
#ifdef WSAESTALE
- inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle");
+ inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle");
#endif
#ifdef WSAVERNOTSUPPORTED
- inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED");
+ inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED");
#endif
#ifdef WSAENETUNREACH
- inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable");
+ inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable");
#endif
#ifdef WSAEPROCLIM
- inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM");
+ inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM");
#endif
#ifdef WSAEFAULT
- inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address");
+ inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address");
#endif
#ifdef WSANOTINITIALISED
- inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED");
+ inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED");
#endif
#ifdef WSAEUSERS
- inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users");
+ inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users");
#endif
#ifdef WSAMAKEASYNCREPL
- inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL");
+ inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL");
#endif
#ifdef WSAENOPROTOOPT
- inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
+ inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
#endif
#ifdef WSAECONNABORTED
- inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
+ inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
#endif
#ifdef WSAENAMETOOLONG
- inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
+ inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
#endif
#ifdef WSAENOTEMPTY
- inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
+ inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
#endif
#ifdef WSAESHUTDOWN
- inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
+ inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
#endif
#ifdef WSAEAFNOSUPPORT
- inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
+ inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
#endif
#ifdef WSAETOOMANYREFS
- inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
+ inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
#endif
#ifdef WSAEACCES
- inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied");
+ inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied");
#endif
#ifdef WSATR
- inscode(d, ds, de, "WSATR", WSATR, "Error WSATR");
+ inscode(d, ds, de, "WSATR", WSATR, "Error WSATR");
#endif
#ifdef WSABASEERR
- inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR");
+ inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR");
#endif
#ifdef WSADESCRIPTIO
- inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO");
+ inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO");
#endif
#ifdef WSAEMSGSIZE
- inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long");
+ inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long");
#endif
#ifdef WSAEBADF
- inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number");
+ inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number");
#endif
#ifdef WSAECONNRESET
- inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer");
+ inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer");
#endif
#ifdef WSAGETSELECTERRO
- inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO");
+ inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO");
#endif
#ifdef WSAETIMEDOUT
- inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
+ inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
#endif
#ifdef WSAENOBUFS
- inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available");
+ inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available");
#endif
#ifdef WSAEDISCON
- inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON");
+ inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON");
#endif
#ifdef WSAEINTR
- inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call");
+ inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call");
#endif
#ifdef WSAEPROTOTYPE
- inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
+ inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
#endif
#ifdef WSAHOS
- inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS");
+ inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS");
#endif
#ifdef WSAEADDRINUSE
- inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use");
+ inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use");
#endif
#ifdef WSAEADDRNOTAVAIL
- inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
+ inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
#endif
#ifdef WSAEALREADY
- inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress");
+ inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress");
#endif
#ifdef WSAEPROTONOSUPPORT
- inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
+ inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
#endif
#ifdef WSASYSNOTREADY
- inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY");
+ inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY");
#endif
#ifdef WSAEWOULDBLOCK
- inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
+ inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
#endif
#ifdef WSAEPFNOSUPPORT
- inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
+ inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
#endif
#ifdef WSAEOPNOTSUPP
- inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
+ inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
#endif
#ifdef WSAEISCONN
- inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected");
+ inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected");
#endif
#ifdef WSAEDQUOT
- inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded");
+ inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded");
#endif
#ifdef WSAENOTCONN
- inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
+ inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
#endif
#ifdef WSAEREMOTE
- inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote");
+ inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote");
#endif
#ifdef WSAEINVAL
- inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument");
+ inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument");
#endif
#ifdef WSAEINPROGRESS
- inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
+ inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
#endif
#ifdef WSAGETSELECTEVEN
- inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN");
+ inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN");
#endif
#ifdef WSAESOCKTNOSUPPORT
- inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
+ inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
#endif
#ifdef WSAGETASYNCERRO
- inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO");
+ inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO");
#endif
#ifdef WSAMAKESELECTREPL
- inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL");
+ inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL");
#endif
#ifdef WSAGETASYNCBUFLE
- inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE");
+ inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE");
#endif
#ifdef WSAEDESTADDRREQ
- inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
+ inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
#endif
#ifdef WSAECONNREFUSED
- inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused");
+ inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused");
#endif
#ifdef WSAENETRESET
- inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset");
+ inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset");
#endif
#ifdef WSAN
- inscode(d, ds, de, "WSAN", WSAN, "Error WSAN");
+ inscode(d, ds, de, "WSAN", WSAN, "Error WSAN");
#endif
- Py_DECREF(de);
- return m;
+ Py_DECREF(de);
+ return m;
}
diff --git a/Modules/fcntlmodule.c b/Modules/fcntlmodule.c
index 683c5b6..5bf4010 100644
--- a/Modules/fcntlmodule.c
+++ b/Modules/fcntlmodule.c
@@ -21,7 +21,7 @@ conv_descriptor(PyObject *object, int *target)
int fd = PyObject_AsFileDescriptor(object);
if (fd < 0)
- return 0;
+ return 0;
*target = fd;
return 1;
}
@@ -32,48 +32,48 @@ conv_descriptor(PyObject *object, int *target)
static PyObject *
fcntl_fcntl(PyObject *self, PyObject *args)
{
- int fd;
- int code;
- long arg;
- int ret;
- char *str;
- Py_ssize_t len;
- char buf[1024];
-
- if (PyArg_ParseTuple(args, "O&is#:fcntl",
- conv_descriptor, &fd, &code, &str, &len)) {
- if (len > sizeof buf) {
- PyErr_SetString(PyExc_ValueError,
- "fcntl string arg too long");
- return NULL;
- }
- memcpy(buf, str, len);
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, code, buf);
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyBytes_FromStringAndSize(buf, len);
- }
-
- PyErr_Clear();
- arg = 0;
- if (!PyArg_ParseTuple(args,
- "O&i|l;fcntl requires a file or file descriptor,"
- " an integer and optionally a third integer or a string",
- conv_descriptor, &fd, &code, &arg)) {
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, code, arg);
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyLong_FromLong((long)ret);
+ int fd;
+ int code;
+ long arg;
+ int ret;
+ char *str;
+ Py_ssize_t len;
+ char buf[1024];
+
+ if (PyArg_ParseTuple(args, "O&is#:fcntl",
+ conv_descriptor, &fd, &code, &str, &len)) {
+ if (len > sizeof buf) {
+ PyErr_SetString(PyExc_ValueError,
+ "fcntl string arg too long");
+ return NULL;
+ }
+ memcpy(buf, str, len);
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, code, buf);
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyBytes_FromStringAndSize(buf, len);
+ }
+
+ PyErr_Clear();
+ arg = 0;
+ if (!PyArg_ParseTuple(args,
+ "O&i|l;fcntl requires a file or file descriptor,"
+ " an integer and optionally a third integer or a string",
+ conv_descriptor, &fd, &code, &arg)) {
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, code, arg);
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyLong_FromLong((long)ret);
}
PyDoc_STRVAR(fcntl_doc,
@@ -96,128 +96,128 @@ static PyObject *
fcntl_ioctl(PyObject *self, PyObject *args)
{
#define IOCTL_BUFSZ 1024
- int fd;
- /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I'
- format for the 'code' parameter because Python turns 0x8000000
- into either a large positive number (PyLong or PyInt on 64-bit
- platforms) or a negative number on others (32-bit PyInt)
- whereas the system expects it to be a 32bit bit field value
- regardless of it being passed as an int or unsigned long on
- various platforms. See the termios.TIOCSWINSZ constant across
- platforms for an example of thise.
-
- If any of the 64bit platforms ever decide to use more than 32bits
- in their unsigned long ioctl codes this will break and need
- special casing based on the platform being built on.
- */
- unsigned int code;
- int arg;
- int ret;
- Py_buffer pstr;
- char *str;
- Py_ssize_t len;
- int mutate_arg = 1;
- char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */
-
- if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl",
- conv_descriptor, &fd, &code,
- &pstr, &mutate_arg)) {
- char *arg;
- str = pstr.buf;
- len = pstr.len;
-
- if (mutate_arg) {
- if (len <= IOCTL_BUFSZ) {
- memcpy(buf, str, len);
- buf[len] = '\0';
- arg = buf;
- }
- else {
- arg = str;
- }
- }
- else {
- if (len > IOCTL_BUFSZ) {
- PyBuffer_Release(&pstr);
- PyErr_SetString(PyExc_ValueError,
- "ioctl string arg too long");
- return NULL;
- }
- else {
- memcpy(buf, str, len);
- buf[len] = '\0';
- arg = buf;
- }
- }
- if (buf == arg) {
- Py_BEGIN_ALLOW_THREADS /* think array.resize() */
- ret = ioctl(fd, code, arg);
- Py_END_ALLOW_THREADS
- }
- else {
- ret = ioctl(fd, code, arg);
- }
- if (mutate_arg && (len < IOCTL_BUFSZ)) {
- memcpy(str, buf, len);
- }
- PyBuffer_Release(&pstr); /* No further access to str below this point */
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- if (mutate_arg) {
- return PyLong_FromLong(ret);
- }
- else {
- return PyBytes_FromStringAndSize(buf, len);
- }
- }
-
- PyErr_Clear();
- if (PyArg_ParseTuple(args, "O&Is*:ioctl",
- conv_descriptor, &fd, &code, &pstr)) {
- str = pstr.buf;
- len = pstr.len;
- if (len > IOCTL_BUFSZ) {
- PyBuffer_Release(&pstr);
- PyErr_SetString(PyExc_ValueError,
- "ioctl string arg too long");
- return NULL;
- }
- memcpy(buf, str, len);
- buf[len] = '\0';
- Py_BEGIN_ALLOW_THREADS
- ret = ioctl(fd, code, buf);
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyBuffer_Release(&pstr);
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- PyBuffer_Release(&pstr);
- return PyBytes_FromStringAndSize(buf, len);
- }
-
- PyErr_Clear();
- arg = 0;
- if (!PyArg_ParseTuple(args,
- "O&I|i;ioctl requires a file or file descriptor,"
- " an integer and optionally an integer or buffer argument",
- conv_descriptor, &fd, &code, &arg)) {
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
+ int fd;
+ /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I'
+ format for the 'code' parameter because Python turns 0x8000000
+ into either a large positive number (PyLong or PyInt on 64-bit
+ platforms) or a negative number on others (32-bit PyInt)
+ whereas the system expects it to be a 32bit bit field value
+ regardless of it being passed as an int or unsigned long on
+ various platforms. See the termios.TIOCSWINSZ constant across
+ platforms for an example of thise.
+
+ If any of the 64bit platforms ever decide to use more than 32bits
+ in their unsigned long ioctl codes this will break and need
+ special casing based on the platform being built on.
+ */
+ unsigned int code;
+ int arg;
+ int ret;
+ Py_buffer pstr;
+ char *str;
+ Py_ssize_t len;
+ int mutate_arg = 1;
+ char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */
+
+ if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl",
+ conv_descriptor, &fd, &code,
+ &pstr, &mutate_arg)) {
+ char *arg;
+ str = pstr.buf;
+ len = pstr.len;
+
+ if (mutate_arg) {
+ if (len <= IOCTL_BUFSZ) {
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ arg = buf;
+ }
+ else {
+ arg = str;
+ }
+ }
+ else {
+ if (len > IOCTL_BUFSZ) {
+ PyBuffer_Release(&pstr);
+ PyErr_SetString(PyExc_ValueError,
+ "ioctl string arg too long");
+ return NULL;
+ }
+ else {
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ arg = buf;
+ }
+ }
+ if (buf == arg) {
+ Py_BEGIN_ALLOW_THREADS /* think array.resize() */
+ ret = ioctl(fd, code, arg);
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ ret = ioctl(fd, code, arg);
+ }
+ if (mutate_arg && (len < IOCTL_BUFSZ)) {
+ memcpy(str, buf, len);
+ }
+ PyBuffer_Release(&pstr); /* No further access to str below this point */
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ if (mutate_arg) {
+ return PyLong_FromLong(ret);
+ }
+ else {
+ return PyBytes_FromStringAndSize(buf, len);
+ }
+ }
+
+ PyErr_Clear();
+ if (PyArg_ParseTuple(args, "O&Is*:ioctl",
+ conv_descriptor, &fd, &code, &pstr)) {
+ str = pstr.buf;
+ len = pstr.len;
+ if (len > IOCTL_BUFSZ) {
+ PyBuffer_Release(&pstr);
+ PyErr_SetString(PyExc_ValueError,
+ "ioctl string arg too long");
+ return NULL;
+ }
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ Py_BEGIN_ALLOW_THREADS
+ ret = ioctl(fd, code, buf);
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyBuffer_Release(&pstr);
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ PyBuffer_Release(&pstr);
+ return PyBytes_FromStringAndSize(buf, len);
+ }
+
+ PyErr_Clear();
+ arg = 0;
+ if (!PyArg_ParseTuple(args,
+ "O&I|i;ioctl requires a file or file descriptor,"
+ " an integer and optionally an integer or buffer argument",
+ conv_descriptor, &fd, &code, &arg)) {
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
#ifdef __VMS
- ret = ioctl(fd, code, (void *)arg);
+ ret = ioctl(fd, code, (void *)arg);
#else
- ret = ioctl(fd, code, arg);
-#endif
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyLong_FromLong((long)ret);
+ ret = ioctl(fd, code, arg);
+#endif
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyLong_FromLong((long)ret);
#undef IOCTL_BUFSZ
}
@@ -258,51 +258,51 @@ code.");
static PyObject *
fcntl_flock(PyObject *self, PyObject *args)
{
- int fd;
- int code;
- int ret;
+ int fd;
+ int code;
+ int ret;
- if (!PyArg_ParseTuple(args, "O&i:flock",
- conv_descriptor, &fd, &code))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O&i:flock",
+ conv_descriptor, &fd, &code))
+ return NULL;
#ifdef HAVE_FLOCK
- Py_BEGIN_ALLOW_THREADS
- ret = flock(fd, code);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ ret = flock(fd, code);
+ Py_END_ALLOW_THREADS
#else
#ifndef LOCK_SH
-#define LOCK_SH 1 /* shared lock */
-#define LOCK_EX 2 /* exclusive lock */
-#define LOCK_NB 4 /* don't block when locking */
-#define LOCK_UN 8 /* unlock */
-#endif
- {
- struct flock l;
- if (code == LOCK_UN)
- l.l_type = F_UNLCK;
- else if (code & LOCK_SH)
- l.l_type = F_RDLCK;
- else if (code & LOCK_EX)
- l.l_type = F_WRLCK;
- else {
- PyErr_SetString(PyExc_ValueError,
- "unrecognized flock argument");
- return NULL;
- }
- l.l_whence = l.l_start = l.l_len = 0;
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
- Py_END_ALLOW_THREADS
- }
+#define LOCK_SH 1 /* shared lock */
+#define LOCK_EX 2 /* exclusive lock */
+#define LOCK_NB 4 /* don't block when locking */
+#define LOCK_UN 8 /* unlock */
+#endif
+ {
+ struct flock l;
+ if (code == LOCK_UN)
+ l.l_type = F_UNLCK;
+ else if (code & LOCK_SH)
+ l.l_type = F_RDLCK;
+ else if (code & LOCK_EX)
+ l.l_type = F_WRLCK;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "unrecognized flock argument");
+ return NULL;
+ }
+ l.l_whence = l.l_start = l.l_len = 0;
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
+ Py_END_ALLOW_THREADS
+ }
#endif /* HAVE_FLOCK */
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(flock_doc,
@@ -317,72 +317,72 @@ emulated using fcntl().)");
static PyObject *
fcntl_lockf(PyObject *self, PyObject *args)
{
- int fd, code, ret, whence = 0;
- PyObject *lenobj = NULL, *startobj = NULL;
+ int fd, code, ret, whence = 0;
+ PyObject *lenobj = NULL, *startobj = NULL;
- if (!PyArg_ParseTuple(args, "O&i|OOi:lockf",
- conv_descriptor, &fd, &code,
- &lenobj, &startobj, &whence))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O&i|OOi:lockf",
+ conv_descriptor, &fd, &code,
+ &lenobj, &startobj, &whence))
+ return NULL;
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- PyErr_SetString(PyExc_NotImplementedError,
- "lockf not supported on OS/2 (EMX)");
- return NULL;
+ PyErr_SetString(PyExc_NotImplementedError,
+ "lockf not supported on OS/2 (EMX)");
+ return NULL;
#else
#ifndef LOCK_SH
-#define LOCK_SH 1 /* shared lock */
-#define LOCK_EX 2 /* exclusive lock */
-#define LOCK_NB 4 /* don't block when locking */
-#define LOCK_UN 8 /* unlock */
+#define LOCK_SH 1 /* shared lock */
+#define LOCK_EX 2 /* exclusive lock */
+#define LOCK_NB 4 /* don't block when locking */
+#define LOCK_UN 8 /* unlock */
#endif /* LOCK_SH */
- {
- struct flock l;
- if (code == LOCK_UN)
- l.l_type = F_UNLCK;
- else if (code & LOCK_SH)
- l.l_type = F_RDLCK;
- else if (code & LOCK_EX)
- l.l_type = F_WRLCK;
- else {
- PyErr_SetString(PyExc_ValueError,
- "unrecognized lockf argument");
- return NULL;
- }
- l.l_start = l.l_len = 0;
- if (startobj != NULL) {
+ {
+ struct flock l;
+ if (code == LOCK_UN)
+ l.l_type = F_UNLCK;
+ else if (code & LOCK_SH)
+ l.l_type = F_RDLCK;
+ else if (code & LOCK_EX)
+ l.l_type = F_WRLCK;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "unrecognized lockf argument");
+ return NULL;
+ }
+ l.l_start = l.l_len = 0;
+ if (startobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
- l.l_start = PyLong_AsLong(startobj);
+ l.l_start = PyLong_AsLong(startobj);
#else
- l.l_start = PyLong_Check(startobj) ?
- PyLong_AsLongLong(startobj) :
- PyLong_AsLong(startobj);
-#endif
- if (PyErr_Occurred())
- return NULL;
- }
- if (lenobj != NULL) {
+ l.l_start = PyLong_Check(startobj) ?
+ PyLong_AsLongLong(startobj) :
+ PyLong_AsLong(startobj);
+#endif
+ if (PyErr_Occurred())
+ return NULL;
+ }
+ if (lenobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
- l.l_len = PyLong_AsLong(lenobj);
+ l.l_len = PyLong_AsLong(lenobj);
#else
- l.l_len = PyLong_Check(lenobj) ?
- PyLong_AsLongLong(lenobj) :
- PyLong_AsLong(lenobj);
-#endif
- if (PyErr_Occurred())
- return NULL;
- }
- l.l_whence = whence;
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
- Py_END_ALLOW_THREADS
- }
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ l.l_len = PyLong_Check(lenobj) ?
+ PyLong_AsLongLong(lenobj) :
+ PyLong_AsLong(lenobj);
+#endif
+ if (PyErr_Occurred())
+ return NULL;
+ }
+ l.l_whence = whence;
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
+ Py_END_ALLOW_THREADS
+ }
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
#endif /* defined(PYOS_OS2) && defined(PYCC_GCC) */
}
@@ -414,11 +414,11 @@ starts. whence is as with fileobj.seek(), specifically:\n\
/* List of functions */
static PyMethodDef fcntl_methods[] = {
- {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc},
- {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc},
- {"flock", fcntl_flock, METH_VARARGS, flock_doc},
- {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc},
- {NULL, NULL} /* sentinel */
+ {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc},
+ {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc},
+ {"flock", fcntl_flock, METH_VARARGS, flock_doc},
+ {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -433,12 +433,12 @@ a file or socket object.");
static int
ins(PyObject* d, char* symbol, long value)
{
- PyObject* v = PyLong_FromLong(value);
- if (!v || PyDict_SetItemString(d, symbol, v) < 0)
- return -1;
+ PyObject* v = PyLong_FromLong(value);
+ if (!v || PyDict_SetItemString(d, symbol, v) < 0)
+ return -1;
- Py_DECREF(v);
- return 0;
+ Py_DECREF(v);
+ return 0;
}
#define INS(x) if (ins(d, #x, (long)x)) return -1
@@ -446,199 +446,199 @@ ins(PyObject* d, char* symbol, long value)
static int
all_ins(PyObject* d)
{
- if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1;
- if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1;
- if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1;
- if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1;
+ if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1;
+ if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1;
+ if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1;
+ if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1;
/* GNU extensions, as of glibc 2.2.4 */
#ifdef LOCK_MAND
- if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1;
+ if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1;
#endif
#ifdef LOCK_READ
- if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1;
+ if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1;
#endif
#ifdef LOCK_WRITE
- if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1;
+ if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1;
#endif
#ifdef LOCK_RW
- if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1;
+ if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1;
#endif
#ifdef F_DUPFD
- if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1;
+ if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1;
#endif
#ifdef F_GETFD
- if (ins(d, "F_GETFD", (long)F_GETFD)) return -1;
+ if (ins(d, "F_GETFD", (long)F_GETFD)) return -1;
#endif
#ifdef F_SETFD
- if (ins(d, "F_SETFD", (long)F_SETFD)) return -1;
+ if (ins(d, "F_SETFD", (long)F_SETFD)) return -1;
#endif
#ifdef F_GETFL
- if (ins(d, "F_GETFL", (long)F_GETFL)) return -1;
+ if (ins(d, "F_GETFL", (long)F_GETFL)) return -1;
#endif
#ifdef F_SETFL
- if (ins(d, "F_SETFL", (long)F_SETFL)) return -1;
+ if (ins(d, "F_SETFL", (long)F_SETFL)) return -1;
#endif
#ifdef F_GETLK
- if (ins(d, "F_GETLK", (long)F_GETLK)) return -1;
+ if (ins(d, "F_GETLK", (long)F_GETLK)) return -1;
#endif
#ifdef F_SETLK
- if (ins(d, "F_SETLK", (long)F_SETLK)) return -1;
+ if (ins(d, "F_SETLK", (long)F_SETLK)) return -1;
#endif
#ifdef F_SETLKW
- if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1;
+ if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1;
#endif
#ifdef F_GETOWN
- if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1;
+ if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1;
#endif
#ifdef F_SETOWN
- if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1;
+ if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1;
#endif
#ifdef F_GETSIG
- if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1;
+ if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1;
#endif
#ifdef F_SETSIG
- if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1;
+ if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1;
#endif
#ifdef F_RDLCK
- if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1;
+ if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1;
#endif
#ifdef F_WRLCK
- if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1;
+ if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1;
#endif
#ifdef F_UNLCK
- if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1;
+ if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1;
#endif
/* LFS constants */
#ifdef F_GETLK64
- if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1;
+ if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1;
#endif
#ifdef F_SETLK64
- if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1;
+ if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1;
#endif
#ifdef F_SETLKW64
- if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
+ if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
#endif
/* GNU extensions, as of glibc 2.2.4. */
#ifdef FASYNC
- if (ins(d, "FASYNC", (long)FASYNC)) return -1;
+ if (ins(d, "FASYNC", (long)FASYNC)) return -1;
#endif
#ifdef F_SETLEASE
- if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
+ if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
#endif
#ifdef F_GETLEASE
- if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1;
+ if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1;
#endif
#ifdef F_NOTIFY
- if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1;
+ if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1;
#endif
/* Old BSD flock(). */
#ifdef F_EXLCK
- if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1;
+ if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1;
#endif
#ifdef F_SHLCK
- if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1;
+ if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1;
#endif
/* OS X (and maybe others) let you tell the storage device to flush to physical media */
#ifdef F_FULLFSYNC
- if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1;
+ if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1;
#endif
/* For F_{GET|SET}FL */
#ifdef FD_CLOEXEC
- if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1;
+ if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1;
#endif
/* For F_NOTIFY */
#ifdef DN_ACCESS
- if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1;
+ if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1;
#endif
#ifdef DN_MODIFY
- if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1;
+ if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1;
#endif
#ifdef DN_CREATE
- if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1;
+ if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1;
#endif
#ifdef DN_DELETE
- if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1;
+ if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1;
#endif
#ifdef DN_RENAME
- if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1;
+ if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1;
#endif
#ifdef DN_ATTRIB
- if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1;
+ if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1;
#endif
#ifdef DN_MULTISHOT
- if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1;
+ if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1;
#endif
#ifdef HAVE_STROPTS_H
- /* Unix 98 guarantees that these are in stropts.h. */
- INS(I_PUSH);
- INS(I_POP);
- INS(I_LOOK);
- INS(I_FLUSH);
- INS(I_FLUSHBAND);
- INS(I_SETSIG);
- INS(I_GETSIG);
- INS(I_FIND);
- INS(I_PEEK);
- INS(I_SRDOPT);
- INS(I_GRDOPT);
- INS(I_NREAD);
- INS(I_FDINSERT);
- INS(I_STR);
- INS(I_SWROPT);
+ /* Unix 98 guarantees that these are in stropts.h. */
+ INS(I_PUSH);
+ INS(I_POP);
+ INS(I_LOOK);
+ INS(I_FLUSH);
+ INS(I_FLUSHBAND);
+ INS(I_SETSIG);
+ INS(I_GETSIG);
+ INS(I_FIND);
+ INS(I_PEEK);
+ INS(I_SRDOPT);
+ INS(I_GRDOPT);
+ INS(I_NREAD);
+ INS(I_FDINSERT);
+ INS(I_STR);
+ INS(I_SWROPT);
#ifdef I_GWROPT
- /* despite the comment above, old-ish glibcs miss a couple... */
- INS(I_GWROPT);
-#endif
- INS(I_SENDFD);
- INS(I_RECVFD);
- INS(I_LIST);
- INS(I_ATMARK);
- INS(I_CKBAND);
- INS(I_GETBAND);
- INS(I_CANPUT);
- INS(I_SETCLTIME);
+ /* despite the comment above, old-ish glibcs miss a couple... */
+ INS(I_GWROPT);
+#endif
+ INS(I_SENDFD);
+ INS(I_RECVFD);
+ INS(I_LIST);
+ INS(I_ATMARK);
+ INS(I_CKBAND);
+ INS(I_GETBAND);
+ INS(I_CANPUT);
+ INS(I_SETCLTIME);
#ifdef I_GETCLTIME
- INS(I_GETCLTIME);
+ INS(I_GETCLTIME);
#endif
- INS(I_LINK);
- INS(I_UNLINK);
- INS(I_PLINK);
- INS(I_PUNLINK);
+ INS(I_LINK);
+ INS(I_UNLINK);
+ INS(I_PLINK);
+ INS(I_PUNLINK);
#endif
-
- return 0;
+
+ return 0;
}
static struct PyModuleDef fcntlmodule = {
- PyModuleDef_HEAD_INIT,
- "fcntl",
- module_doc,
- -1,
- fcntl_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "fcntl",
+ module_doc,
+ -1,
+ fcntl_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_fcntl(void)
{
- PyObject *m, *d;
+ PyObject *m, *d;
- /* Create the module and add the functions and documentation */
- m = PyModule_Create(&fcntlmodule);
- if (m == NULL)
- return NULL;
+ /* Create the module and add the functions and documentation */
+ m = PyModule_Create(&fcntlmodule);
+ if (m == NULL)
+ return NULL;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- all_ins(d);
- return m;
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ all_ins(d);
+ return m;
}
diff --git a/Modules/fpectlmodule.c b/Modules/fpectlmodule.c
index 6e6a616..1bb51cf 100644
--- a/Modules/fpectlmodule.c
+++ b/Modules/fpectlmodule.c
@@ -1,6 +1,6 @@
/*
- ---------------------------------------------------------------------
- / Copyright (c) 1996. \
+ ---------------------------------------------------------------------
+ / Copyright (c) 1996. \
| The Regents of the University of California. |
| All rights reserved. |
| |
@@ -32,12 +32,12 @@
| opinions of authors expressed herein do not necessarily state or |
| reflect those of the United States Government or the University |
| of California, and shall not be used for advertising or product |
- \ endorsement purposes. /
- ---------------------------------------------------------------------
+ \ endorsement purposes. /
+ ---------------------------------------------------------------------
*/
/*
- Floating point exception control module.
+ Floating point exception control module.
This Python module provides bare-bones control over floating point
units from several hardware manufacturers. Specifically, it allows
@@ -96,8 +96,8 @@ static PyObject *turnon_sigfpe (PyObject *self,PyObject *args);
static PyObject *turnoff_sigfpe (PyObject *self,PyObject *args);
static PyMethodDef fpectl_methods[] = {
- {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS},
- {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS},
+ {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS},
+ {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS},
{0,0}
};
@@ -122,19 +122,19 @@ static void fpe_reset(Sigfunc *handler)
* My usage doesn't follow the man page exactly. Maybe somebody
* else can explain handle_sigfpes to me....
* cc -c -I/usr/local/python/include fpectlmodule.c
- * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe
+ * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe
*/
#include <sigfpe.h>
typedef void user_routine (unsigned[5], int[2]);
typedef void abort_routine (unsigned long);
handle_sigfpes(_OFF, 0,
- (user_routine *)0,
- _TURN_OFF_HANDLER_ON_ERROR,
- NULL);
+ (user_routine *)0,
+ _TURN_OFF_HANDLER_ON_ERROR,
+ NULL);
handle_sigfpes(_ON, _EN_OVERFL | _EN_DIVZERO | _EN_INVALID,
- (user_routine *)0,
- _ABORT_ON_ERROR,
- NULL);
+ (user_routine *)0,
+ _ABORT_ON_ERROR,
+ NULL);
PyOS_setsig(SIGFPE, handler);
/*-- SunOS and Solaris ----------------------------------------------------*/
@@ -195,16 +195,16 @@ static void fpe_reset(Sigfunc *handler)
/*-- DEC ALPHA VMS --------------------------------------------------------*/
#elif defined(__ALPHA) && defined(__VMS)
- IEEE clrmsk;
- IEEE setmsk;
- clrmsk.ieee$q_flags =
- IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
- IEEE$M_MAP_UMZ;
- setmsk.ieee$q_flags =
- IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE |
- IEEE$M_TRAP_ENABLE_OVF;
- sys$ieee_set_fp_control(&clrmsk, &setmsk, 0);
- PyOS_setsig(SIGFPE, handler);
+ IEEE clrmsk;
+ IEEE setmsk;
+ clrmsk.ieee$q_flags =
+ IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
+ IEEE$M_MAP_UMZ;
+ setmsk.ieee$q_flags =
+ IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE |
+ IEEE$M_TRAP_ENABLE_OVF;
+ sys$ieee_set_fp_control(&clrmsk, &setmsk, 0);
+ PyOS_setsig(SIGFPE, handler);
/*-- HP IA64 VMS --------------------------------------------------------*/
#elif defined(__ia64) && defined(__VMS)
@@ -263,13 +263,13 @@ static PyObject *turnoff_sigfpe(PyObject *self,PyObject *args)
fpresetsticky(fpgetsticky());
fpsetmask(0);
#elif defined(__VMS)
- IEEE clrmsk;
- clrmsk.ieee$q_flags =
- IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
- IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV |
- IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF |
- IEEE$M_INHERIT;
- sys$ieee_set_fp_control(&clrmsk, 0, 0);
+ IEEE clrmsk;
+ clrmsk.ieee$q_flags =
+ IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
+ IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV |
+ IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF |
+ IEEE$M_INHERIT;
+ sys$ieee_set_fp_control(&clrmsk, 0, 0);
#else
fputs("Operation not implemented\n", stderr);
#endif
@@ -288,15 +288,15 @@ static void sigfpe_handler(int signo)
}
static struct PyModuleDef fpectlmodule = {
- PyModuleDef_HEAD_INIT,
- "fpectl",
- NULL,
- -1,
- fpectl_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "fpectl",
+ NULL,
+ -1,
+ fpectl_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC PyInit_fpectl(void)
@@ -304,11 +304,11 @@ PyMODINIT_FUNC PyInit_fpectl(void)
PyObject *m, *d;
m = PyModule_Create(&fpectlmodule);
if (m == NULL)
- return NULL;
+ return NULL;
d = PyModule_GetDict(m);
fpe_error = PyErr_NewException("fpectl.error", NULL, NULL);
if (fpe_error != NULL)
- PyDict_SetItemString(d, "error", fpe_error);
+ PyDict_SetItemString(d, "error", fpe_error);
return m;
}
diff --git a/Modules/fpetestmodule.c b/Modules/fpetestmodule.c
index 64acd3d..5b6c220 100644
--- a/Modules/fpetestmodule.c
+++ b/Modules/fpetestmodule.c
@@ -1,6 +1,6 @@
/*
- ---------------------------------------------------------------------
- / Copyright (c) 1996. \
+ ---------------------------------------------------------------------
+ / Copyright (c) 1996. \
| The Regents of the University of California. |
| All rights reserved. |
| |
@@ -32,12 +32,12 @@
| opinions of authors expressed herein do not necessarily state or |
| reflect those of the United States Government or the University |
| of California, and shall not be used for advertising or product |
- \ endorsement purposes. /
- ---------------------------------------------------------------------
+ \ endorsement purposes. /
+ ---------------------------------------------------------------------
*/
/*
- Floating point exception test module.
+ Floating point exception test module.
*/
@@ -55,7 +55,7 @@ static double nest3(double);
static void printerr(double);
static PyMethodDef fpetest_methods[] = {
- {"test", (PyCFunction) test, METH_VARARGS},
+ {"test", (PyCFunction) test, METH_VARARGS},
{0,0}
};
@@ -174,15 +174,15 @@ static double overflow(double b)
}
static struct PyModuleDef fpetestmodule = {
- PyModuleDef_HEAD_INIT,
- "fpetest",
- NULL,
- -1,
- fpetest_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "fpetest",
+ NULL,
+ -1,
+ fpetest_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC PyInit_fpetest(void)
@@ -191,10 +191,10 @@ PyMODINIT_FUNC PyInit_fpetest(void)
m = PyModule_Create(&fpetestmodule);
if (m == NULL)
- return NULL;
+ return NULL;
d = PyModule_GetDict(m);
fpe_error = PyErr_NewException("fpetest.error", NULL, NULL);
if (fpe_error != NULL)
- PyDict_SetItemString(d, "error", fpe_error);
+ PyDict_SetItemString(d, "error", fpe_error);
return m;
}
diff --git a/Modules/gcmodule.c b/Modules/gcmodule.c
index 3058724..3717a27 100644
--- a/Modules/gcmodule.c
+++ b/Modules/gcmodule.c
@@ -24,7 +24,7 @@
*/
#include "Python.h"
-#include "frameobject.h" /* for PyFrame_ClearFreeList */
+#include "frameobject.h" /* for PyFrame_ClearFreeList */
/* Get an object's GC head */
#define AS_GC(o) ((PyGC_Head *)(o)-1)
@@ -35,10 +35,10 @@
/*** Global GC state ***/
struct gc_generation {
- PyGC_Head head;
- int threshold; /* collection threshold */
- int count; /* count of allocations or collections of younger
- generations */
+ PyGC_Head head;
+ int threshold; /* collection threshold */
+ int count; /* count of allocations or collections of younger
+ generations */
};
#define NUM_GENERATIONS 3
@@ -46,10 +46,10 @@ struct gc_generation {
/* linked lists of container objects */
static struct gc_generation generations[NUM_GENERATIONS] = {
- /* PyGC_Head, threshold, count */
- {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},
- {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},
- {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},
+ /* PyGC_Head, threshold, count */
+ {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},
+ {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},
+ {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},
};
PyGC_Head *_PyGC_generation0 = GEN_HEAD(0);
@@ -91,7 +91,7 @@ static Py_ssize_t long_lived_pending = 0;
In addition to the various configurable thresholds, we only trigger a
full collection if the ratio
- long_lived_pending / long_lived_total
+ long_lived_pending / long_lived_total
is above a given value (hardwired to 25%).
The reason is that, while "non-full" collections (i.e., collections of
@@ -113,18 +113,18 @@ static Py_ssize_t long_lived_pending = 0;
This heuristic was suggested by Martin von Löwis on python-dev in
June 2008. His original analysis and proposal can be found at:
- http://mail.python.org/pipermail/python-dev/2008-June/080579.html
+ http://mail.python.org/pipermail/python-dev/2008-June/080579.html
*/
/* set for debugging information */
-#define DEBUG_STATS (1<<0) /* print collection statistics */
-#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
-#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
-#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
-#define DEBUG_LEAK DEBUG_COLLECTABLE | \
- DEBUG_UNCOLLECTABLE | \
- DEBUG_SAVEALL
+#define DEBUG_STATS (1<<0) /* print collection statistics */
+#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
+#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
+#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
+#define DEBUG_LEAK DEBUG_COLLECTABLE | \
+ DEBUG_UNCOLLECTABLE | \
+ DEBUG_SAVEALL
static int debug;
static PyObject *tmod = NULL;
@@ -167,28 +167,28 @@ GC_TENTATIVELY_UNREACHABLE
it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
----------------------------------------------------------------------------
*/
-#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
-#define GC_REACHABLE _PyGC_REFS_REACHABLE
-#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
+#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
+#define GC_REACHABLE _PyGC_REFS_REACHABLE
+#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
#define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED)
#define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE)
#define IS_TENTATIVELY_UNREACHABLE(o) ( \
- (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
+ (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
/*** list functions ***/
static void
gc_list_init(PyGC_Head *list)
{
- list->gc.gc_prev = list;
- list->gc.gc_next = list;
+ list->gc.gc_prev = list;
+ list->gc.gc_next = list;
}
static int
gc_list_is_empty(PyGC_Head *list)
{
- return (list->gc.gc_next == list);
+ return (list->gc.gc_next == list);
}
#if 0
@@ -197,10 +197,10 @@ gc_list_is_empty(PyGC_Head *list)
static void
gc_list_append(PyGC_Head *node, PyGC_Head *list)
{
- node->gc.gc_next = list;
- node->gc.gc_prev = list->gc.gc_prev;
- node->gc.gc_prev->gc.gc_next = node;
- list->gc.gc_prev = node;
+ node->gc.gc_next = list;
+ node->gc.gc_prev = list->gc.gc_prev;
+ node->gc.gc_prev->gc.gc_next = node;
+ list->gc.gc_prev = node;
}
#endif
@@ -208,9 +208,9 @@ gc_list_append(PyGC_Head *node, PyGC_Head *list)
static void
gc_list_remove(PyGC_Head *node)
{
- node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
- node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
- node->gc.gc_next = NULL; /* object is not currently tracked */
+ node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
+ node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
+ node->gc.gc_next = NULL; /* object is not currently tracked */
}
/* Move `node` from the gc list it's currently in (which is not explicitly
@@ -220,43 +220,43 @@ gc_list_remove(PyGC_Head *node)
static void
gc_list_move(PyGC_Head *node, PyGC_Head *list)
{
- PyGC_Head *new_prev;
- PyGC_Head *current_prev = node->gc.gc_prev;
- PyGC_Head *current_next = node->gc.gc_next;
- /* Unlink from current list. */
- current_prev->gc.gc_next = current_next;
- current_next->gc.gc_prev = current_prev;
- /* Relink at end of new list. */
- new_prev = node->gc.gc_prev = list->gc.gc_prev;
- new_prev->gc.gc_next = list->gc.gc_prev = node;
- node->gc.gc_next = list;
+ PyGC_Head *new_prev;
+ PyGC_Head *current_prev = node->gc.gc_prev;
+ PyGC_Head *current_next = node->gc.gc_next;
+ /* Unlink from current list. */
+ current_prev->gc.gc_next = current_next;
+ current_next->gc.gc_prev = current_prev;
+ /* Relink at end of new list. */
+ new_prev = node->gc.gc_prev = list->gc.gc_prev;
+ new_prev->gc.gc_next = list->gc.gc_prev = node;
+ node->gc.gc_next = list;
}
/* append list `from` onto list `to`; `from` becomes an empty list */
static void
gc_list_merge(PyGC_Head *from, PyGC_Head *to)
{
- PyGC_Head *tail;
- assert(from != to);
- if (!gc_list_is_empty(from)) {
- tail = to->gc.gc_prev;
- tail->gc.gc_next = from->gc.gc_next;
- tail->gc.gc_next->gc.gc_prev = tail;
- to->gc.gc_prev = from->gc.gc_prev;
- to->gc.gc_prev->gc.gc_next = to;
- }
- gc_list_init(from);
+ PyGC_Head *tail;
+ assert(from != to);
+ if (!gc_list_is_empty(from)) {
+ tail = to->gc.gc_prev;
+ tail->gc.gc_next = from->gc.gc_next;
+ tail->gc.gc_next->gc.gc_prev = tail;
+ to->gc.gc_prev = from->gc.gc_prev;
+ to->gc.gc_prev->gc.gc_next = to;
+ }
+ gc_list_init(from);
}
static Py_ssize_t
gc_list_size(PyGC_Head *list)
{
- PyGC_Head *gc;
- Py_ssize_t n = 0;
- for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
- n++;
- }
- return n;
+ PyGC_Head *gc;
+ Py_ssize_t n = 0;
+ for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
+ n++;
+ }
+ return n;
}
/* Append objects in a GC list to a Python list.
@@ -265,16 +265,16 @@ gc_list_size(PyGC_Head *list)
static int
append_objects(PyObject *py_list, PyGC_Head *gc_list)
{
- PyGC_Head *gc;
- for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
- PyObject *op = FROM_GC(gc);
- if (op != py_list) {
- if (PyList_Append(py_list, op)) {
- return -1; /* exception */
- }
- }
- }
- return 0;
+ PyGC_Head *gc;
+ for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
+ PyObject *op = FROM_GC(gc);
+ if (op != py_list) {
+ if (PyList_Append(py_list, op)) {
+ return -1; /* exception */
+ }
+ }
+ }
+ return 0;
}
/*** end of list stuff ***/
@@ -287,48 +287,48 @@ append_objects(PyObject *py_list, PyGC_Head *gc_list)
static void
update_refs(PyGC_Head *containers)
{
- PyGC_Head *gc = containers->gc.gc_next;
- for (; gc != containers; gc = gc->gc.gc_next) {
- assert(gc->gc.gc_refs == GC_REACHABLE);
- gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
- /* Python's cyclic gc should never see an incoming refcount
- * of 0: if something decref'ed to 0, it should have been
- * deallocated immediately at that time.
- * Possible cause (if the assert triggers): a tp_dealloc
- * routine left a gc-aware object tracked during its teardown
- * phase, and did something-- or allowed something to happen --
- * that called back into Python. gc can trigger then, and may
- * see the still-tracked dying object. Before this assert
- * was added, such mistakes went on to allow gc to try to
- * delete the object again. In a debug build, that caused
- * a mysterious segfault, when _Py_ForgetReference tried
- * to remove the object from the doubly-linked list of all
- * objects a second time. In a release build, an actual
- * double deallocation occurred, which leads to corruption
- * of the allocator's internal bookkeeping pointers. That's
- * so serious that maybe this should be a release-build
- * check instead of an assert?
- */
- assert(gc->gc.gc_refs != 0);
- }
+ PyGC_Head *gc = containers->gc.gc_next;
+ for (; gc != containers; gc = gc->gc.gc_next) {
+ assert(gc->gc.gc_refs == GC_REACHABLE);
+ gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
+ /* Python's cyclic gc should never see an incoming refcount
+ * of 0: if something decref'ed to 0, it should have been
+ * deallocated immediately at that time.
+ * Possible cause (if the assert triggers): a tp_dealloc
+ * routine left a gc-aware object tracked during its teardown
+ * phase, and did something-- or allowed something to happen --
+ * that called back into Python. gc can trigger then, and may
+ * see the still-tracked dying object. Before this assert
+ * was added, such mistakes went on to allow gc to try to
+ * delete the object again. In a debug build, that caused
+ * a mysterious segfault, when _Py_ForgetReference tried
+ * to remove the object from the doubly-linked list of all
+ * objects a second time. In a release build, an actual
+ * double deallocation occurred, which leads to corruption
+ * of the allocator's internal bookkeeping pointers. That's
+ * so serious that maybe this should be a release-build
+ * check instead of an assert?
+ */
+ assert(gc->gc.gc_refs != 0);
+ }
}
/* A traversal callback for subtract_refs. */
static int
visit_decref(PyObject *op, void *data)
{
- assert(op != NULL);
- if (PyObject_IS_GC(op)) {
- PyGC_Head *gc = AS_GC(op);
- /* We're only interested in gc_refs for objects in the
- * generation being collected, which can be recognized
- * because only they have positive gc_refs.
- */
- assert(gc->gc.gc_refs != 0); /* else refcount was too small */
- if (gc->gc.gc_refs > 0)
- gc->gc.gc_refs--;
- }
- return 0;
+ assert(op != NULL);
+ if (PyObject_IS_GC(op)) {
+ PyGC_Head *gc = AS_GC(op);
+ /* We're only interested in gc_refs for objects in the
+ * generation being collected, which can be recognized
+ * because only they have positive gc_refs.
+ */
+ assert(gc->gc.gc_refs != 0); /* else refcount was too small */
+ if (gc->gc.gc_refs > 0)
+ gc->gc.gc_refs--;
+ }
+ return 0;
}
/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
@@ -339,57 +339,57 @@ visit_decref(PyObject *op, void *data)
static void
subtract_refs(PyGC_Head *containers)
{
- traverseproc traverse;
- PyGC_Head *gc = containers->gc.gc_next;
- for (; gc != containers; gc=gc->gc.gc_next) {
- traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
- (void) traverse(FROM_GC(gc),
- (visitproc)visit_decref,
- NULL);
- }
+ traverseproc traverse;
+ PyGC_Head *gc = containers->gc.gc_next;
+ for (; gc != containers; gc=gc->gc.gc_next) {
+ traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
+ (void) traverse(FROM_GC(gc),
+ (visitproc)visit_decref,
+ NULL);
+ }
}
/* A traversal callback for move_unreachable. */
static int
visit_reachable(PyObject *op, PyGC_Head *reachable)
{
- if (PyObject_IS_GC(op)) {
- PyGC_Head *gc = AS_GC(op);
- const Py_ssize_t gc_refs = gc->gc.gc_refs;
-
- if (gc_refs == 0) {
- /* This is in move_unreachable's 'young' list, but
- * the traversal hasn't yet gotten to it. All
- * we need to do is tell move_unreachable that it's
- * reachable.
- */
- gc->gc.gc_refs = 1;
- }
- else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
- /* This had gc_refs = 0 when move_unreachable got
- * to it, but turns out it's reachable after all.
- * Move it back to move_unreachable's 'young' list,
- * and move_unreachable will eventually get to it
- * again.
- */
- gc_list_move(gc, reachable);
- gc->gc.gc_refs = 1;
- }
- /* Else there's nothing to do.
- * If gc_refs > 0, it must be in move_unreachable's 'young'
- * list, and move_unreachable will eventually get to it.
- * If gc_refs == GC_REACHABLE, it's either in some other
- * generation so we don't care about it, or move_unreachable
- * already dealt with it.
- * If gc_refs == GC_UNTRACKED, it must be ignored.
- */
- else {
- assert(gc_refs > 0
- || gc_refs == GC_REACHABLE
- || gc_refs == GC_UNTRACKED);
- }
- }
- return 0;
+ if (PyObject_IS_GC(op)) {
+ PyGC_Head *gc = AS_GC(op);
+ const Py_ssize_t gc_refs = gc->gc.gc_refs;
+
+ if (gc_refs == 0) {
+ /* This is in move_unreachable's 'young' list, but
+ * the traversal hasn't yet gotten to it. All
+ * we need to do is tell move_unreachable that it's
+ * reachable.
+ */
+ gc->gc.gc_refs = 1;
+ }
+ else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
+ /* This had gc_refs = 0 when move_unreachable got
+ * to it, but turns out it's reachable after all.
+ * Move it back to move_unreachable's 'young' list,
+ * and move_unreachable will eventually get to it
+ * again.
+ */
+ gc_list_move(gc, reachable);
+ gc->gc.gc_refs = 1;
+ }
+ /* Else there's nothing to do.
+ * If gc_refs > 0, it must be in move_unreachable's 'young'
+ * list, and move_unreachable will eventually get to it.
+ * If gc_refs == GC_REACHABLE, it's either in some other
+ * generation so we don't care about it, or move_unreachable
+ * already dealt with it.
+ * If gc_refs == GC_UNTRACKED, it must be ignored.
+ */
+ else {
+ assert(gc_refs > 0
+ || gc_refs == GC_REACHABLE
+ || gc_refs == GC_UNTRACKED);
+ }
+ }
+ return 0;
}
/* Move the unreachable objects from young to unreachable. After this,
@@ -403,68 +403,68 @@ visit_reachable(PyObject *op, PyGC_Head *reachable)
static void
move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
{
- PyGC_Head *gc = young->gc.gc_next;
-
- /* Invariants: all objects "to the left" of us in young have gc_refs
- * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
- * from outside the young list as it was at entry. All other objects
- * from the original young "to the left" of us are in unreachable now,
- * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
- * left of us in 'young' now have been scanned, and no objects here
- * or to the right have been scanned yet.
- */
-
- while (gc != young) {
- PyGC_Head *next;
-
- if (gc->gc.gc_refs) {
- /* gc is definitely reachable from outside the
- * original 'young'. Mark it as such, and traverse
- * its pointers to find any other objects that may
- * be directly reachable from it. Note that the
- * call to tp_traverse may append objects to young,
- * so we have to wait until it returns to determine
- * the next object to visit.
- */
- PyObject *op = FROM_GC(gc);
- traverseproc traverse = Py_TYPE(op)->tp_traverse;
- assert(gc->gc.gc_refs > 0);
- gc->gc.gc_refs = GC_REACHABLE;
- (void) traverse(op,
- (visitproc)visit_reachable,
- (void *)young);
- next = gc->gc.gc_next;
- if (PyTuple_CheckExact(op)) {
- _PyTuple_MaybeUntrack(op);
- }
- else if (PyDict_CheckExact(op)) {
- _PyDict_MaybeUntrack(op);
- }
- }
- else {
- /* This *may* be unreachable. To make progress,
- * assume it is. gc isn't directly reachable from
- * any object we've already traversed, but may be
- * reachable from an object we haven't gotten to yet.
- * visit_reachable will eventually move gc back into
- * young if that's so, and we'll see it again.
- */
- next = gc->gc.gc_next;
- gc_list_move(gc, unreachable);
- gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
- }
- gc = next;
- }
+ PyGC_Head *gc = young->gc.gc_next;
+
+ /* Invariants: all objects "to the left" of us in young have gc_refs
+ * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
+ * from outside the young list as it was at entry. All other objects
+ * from the original young "to the left" of us are in unreachable now,
+ * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
+ * left of us in 'young' now have been scanned, and no objects here
+ * or to the right have been scanned yet.
+ */
+
+ while (gc != young) {
+ PyGC_Head *next;
+
+ if (gc->gc.gc_refs) {
+ /* gc is definitely reachable from outside the
+ * original 'young'. Mark it as such, and traverse
+ * its pointers to find any other objects that may
+ * be directly reachable from it. Note that the
+ * call to tp_traverse may append objects to young,
+ * so we have to wait until it returns to determine
+ * the next object to visit.
+ */
+ PyObject *op = FROM_GC(gc);
+ traverseproc traverse = Py_TYPE(op)->tp_traverse;
+ assert(gc->gc.gc_refs > 0);
+ gc->gc.gc_refs = GC_REACHABLE;
+ (void) traverse(op,
+ (visitproc)visit_reachable,
+ (void *)young);
+ next = gc->gc.gc_next;
+ if (PyTuple_CheckExact(op)) {
+ _PyTuple_MaybeUntrack(op);
+ }
+ else if (PyDict_CheckExact(op)) {
+ _PyDict_MaybeUntrack(op);
+ }
+ }
+ else {
+ /* This *may* be unreachable. To make progress,
+ * assume it is. gc isn't directly reachable from
+ * any object we've already traversed, but may be
+ * reachable from an object we haven't gotten to yet.
+ * visit_reachable will eventually move gc back into
+ * young if that's so, and we'll see it again.
+ */
+ next = gc->gc.gc_next;
+ gc_list_move(gc, unreachable);
+ gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
+ }
+ gc = next;
+ }
}
/* Return true if object has a finalization method. */
static int
has_finalizer(PyObject *op)
{
- if (PyGen_CheckExact(op))
- return PyGen_NeedsFinalizing((PyGenObject *)op);
- else
- return op->ob_type->tp_del != NULL;
+ if (PyGen_CheckExact(op))
+ return PyGen_NeedsFinalizing((PyGenObject *)op);
+ else
+ return op->ob_type->tp_del != NULL;
}
/* Move the objects in unreachable with __del__ methods into `finalizers`.
@@ -474,37 +474,37 @@ has_finalizer(PyObject *op)
static void
move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
{
- PyGC_Head *gc;
- PyGC_Head *next;
-
- /* March over unreachable. Move objects with finalizers into
- * `finalizers`.
- */
- for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
- PyObject *op = FROM_GC(gc);
-
- assert(IS_TENTATIVELY_UNREACHABLE(op));
- next = gc->gc.gc_next;
-
- if (has_finalizer(op)) {
- gc_list_move(gc, finalizers);
- gc->gc.gc_refs = GC_REACHABLE;
- }
- }
+ PyGC_Head *gc;
+ PyGC_Head *next;
+
+ /* March over unreachable. Move objects with finalizers into
+ * `finalizers`.
+ */
+ for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
+ PyObject *op = FROM_GC(gc);
+
+ assert(IS_TENTATIVELY_UNREACHABLE(op));
+ next = gc->gc.gc_next;
+
+ if (has_finalizer(op)) {
+ gc_list_move(gc, finalizers);
+ gc->gc.gc_refs = GC_REACHABLE;
+ }
+ }
}
/* A traversal callback for move_finalizer_reachable. */
static int
visit_move(PyObject *op, PyGC_Head *tolist)
{
- if (PyObject_IS_GC(op)) {
- if (IS_TENTATIVELY_UNREACHABLE(op)) {
- PyGC_Head *gc = AS_GC(op);
- gc_list_move(gc, tolist);
- gc->gc.gc_refs = GC_REACHABLE;
- }
- }
- return 0;
+ if (PyObject_IS_GC(op)) {
+ if (IS_TENTATIVELY_UNREACHABLE(op)) {
+ PyGC_Head *gc = AS_GC(op);
+ gc_list_move(gc, tolist);
+ gc->gc.gc_refs = GC_REACHABLE;
+ }
+ }
+ return 0;
}
/* Move objects that are reachable from finalizers, from the unreachable set
@@ -513,15 +513,15 @@ visit_move(PyObject *op, PyGC_Head *tolist)
static void
move_finalizer_reachable(PyGC_Head *finalizers)
{
- traverseproc traverse;
- PyGC_Head *gc = finalizers->gc.gc_next;
- for (; gc != finalizers; gc = gc->gc.gc_next) {
- /* Note that the finalizers list may grow during this. */
- traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
- (void) traverse(FROM_GC(gc),
- (visitproc)visit_move,
- (void *)finalizers);
- }
+ traverseproc traverse;
+ PyGC_Head *gc = finalizers->gc.gc_next;
+ for (; gc != finalizers; gc = gc->gc.gc_next) {
+ /* Note that the finalizers list may grow during this. */
+ traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
+ (void) traverse(FROM_GC(gc),
+ (visitproc)visit_move,
+ (void *)finalizers);
+ }
}
/* Clear all weakrefs to unreachable objects, and if such a weakref has a
@@ -538,150 +538,150 @@ move_finalizer_reachable(PyGC_Head *finalizers)
static int
handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
{
- PyGC_Head *gc;
- PyObject *op; /* generally FROM_GC(gc) */
- PyWeakReference *wr; /* generally a cast of op */
- PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
- PyGC_Head *next;
- int num_freed = 0;
-
- gc_list_init(&wrcb_to_call);
-
- /* Clear all weakrefs to the objects in unreachable. If such a weakref
- * also has a callback, move it into `wrcb_to_call` if the callback
- * needs to be invoked. Note that we cannot invoke any callbacks until
- * all weakrefs to unreachable objects are cleared, lest the callback
- * resurrect an unreachable object via a still-active weakref. We
- * make another pass over wrcb_to_call, invoking callbacks, after this
- * pass completes.
- */
- for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
- PyWeakReference **wrlist;
-
- op = FROM_GC(gc);
- assert(IS_TENTATIVELY_UNREACHABLE(op));
- next = gc->gc.gc_next;
-
- if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
- continue;
-
- /* It supports weakrefs. Does it have any? */
- wrlist = (PyWeakReference **)
- PyObject_GET_WEAKREFS_LISTPTR(op);
-
- /* `op` may have some weakrefs. March over the list, clear
- * all the weakrefs, and move the weakrefs with callbacks
- * that must be called into wrcb_to_call.
- */
- for (wr = *wrlist; wr != NULL; wr = *wrlist) {
- PyGC_Head *wrasgc; /* AS_GC(wr) */
-
- /* _PyWeakref_ClearRef clears the weakref but leaves
- * the callback pointer intact. Obscure: it also
- * changes *wrlist.
- */
- assert(wr->wr_object == op);
- _PyWeakref_ClearRef(wr);
- assert(wr->wr_object == Py_None);
- if (wr->wr_callback == NULL)
- continue; /* no callback */
-
- /* Headache time. `op` is going away, and is weakly referenced by
- * `wr`, which has a callback. Should the callback be invoked? If wr
- * is also trash, no:
- *
- * 1. There's no need to call it. The object and the weakref are
- * both going away, so it's legitimate to pretend the weakref is
- * going away first. The user has to ensure a weakref outlives its
- * referent if they want a guarantee that the wr callback will get
- * invoked.
- *
- * 2. It may be catastrophic to call it. If the callback is also in
- * cyclic trash (CT), then although the CT is unreachable from
- * outside the current generation, CT may be reachable from the
- * callback. Then the callback could resurrect insane objects.
- *
- * Since the callback is never needed and may be unsafe in this case,
- * wr is simply left in the unreachable set. Note that because we
- * already called _PyWeakref_ClearRef(wr), its callback will never
- * trigger.
- *
- * OTOH, if wr isn't part of CT, we should invoke the callback: the
- * weakref outlived the trash. Note that since wr isn't CT in this
- * case, its callback can't be CT either -- wr acted as an external
- * root to this generation, and therefore its callback did too. So
- * nothing in CT is reachable from the callback either, so it's hard
- * to imagine how calling it later could create a problem for us. wr
- * is moved to wrcb_to_call in this case.
- */
- if (IS_TENTATIVELY_UNREACHABLE(wr))
- continue;
- assert(IS_REACHABLE(wr));
-
- /* Create a new reference so that wr can't go away
- * before we can process it again.
- */
- Py_INCREF(wr);
-
- /* Move wr to wrcb_to_call, for the next pass. */
- wrasgc = AS_GC(wr);
- assert(wrasgc != next); /* wrasgc is reachable, but
- next isn't, so they can't
- be the same */
- gc_list_move(wrasgc, &wrcb_to_call);
- }
- }
-
- /* Invoke the callbacks we decided to honor. It's safe to invoke them
- * because they can't reference unreachable objects.
- */
- while (! gc_list_is_empty(&wrcb_to_call)) {
- PyObject *temp;
- PyObject *callback;
-
- gc = wrcb_to_call.gc.gc_next;
- op = FROM_GC(gc);
- assert(IS_REACHABLE(op));
- assert(PyWeakref_Check(op));
- wr = (PyWeakReference *)op;
- callback = wr->wr_callback;
- assert(callback != NULL);
-
- /* copy-paste of weakrefobject.c's handle_callback() */
- temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
- if (temp == NULL)
- PyErr_WriteUnraisable(callback);
- else
- Py_DECREF(temp);
-
- /* Give up the reference we created in the first pass. When
- * op's refcount hits 0 (which it may or may not do right now),
- * op's tp_dealloc will decref op->wr_callback too. Note
- * that the refcount probably will hit 0 now, and because this
- * weakref was reachable to begin with, gc didn't already
- * add it to its count of freed objects. Example: a reachable
- * weak value dict maps some key to this reachable weakref.
- * The callback removes this key->weakref mapping from the
- * dict, leaving no other references to the weakref (excepting
- * ours).
- */
- Py_DECREF(op);
- if (wrcb_to_call.gc.gc_next == gc) {
- /* object is still alive -- move it */
- gc_list_move(gc, old);
- }
- else
- ++num_freed;
- }
-
- return num_freed;
+ PyGC_Head *gc;
+ PyObject *op; /* generally FROM_GC(gc) */
+ PyWeakReference *wr; /* generally a cast of op */
+ PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
+ PyGC_Head *next;
+ int num_freed = 0;
+
+ gc_list_init(&wrcb_to_call);
+
+ /* Clear all weakrefs to the objects in unreachable. If such a weakref
+ * also has a callback, move it into `wrcb_to_call` if the callback
+ * needs to be invoked. Note that we cannot invoke any callbacks until
+ * all weakrefs to unreachable objects are cleared, lest the callback
+ * resurrect an unreachable object via a still-active weakref. We
+ * make another pass over wrcb_to_call, invoking callbacks, after this
+ * pass completes.
+ */
+ for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
+ PyWeakReference **wrlist;
+
+ op = FROM_GC(gc);
+ assert(IS_TENTATIVELY_UNREACHABLE(op));
+ next = gc->gc.gc_next;
+
+ if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
+ continue;
+
+ /* It supports weakrefs. Does it have any? */
+ wrlist = (PyWeakReference **)
+ PyObject_GET_WEAKREFS_LISTPTR(op);
+
+ /* `op` may have some weakrefs. March over the list, clear
+ * all the weakrefs, and move the weakrefs with callbacks
+ * that must be called into wrcb_to_call.
+ */
+ for (wr = *wrlist; wr != NULL; wr = *wrlist) {
+ PyGC_Head *wrasgc; /* AS_GC(wr) */
+
+ /* _PyWeakref_ClearRef clears the weakref but leaves
+ * the callback pointer intact. Obscure: it also
+ * changes *wrlist.
+ */
+ assert(wr->wr_object == op);
+ _PyWeakref_ClearRef(wr);
+ assert(wr->wr_object == Py_None);
+ if (wr->wr_callback == NULL)
+ continue; /* no callback */
+
+ /* Headache time. `op` is going away, and is weakly referenced by
+ * `wr`, which has a callback. Should the callback be invoked? If wr
+ * is also trash, no:
+ *
+ * 1. There's no need to call it. The object and the weakref are
+ * both going away, so it's legitimate to pretend the weakref is
+ * going away first. The user has to ensure a weakref outlives its
+ * referent if they want a guarantee that the wr callback will get
+ * invoked.
+ *
+ * 2. It may be catastrophic to call it. If the callback is also in
+ * cyclic trash (CT), then although the CT is unreachable from
+ * outside the current generation, CT may be reachable from the
+ * callback. Then the callback could resurrect insane objects.
+ *
+ * Since the callback is never needed and may be unsafe in this case,
+ * wr is simply left in the unreachable set. Note that because we
+ * already called _PyWeakref_ClearRef(wr), its callback will never
+ * trigger.
+ *
+ * OTOH, if wr isn't part of CT, we should invoke the callback: the
+ * weakref outlived the trash. Note that since wr isn't CT in this
+ * case, its callback can't be CT either -- wr acted as an external
+ * root to this generation, and therefore its callback did too. So
+ * nothing in CT is reachable from the callback either, so it's hard
+ * to imagine how calling it later could create a problem for us. wr
+ * is moved to wrcb_to_call in this case.
+ */
+ if (IS_TENTATIVELY_UNREACHABLE(wr))
+ continue;
+ assert(IS_REACHABLE(wr));
+
+ /* Create a new reference so that wr can't go away
+ * before we can process it again.
+ */
+ Py_INCREF(wr);
+
+ /* Move wr to wrcb_to_call, for the next pass. */
+ wrasgc = AS_GC(wr);
+ assert(wrasgc != next); /* wrasgc is reachable, but
+ next isn't, so they can't
+ be the same */
+ gc_list_move(wrasgc, &wrcb_to_call);
+ }
+ }
+
+ /* Invoke the callbacks we decided to honor. It's safe to invoke them
+ * because they can't reference unreachable objects.
+ */
+ while (! gc_list_is_empty(&wrcb_to_call)) {
+ PyObject *temp;
+ PyObject *callback;
+
+ gc = wrcb_to_call.gc.gc_next;
+ op = FROM_GC(gc);
+ assert(IS_REACHABLE(op));
+ assert(PyWeakref_Check(op));
+ wr = (PyWeakReference *)op;
+ callback = wr->wr_callback;
+ assert(callback != NULL);
+
+ /* copy-paste of weakrefobject.c's handle_callback() */
+ temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
+ if (temp == NULL)
+ PyErr_WriteUnraisable(callback);
+ else
+ Py_DECREF(temp);
+
+ /* Give up the reference we created in the first pass. When
+ * op's refcount hits 0 (which it may or may not do right now),
+ * op's tp_dealloc will decref op->wr_callback too. Note
+ * that the refcount probably will hit 0 now, and because this
+ * weakref was reachable to begin with, gc didn't already
+ * add it to its count of freed objects. Example: a reachable
+ * weak value dict maps some key to this reachable weakref.
+ * The callback removes this key->weakref mapping from the
+ * dict, leaving no other references to the weakref (excepting
+ * ours).
+ */
+ Py_DECREF(op);
+ if (wrcb_to_call.gc.gc_next == gc) {
+ /* object is still alive -- move it */
+ gc_list_move(gc, old);
+ }
+ else
+ ++num_freed;
+ }
+
+ return num_freed;
}
static void
debug_cycle(char *msg, PyObject *op)
{
- PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
- msg, Py_TYPE(op)->tp_name, op);
+ PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
+ msg, Py_TYPE(op)->tp_name, op);
}
/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
@@ -696,56 +696,56 @@ debug_cycle(char *msg, PyObject *op)
static int
handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
{
- PyGC_Head *gc = finalizers->gc.gc_next;
-
- if (garbage == NULL) {
- garbage = PyList_New(0);
- if (garbage == NULL)
- Py_FatalError("gc couldn't create gc.garbage list");
- }
- for (; gc != finalizers; gc = gc->gc.gc_next) {
- PyObject *op = FROM_GC(gc);
-
- if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {
- if (PyList_Append(garbage, op) < 0)
- return -1;
- }
- }
-
- gc_list_merge(finalizers, old);
- return 0;
+ PyGC_Head *gc = finalizers->gc.gc_next;
+
+ if (garbage == NULL) {
+ garbage = PyList_New(0);
+ if (garbage == NULL)
+ Py_FatalError("gc couldn't create gc.garbage list");
+ }
+ for (; gc != finalizers; gc = gc->gc.gc_next) {
+ PyObject *op = FROM_GC(gc);
+
+ if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {
+ if (PyList_Append(garbage, op) < 0)
+ return -1;
+ }
+ }
+
+ gc_list_merge(finalizers, old);
+ return 0;
}
-/* Break reference cycles by clearing the containers involved. This is
+/* Break reference cycles by clearing the containers involved. This is
* tricky business as the lists can be changing and we don't know which
* objects may be freed. It is possible I screwed something up here.
*/
static void
delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
{
- inquiry clear;
-
- while (!gc_list_is_empty(collectable)) {
- PyGC_Head *gc = collectable->gc.gc_next;
- PyObject *op = FROM_GC(gc);
-
- assert(IS_TENTATIVELY_UNREACHABLE(op));
- if (debug & DEBUG_SAVEALL) {
- PyList_Append(garbage, op);
- }
- else {
- if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
- Py_INCREF(op);
- clear(op);
- Py_DECREF(op);
- }
- }
- if (collectable->gc.gc_next == gc) {
- /* object is still alive, move it, it may die later */
- gc_list_move(gc, old);
- gc->gc.gc_refs = GC_REACHABLE;
- }
- }
+ inquiry clear;
+
+ while (!gc_list_is_empty(collectable)) {
+ PyGC_Head *gc = collectable->gc.gc_next;
+ PyObject *op = FROM_GC(gc);
+
+ assert(IS_TENTATIVELY_UNREACHABLE(op));
+ if (debug & DEBUG_SAVEALL) {
+ PyList_Append(garbage, op);
+ }
+ else {
+ if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
+ Py_INCREF(op);
+ clear(op);
+ Py_DECREF(op);
+ }
+ }
+ if (collectable->gc.gc_next == gc) {
+ /* object is still alive, move it, it may die later */
+ gc_list_move(gc, old);
+ gc->gc.gc_refs = GC_REACHABLE;
+ }
+ }
}
/* Clear all free lists
@@ -756,30 +756,30 @@ delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
static void
clear_freelists(void)
{
- (void)PyMethod_ClearFreeList();
- (void)PyFrame_ClearFreeList();
- (void)PyCFunction_ClearFreeList();
- (void)PyTuple_ClearFreeList();
- (void)PyUnicode_ClearFreeList();
- (void)PyFloat_ClearFreeList();
+ (void)PyMethod_ClearFreeList();
+ (void)PyFrame_ClearFreeList();
+ (void)PyCFunction_ClearFreeList();
+ (void)PyTuple_ClearFreeList();
+ (void)PyUnicode_ClearFreeList();
+ (void)PyFloat_ClearFreeList();
}
static double
get_time(void)
{
- double result = 0;
- if (tmod != NULL) {
- PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
- if (f == NULL) {
- PyErr_Clear();
- }
- else {
- if (PyFloat_Check(f))
- result = PyFloat_AsDouble(f);
- Py_DECREF(f);
- }
- }
- return result;
+ double result = 0;
+ if (tmod != NULL) {
+ PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
+ if (f == NULL) {
+ PyErr_Clear();
+ }
+ else {
+ if (PyFloat_Check(f))
+ result = PyFloat_AsDouble(f);
+ Py_DECREF(f);
+ }
+ }
+ return result;
}
/* This is the main function. Read this to understand how the
@@ -787,184 +787,184 @@ get_time(void)
static Py_ssize_t
collect(int generation)
{
- int i;
- Py_ssize_t m = 0; /* # objects collected */
- Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
- PyGC_Head *young; /* the generation we are examining */
- PyGC_Head *old; /* next older generation */
- PyGC_Head unreachable; /* non-problematic unreachable trash */
- PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
- PyGC_Head *gc;
- double t1 = 0.0;
-
- if (delstr == NULL) {
- delstr = PyUnicode_InternFromString("__del__");
- if (delstr == NULL)
- Py_FatalError("gc couldn't allocate \"__del__\"");
- }
-
- if (debug & DEBUG_STATS) {
- PySys_WriteStderr("gc: collecting generation %d...\n",
- generation);
- PySys_WriteStderr("gc: objects in each generation:");
- for (i = 0; i < NUM_GENERATIONS; i++)
- PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
- gc_list_size(GEN_HEAD(i)));
- t1 = get_time();
- PySys_WriteStderr("\n");
- }
-
- /* update collection and allocation counters */
- if (generation+1 < NUM_GENERATIONS)
- generations[generation+1].count += 1;
- for (i = 0; i <= generation; i++)
- generations[i].count = 0;
-
- /* merge younger generations with one we are currently collecting */
- for (i = 0; i < generation; i++) {
- gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
- }
-
- /* handy references */
- young = GEN_HEAD(generation);
- if (generation < NUM_GENERATIONS-1)
- old = GEN_HEAD(generation+1);
- else
- old = young;
-
- /* Using ob_refcnt and gc_refs, calculate which objects in the
- * container set are reachable from outside the set (i.e., have a
- * refcount greater than 0 when all the references within the
- * set are taken into account).
- */
- update_refs(young);
- subtract_refs(young);
-
- /* Leave everything reachable from outside young in young, and move
- * everything else (in young) to unreachable.
- * NOTE: This used to move the reachable objects into a reachable
- * set instead. But most things usually turn out to be reachable,
- * so it's more efficient to move the unreachable things.
- */
- gc_list_init(&unreachable);
- move_unreachable(young, &unreachable);
-
- /* Move reachable objects to next generation. */
- if (young != old) {
- if (generation == NUM_GENERATIONS - 2) {
- long_lived_pending += gc_list_size(young);
- }
- gc_list_merge(young, old);
- }
- else {
- long_lived_pending = 0;
- long_lived_total = gc_list_size(young);
- }
-
- /* All objects in unreachable are trash, but objects reachable from
- * finalizers can't safely be deleted. Python programmers should take
- * care not to create such things. For Python, finalizers means
- * instance objects with __del__ methods. Weakrefs with callbacks
- * can also call arbitrary Python code but they will be dealt with by
- * handle_weakrefs().
- */
- gc_list_init(&finalizers);
- move_finalizers(&unreachable, &finalizers);
- /* finalizers contains the unreachable objects with a finalizer;
- * unreachable objects reachable *from* those are also uncollectable,
- * and we move those into the finalizers list too.
- */
- move_finalizer_reachable(&finalizers);
-
- /* Collect statistics on collectable objects found and print
- * debugging information.
- */
- for (gc = unreachable.gc.gc_next; gc != &unreachable;
- gc = gc->gc.gc_next) {
- m++;
- if (debug & DEBUG_COLLECTABLE) {
- debug_cycle("collectable", FROM_GC(gc));
- }
- }
-
- /* Clear weakrefs and invoke callbacks as necessary. */
- m += handle_weakrefs(&unreachable, old);
-
- /* Call tp_clear on objects in the unreachable set. This will cause
- * the reference cycles to be broken. It may also cause some objects
- * in finalizers to be freed.
- */
- delete_garbage(&unreachable, old);
-
- /* Collect statistics on uncollectable objects found and print
- * debugging information. */
- for (gc = finalizers.gc.gc_next;
- gc != &finalizers;
- gc = gc->gc.gc_next) {
- n++;
- if (debug & DEBUG_UNCOLLECTABLE)
- debug_cycle("uncollectable", FROM_GC(gc));
- }
- if (debug & DEBUG_STATS) {
- double t2 = get_time();
- if (m == 0 && n == 0)
- PySys_WriteStderr("gc: done");
- else
- PySys_WriteStderr(
- "gc: done, "
- "%" PY_FORMAT_SIZE_T "d unreachable, "
- "%" PY_FORMAT_SIZE_T "d uncollectable",
- n+m, n);
- if (t1 && t2) {
- PySys_WriteStderr(", %.4fs elapsed", t2-t1);
- }
- PySys_WriteStderr(".\n");
- }
-
- /* Append instances in the uncollectable set to a Python
- * reachable list of garbage. The programmer has to deal with
- * this if they insist on creating this type of structure.
- */
- (void)handle_finalizers(&finalizers, old);
-
- /* Clear free list only during the collection of the highest
- * generation */
- if (generation == NUM_GENERATIONS-1) {
- clear_freelists();
- }
-
- if (PyErr_Occurred()) {
- if (gc_str == NULL)
- gc_str = PyUnicode_FromString("garbage collection");
- PyErr_WriteUnraisable(gc_str);
- Py_FatalError("unexpected exception during garbage collection");
- }
- return n+m;
+ int i;
+ Py_ssize_t m = 0; /* # objects collected */
+ Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
+ PyGC_Head *young; /* the generation we are examining */
+ PyGC_Head *old; /* next older generation */
+ PyGC_Head unreachable; /* non-problematic unreachable trash */
+ PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
+ PyGC_Head *gc;
+ double t1 = 0.0;
+
+ if (delstr == NULL) {
+ delstr = PyUnicode_InternFromString("__del__");
+ if (delstr == NULL)
+ Py_FatalError("gc couldn't allocate \"__del__\"");
+ }
+
+ if (debug & DEBUG_STATS) {
+ PySys_WriteStderr("gc: collecting generation %d...\n",
+ generation);
+ PySys_WriteStderr("gc: objects in each generation:");
+ for (i = 0; i < NUM_GENERATIONS; i++)
+ PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
+ gc_list_size(GEN_HEAD(i)));
+ t1 = get_time();
+ PySys_WriteStderr("\n");
+ }
+
+ /* update collection and allocation counters */
+ if (generation+1 < NUM_GENERATIONS)
+ generations[generation+1].count += 1;
+ for (i = 0; i <= generation; i++)
+ generations[i].count = 0;
+
+ /* merge younger generations with one we are currently collecting */
+ for (i = 0; i < generation; i++) {
+ gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
+ }
+
+ /* handy references */
+ young = GEN_HEAD(generation);
+ if (generation < NUM_GENERATIONS-1)
+ old = GEN_HEAD(generation+1);
+ else
+ old = young;
+
+ /* Using ob_refcnt and gc_refs, calculate which objects in the
+ * container set are reachable from outside the set (i.e., have a
+ * refcount greater than 0 when all the references within the
+ * set are taken into account).
+ */
+ update_refs(young);
+ subtract_refs(young);
+
+ /* Leave everything reachable from outside young in young, and move
+ * everything else (in young) to unreachable.
+ * NOTE: This used to move the reachable objects into a reachable
+ * set instead. But most things usually turn out to be reachable,
+ * so it's more efficient to move the unreachable things.
+ */
+ gc_list_init(&unreachable);
+ move_unreachable(young, &unreachable);
+
+ /* Move reachable objects to next generation. */
+ if (young != old) {
+ if (generation == NUM_GENERATIONS - 2) {
+ long_lived_pending += gc_list_size(young);
+ }
+ gc_list_merge(young, old);
+ }
+ else {
+ long_lived_pending = 0;
+ long_lived_total = gc_list_size(young);
+ }
+
+ /* All objects in unreachable are trash, but objects reachable from
+ * finalizers can't safely be deleted. Python programmers should take
+ * care not to create such things. For Python, finalizers means
+ * instance objects with __del__ methods. Weakrefs with callbacks
+ * can also call arbitrary Python code but they will be dealt with by
+ * handle_weakrefs().
+ */
+ gc_list_init(&finalizers);
+ move_finalizers(&unreachable, &finalizers);
+ /* finalizers contains the unreachable objects with a finalizer;
+ * unreachable objects reachable *from* those are also uncollectable,
+ * and we move those into the finalizers list too.
+ */
+ move_finalizer_reachable(&finalizers);
+
+ /* Collect statistics on collectable objects found and print
+ * debugging information.
+ */
+ for (gc = unreachable.gc.gc_next; gc != &unreachable;
+ gc = gc->gc.gc_next) {
+ m++;
+ if (debug & DEBUG_COLLECTABLE) {
+ debug_cycle("collectable", FROM_GC(gc));
+ }
+ }
+
+ /* Clear weakrefs and invoke callbacks as necessary. */
+ m += handle_weakrefs(&unreachable, old);
+
+ /* Call tp_clear on objects in the unreachable set. This will cause
+ * the reference cycles to be broken. It may also cause some objects
+ * in finalizers to be freed.
+ */
+ delete_garbage(&unreachable, old);
+
+ /* Collect statistics on uncollectable objects found and print
+ * debugging information. */
+ for (gc = finalizers.gc.gc_next;
+ gc != &finalizers;
+ gc = gc->gc.gc_next) {
+ n++;
+ if (debug & DEBUG_UNCOLLECTABLE)
+ debug_cycle("uncollectable", FROM_GC(gc));
+ }
+ if (debug & DEBUG_STATS) {
+ double t2 = get_time();
+ if (m == 0 && n == 0)
+ PySys_WriteStderr("gc: done");
+ else
+ PySys_WriteStderr(
+ "gc: done, "
+ "%" PY_FORMAT_SIZE_T "d unreachable, "
+ "%" PY_FORMAT_SIZE_T "d uncollectable",
+ n+m, n);
+ if (t1 && t2) {
+ PySys_WriteStderr(", %.4fs elapsed", t2-t1);
+ }
+ PySys_WriteStderr(".\n");
+ }
+
+ /* Append instances in the uncollectable set to a Python
+ * reachable list of garbage. The programmer has to deal with
+ * this if they insist on creating this type of structure.
+ */
+ (void)handle_finalizers(&finalizers, old);
+
+ /* Clear free list only during the collection of the highest
+ * generation */
+ if (generation == NUM_GENERATIONS-1) {
+ clear_freelists();
+ }
+
+ if (PyErr_Occurred()) {
+ if (gc_str == NULL)
+ gc_str = PyUnicode_FromString("garbage collection");
+ PyErr_WriteUnraisable(gc_str);
+ Py_FatalError("unexpected exception during garbage collection");
+ }
+ return n+m;
}
static Py_ssize_t
collect_generations(void)
{
- int i;
- Py_ssize_t n = 0;
-
- /* Find the oldest generation (highest numbered) where the count
- * exceeds the threshold. Objects in the that generation and
- * generations younger than it will be collected. */
- for (i = NUM_GENERATIONS-1; i >= 0; i--) {
- if (generations[i].count > generations[i].threshold) {
- /* Avoid quadratic performance degradation in number
- of tracked objects. See comments at the beginning
- of this file, and issue #4074.
- */
- if (i == NUM_GENERATIONS - 1
- && long_lived_pending < long_lived_total / 4)
- continue;
- n = collect(i);
- break;
- }
- }
- return n;
+ int i;
+ Py_ssize_t n = 0;
+
+ /* Find the oldest generation (highest numbered) where the count
+ * exceeds the threshold. Objects in the that generation and
+ * generations younger than it will be collected. */
+ for (i = NUM_GENERATIONS-1; i >= 0; i--) {
+ if (generations[i].count > generations[i].threshold) {
+ /* Avoid quadratic performance degradation in number
+ of tracked objects. See comments at the beginning
+ of this file, and issue #4074.
+ */
+ if (i == NUM_GENERATIONS - 1
+ && long_lived_pending < long_lived_total / 4)
+ continue;
+ n = collect(i);
+ break;
+ }
+ }
+ return n;
}
PyDoc_STRVAR(gc_enable__doc__,
@@ -975,9 +975,9 @@ PyDoc_STRVAR(gc_enable__doc__,
static PyObject *
gc_enable(PyObject *self, PyObject *noargs)
{
- enabled = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ enabled = 1;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_disable__doc__,
@@ -988,9 +988,9 @@ PyDoc_STRVAR(gc_disable__doc__,
static PyObject *
gc_disable(PyObject *self, PyObject *noargs)
{
- enabled = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ enabled = 0;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_isenabled__doc__,
@@ -1001,7 +1001,7 @@ PyDoc_STRVAR(gc_isenabled__doc__,
static PyObject *
gc_isenabled(PyObject *self, PyObject *noargs)
{
- return PyBool_FromLong((long)enabled);
+ return PyBool_FromLong((long)enabled);
}
PyDoc_STRVAR(gc_collect__doc__,
@@ -1015,27 +1015,27 @@ PyDoc_STRVAR(gc_collect__doc__,
static PyObject *
gc_collect(PyObject *self, PyObject *args, PyObject *kws)
{
- static char *keywords[] = {"generation", NULL};
- int genarg = NUM_GENERATIONS - 1;
- Py_ssize_t n;
-
- if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))
- return NULL;
-
- else if (genarg < 0 || genarg >= NUM_GENERATIONS) {
- PyErr_SetString(PyExc_ValueError, "invalid generation");
- return NULL;
- }
-
- if (collecting)
- n = 0; /* already collecting, don't do anything */
- else {
- collecting = 1;
- n = collect(genarg);
- collecting = 0;
- }
-
- return PyLong_FromSsize_t(n);
+ static char *keywords[] = {"generation", NULL};
+ int genarg = NUM_GENERATIONS - 1;
+ Py_ssize_t n;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))
+ return NULL;
+
+ else if (genarg < 0 || genarg >= NUM_GENERATIONS) {
+ PyErr_SetString(PyExc_ValueError, "invalid generation");
+ return NULL;
+ }
+
+ if (collecting)
+ n = 0; /* already collecting, don't do anything */
+ else {
+ collecting = 1;
+ n = collect(genarg);
+ collecting = 0;
+ }
+
+ return PyLong_FromSsize_t(n);
}
PyDoc_STRVAR(gc_set_debug__doc__,
@@ -1055,11 +1055,11 @@ PyDoc_STRVAR(gc_set_debug__doc__,
static PyObject *
gc_set_debug(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_get_debug__doc__,
@@ -1070,7 +1070,7 @@ PyDoc_STRVAR(gc_get_debug__doc__,
static PyObject *
gc_get_debug(PyObject *self, PyObject *noargs)
{
- return Py_BuildValue("i", debug);
+ return Py_BuildValue("i", debug);
}
PyDoc_STRVAR(gc_set_thresh__doc__,
@@ -1082,19 +1082,19 @@ PyDoc_STRVAR(gc_set_thresh__doc__,
static PyObject *
gc_set_thresh(PyObject *self, PyObject *args)
{
- int i;
- if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
- &generations[0].threshold,
- &generations[1].threshold,
- &generations[2].threshold))
- return NULL;
- for (i = 2; i < NUM_GENERATIONS; i++) {
- /* generations higher than 2 get the same threshold */
- generations[i].threshold = generations[2].threshold;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ int i;
+ if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
+ &generations[0].threshold,
+ &generations[1].threshold,
+ &generations[2].threshold))
+ return NULL;
+ for (i = 2; i < NUM_GENERATIONS; i++) {
+ /* generations higher than 2 get the same threshold */
+ generations[i].threshold = generations[2].threshold;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_get_thresh__doc__,
@@ -1105,10 +1105,10 @@ PyDoc_STRVAR(gc_get_thresh__doc__,
static PyObject *
gc_get_thresh(PyObject *self, PyObject *noargs)
{
- return Py_BuildValue("(iii)",
- generations[0].threshold,
- generations[1].threshold,
- generations[2].threshold);
+ return Py_BuildValue("(iii)",
+ generations[0].threshold,
+ generations[1].threshold,
+ generations[2].threshold);
}
PyDoc_STRVAR(gc_get_count__doc__,
@@ -1119,39 +1119,39 @@ PyDoc_STRVAR(gc_get_count__doc__,
static PyObject *
gc_get_count(PyObject *self, PyObject *noargs)
{
- return Py_BuildValue("(iii)",
- generations[0].count,
- generations[1].count,
- generations[2].count);
+ return Py_BuildValue("(iii)",
+ generations[0].count,
+ generations[1].count,
+ generations[2].count);
}
static int
referrersvisit(PyObject* obj, PyObject *objs)
{
- Py_ssize_t i;
- for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
- if (PyTuple_GET_ITEM(objs, i) == obj)
- return 1;
- return 0;
+ Py_ssize_t i;
+ for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
+ if (PyTuple_GET_ITEM(objs, i) == obj)
+ return 1;
+ return 0;
}
static int
gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
{
- PyGC_Head *gc;
- PyObject *obj;
- traverseproc traverse;
- for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
- obj = FROM_GC(gc);
- traverse = Py_TYPE(obj)->tp_traverse;
- if (obj == objs || obj == resultlist)
- continue;
- if (traverse(obj, (visitproc)referrersvisit, objs)) {
- if (PyList_Append(resultlist, obj) < 0)
- return 0; /* error */
- }
- }
- return 1; /* no error */
+ PyGC_Head *gc;
+ PyObject *obj;
+ traverseproc traverse;
+ for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
+ obj = FROM_GC(gc);
+ traverse = Py_TYPE(obj)->tp_traverse;
+ if (obj == objs || obj == resultlist)
+ continue;
+ if (traverse(obj, (visitproc)referrersvisit, objs)) {
+ if (PyList_Append(resultlist, obj) < 0)
+ return 0; /* error */
+ }
+ }
+ return 1; /* no error */
}
PyDoc_STRVAR(gc_get_referrers__doc__,
@@ -1161,24 +1161,24 @@ Return the list of objects that directly refer to any of objs.");
static PyObject *
gc_get_referrers(PyObject *self, PyObject *args)
{
- int i;
- PyObject *result = PyList_New(0);
- if (!result) return NULL;
-
- for (i = 0; i < NUM_GENERATIONS; i++) {
- if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ int i;
+ PyObject *result = PyList_New(0);
+ if (!result) return NULL;
+
+ for (i = 0; i < NUM_GENERATIONS; i++) {
+ if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
/* Append obj to list; return true if error (out of memory), false if OK. */
static int
referentsvisit(PyObject *obj, PyObject *list)
{
- return PyList_Append(list, obj) < 0;
+ return PyList_Append(list, obj) < 0;
}
PyDoc_STRVAR(gc_get_referents__doc__,
@@ -1188,27 +1188,27 @@ Return the list of objects that are directly referred to by objs.");
static PyObject *
gc_get_referents(PyObject *self, PyObject *args)
{
- Py_ssize_t i;
- PyObject *result = PyList_New(0);
-
- if (result == NULL)
- return NULL;
-
- for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
- traverseproc traverse;
- PyObject *obj = PyTuple_GET_ITEM(args, i);
-
- if (! PyObject_IS_GC(obj))
- continue;
- traverse = Py_TYPE(obj)->tp_traverse;
- if (! traverse)
- continue;
- if (traverse(obj, (visitproc)referentsvisit, result)) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ Py_ssize_t i;
+ PyObject *result = PyList_New(0);
+
+ if (result == NULL)
+ return NULL;
+
+ for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
+ traverseproc traverse;
+ PyObject *obj = PyTuple_GET_ITEM(args, i);
+
+ if (! PyObject_IS_GC(obj))
+ continue;
+ traverse = Py_TYPE(obj)->tp_traverse;
+ if (! traverse)
+ continue;
+ if (traverse(obj, (visitproc)referentsvisit, result)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
PyDoc_STRVAR(gc_get_objects__doc__,
@@ -1220,19 +1220,19 @@ PyDoc_STRVAR(gc_get_objects__doc__,
static PyObject *
gc_get_objects(PyObject *self, PyObject *noargs)
{
- int i;
- PyObject* result;
-
- result = PyList_New(0);
- if (result == NULL)
- return NULL;
- for (i = 0; i < NUM_GENERATIONS; i++) {
- if (append_objects(result, GEN_HEAD(i))) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ int i;
+ PyObject* result;
+
+ result = PyList_New(0);
+ if (result == NULL)
+ return NULL;
+ for (i = 0; i < NUM_GENERATIONS; i++) {
+ if (append_objects(result, GEN_HEAD(i))) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
PyDoc_STRVAR(gc_is_tracked__doc__,
@@ -1245,14 +1245,14 @@ PyDoc_STRVAR(gc_is_tracked__doc__,
static PyObject *
gc_is_tracked(PyObject *self, PyObject *obj)
{
- PyObject *result;
-
- if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
- result = Py_True;
- else
- result = Py_False;
- Py_INCREF(result);
- return result;
+ PyObject *result;
+
+ if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
+ result = Py_True;
+ else
+ result = Py_False;
+ Py_INCREF(result);
+ return result;
}
@@ -1274,101 +1274,101 @@ PyDoc_STRVAR(gc__doc__,
"get_referents() -- Return the list of objects that an object refers to.\n");
static PyMethodDef GcMethods[] = {
- {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
- {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
- {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
- {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
- {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
- {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},
- {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
- {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
- {"collect", (PyCFunction)gc_collect,
- METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},
- {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
- {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__},
- {"get_referrers", gc_get_referrers, METH_VARARGS,
- gc_get_referrers__doc__},
- {"get_referents", gc_get_referents, METH_VARARGS,
- gc_get_referents__doc__},
- {NULL, NULL} /* Sentinel */
+ {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
+ {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
+ {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
+ {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
+ {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
+ {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},
+ {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
+ {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
+ {"collect", (PyCFunction)gc_collect,
+ METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},
+ {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
+ {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__},
+ {"get_referrers", gc_get_referrers, METH_VARARGS,
+ gc_get_referrers__doc__},
+ {"get_referents", gc_get_referents, METH_VARARGS,
+ gc_get_referents__doc__},
+ {NULL, NULL} /* Sentinel */
};
static struct PyModuleDef gcmodule = {
- PyModuleDef_HEAD_INIT,
- "gc",
- gc__doc__,
- -1,
- GcMethods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "gc",
+ gc__doc__,
+ -1,
+ GcMethods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_gc(void)
{
- PyObject *m;
-
- m = PyModule_Create(&gcmodule);
-
- if (m == NULL)
- return NULL;
-
- if (garbage == NULL) {
- garbage = PyList_New(0);
- if (garbage == NULL)
- return NULL;
- }
- Py_INCREF(garbage);
- if (PyModule_AddObject(m, "garbage", garbage) < 0)
- return NULL;
-
- /* Importing can't be done in collect() because collect()
- * can be called via PyGC_Collect() in Py_Finalize().
- * This wouldn't be a problem, except that <initialized> is
- * reset to 0 before calling collect which trips up
- * the import and triggers an assertion.
- */
- if (tmod == NULL) {
- tmod = PyImport_ImportModuleNoBlock("time");
- if (tmod == NULL)
- PyErr_Clear();
- }
+ PyObject *m;
+
+ m = PyModule_Create(&gcmodule);
+
+ if (m == NULL)
+ return NULL;
+
+ if (garbage == NULL) {
+ garbage = PyList_New(0);
+ if (garbage == NULL)
+ return NULL;
+ }
+ Py_INCREF(garbage);
+ if (PyModule_AddObject(m, "garbage", garbage) < 0)
+ return NULL;
+
+ /* Importing can't be done in collect() because collect()
+ * can be called via PyGC_Collect() in Py_Finalize().
+ * This wouldn't be a problem, except that <initialized> is
+ * reset to 0 before calling collect which trips up
+ * the import and triggers an assertion.
+ */
+ if (tmod == NULL) {
+ tmod = PyImport_ImportModuleNoBlock("time");
+ if (tmod == NULL)
+ PyErr_Clear();
+ }
#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL
- ADD_INT(DEBUG_STATS);
- ADD_INT(DEBUG_COLLECTABLE);
- ADD_INT(DEBUG_UNCOLLECTABLE);
- ADD_INT(DEBUG_SAVEALL);
- ADD_INT(DEBUG_LEAK);
+ ADD_INT(DEBUG_STATS);
+ ADD_INT(DEBUG_COLLECTABLE);
+ ADD_INT(DEBUG_UNCOLLECTABLE);
+ ADD_INT(DEBUG_SAVEALL);
+ ADD_INT(DEBUG_LEAK);
#undef ADD_INT
- return m;
+ return m;
}
/* API to invoke gc.collect() from C */
Py_ssize_t
PyGC_Collect(void)
{
- Py_ssize_t n;
+ Py_ssize_t n;
- if (collecting)
- n = 0; /* already collecting, don't do anything */
- else {
- collecting = 1;
- n = collect(NUM_GENERATIONS - 1);
- collecting = 0;
- }
+ if (collecting)
+ n = 0; /* already collecting, don't do anything */
+ else {
+ collecting = 1;
+ n = collect(NUM_GENERATIONS - 1);
+ collecting = 0;
+ }
- return n;
+ return n;
}
/* for debugging */
void
_PyGC_Dump(PyGC_Head *g)
{
- _PyObject_Dump(FROM_GC(g));
+ _PyObject_Dump(FROM_GC(g));
}
/* extension modules might be compiled with GC support so these
@@ -1382,7 +1382,7 @@ _PyGC_Dump(PyGC_Head *g)
void
PyObject_GC_Track(void *op)
{
- _PyObject_GC_TRACK(op);
+ _PyObject_GC_TRACK(op);
}
/* for binary compatibility with 2.2 */
@@ -1395,11 +1395,11 @@ _PyObject_GC_Track(PyObject *op)
void
PyObject_GC_UnTrack(void *op)
{
- /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
- * call PyObject_GC_UnTrack twice on an object.
- */
- if (IS_TRACKED(op))
- _PyObject_GC_UNTRACK(op);
+ /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
+ * call PyObject_GC_UnTrack twice on an object.
+ */
+ if (IS_TRACKED(op))
+ _PyObject_GC_UNTRACK(op);
}
/* for binary compatibility with 2.2 */
@@ -1412,73 +1412,73 @@ _PyObject_GC_UnTrack(PyObject *op)
PyObject *
_PyObject_GC_Malloc(size_t basicsize)
{
- PyObject *op;
- PyGC_Head *g;
- if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
- return PyErr_NoMemory();
- g = (PyGC_Head *)PyObject_MALLOC(
- sizeof(PyGC_Head) + basicsize);
- if (g == NULL)
- return PyErr_NoMemory();
- g->gc.gc_refs = GC_UNTRACKED;
- generations[0].count++; /* number of allocated GC objects */
- if (generations[0].count > generations[0].threshold &&
- enabled &&
- generations[0].threshold &&
- !collecting &&
- !PyErr_Occurred()) {
- collecting = 1;
- collect_generations();
- collecting = 0;
- }
- op = FROM_GC(g);
- return op;
+ PyObject *op;
+ PyGC_Head *g;
+ if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
+ return PyErr_NoMemory();
+ g = (PyGC_Head *)PyObject_MALLOC(
+ sizeof(PyGC_Head) + basicsize);
+ if (g == NULL)
+ return PyErr_NoMemory();
+ g->gc.gc_refs = GC_UNTRACKED;
+ generations[0].count++; /* number of allocated GC objects */
+ if (generations[0].count > generations[0].threshold &&
+ enabled &&
+ generations[0].threshold &&
+ !collecting &&
+ !PyErr_Occurred()) {
+ collecting = 1;
+ collect_generations();
+ collecting = 0;
+ }
+ op = FROM_GC(g);
+ return op;
}
PyObject *
_PyObject_GC_New(PyTypeObject *tp)
{
- PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
- if (op != NULL)
- op = PyObject_INIT(op, tp);
- return op;
+ PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
+ if (op != NULL)
+ op = PyObject_INIT(op, tp);
+ return op;
}
PyVarObject *
_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
{
- const size_t size = _PyObject_VAR_SIZE(tp, nitems);
- PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
- if (op != NULL)
- op = PyObject_INIT_VAR(op, tp, nitems);
- return op;
+ const size_t size = _PyObject_VAR_SIZE(tp, nitems);
+ PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
+ if (op != NULL)
+ op = PyObject_INIT_VAR(op, tp, nitems);
+ return op;
}
PyVarObject *
_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
{
- const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
- PyGC_Head *g = AS_GC(op);
- if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
- return (PyVarObject *)PyErr_NoMemory();
- g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
- if (g == NULL)
- return (PyVarObject *)PyErr_NoMemory();
- op = (PyVarObject *) FROM_GC(g);
- Py_SIZE(op) = nitems;
- return op;
+ const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
+ PyGC_Head *g = AS_GC(op);
+ if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
+ return (PyVarObject *)PyErr_NoMemory();
+ g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
+ if (g == NULL)
+ return (PyVarObject *)PyErr_NoMemory();
+ op = (PyVarObject *) FROM_GC(g);
+ Py_SIZE(op) = nitems;
+ return op;
}
void
PyObject_GC_Del(void *op)
{
- PyGC_Head *g = AS_GC(op);
- if (IS_TRACKED(op))
- gc_list_remove(g);
- if (generations[0].count > 0) {
- generations[0].count--;
- }
- PyObject_FREE(g);
+ PyGC_Head *g = AS_GC(op);
+ if (IS_TRACKED(op))
+ gc_list_remove(g);
+ if (generations[0].count > 0) {
+ generations[0].count--;
+ }
+ PyObject_FREE(g);
}
/* for binary compatibility with 2.2 */
diff --git a/Modules/getaddrinfo.c b/Modules/getaddrinfo.c
index 5bcec2b..a3ca30a 100644
--- a/Modules/getaddrinfo.c
+++ b/Modules/getaddrinfo.c
@@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
@@ -13,7 +13,7 @@
* 3. Neither the name of the project 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 PROJECT AND CONTRIBUTORS ``AS IS'' AND
* GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@@ -73,52 +73,52 @@ static struct in6_addr faith_prefix = IN6ADDR_GAI_ANY_INIT;
static const char in_addrany[] = { 0, 0, 0, 0 };
static const char in6_addrany[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
-static const char in_loopback[] = { 127, 0, 0, 1 };
+static const char in_loopback[] = { 127, 0, 0, 1 };
static const char in6_loopback[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
};
struct sockinet {
- u_char si_len;
- u_char si_family;
- u_short si_port;
+ u_char si_len;
+ u_char si_family;
+ u_short si_port;
};
static struct gai_afd {
- int a_af;
- int a_addrlen;
- int a_socklen;
- int a_off;
- const char *a_addrany;
- const char *a_loopback;
+ int a_af;
+ int a_addrlen;
+ int a_socklen;
+ int a_off;
+ const char *a_addrany;
+ const char *a_loopback;
} gai_afdl [] = {
#ifdef ENABLE_IPV6
#define N_INET6 0
- {PF_INET6, sizeof(struct in6_addr),
- sizeof(struct sockaddr_in6),
- offsetof(struct sockaddr_in6, sin6_addr),
- in6_addrany, in6_loopback},
+ {PF_INET6, sizeof(struct in6_addr),
+ sizeof(struct sockaddr_in6),
+ offsetof(struct sockaddr_in6, sin6_addr),
+ in6_addrany, in6_loopback},
#define N_INET 1
#else
#define N_INET 0
#endif
- {PF_INET, sizeof(struct in_addr),
- sizeof(struct sockaddr_in),
- offsetof(struct sockaddr_in, sin_addr),
- in_addrany, in_loopback},
- {0, 0, 0, 0, NULL, NULL},
+ {PF_INET, sizeof(struct in_addr),
+ sizeof(struct sockaddr_in),
+ offsetof(struct sockaddr_in, sin_addr),
+ in_addrany, in_loopback},
+ {0, 0, 0, 0, NULL, NULL},
};
#ifdef ENABLE_IPV6
-#define PTON_MAX 16
+#define PTON_MAX 16
#else
-#define PTON_MAX 4
+#define PTON_MAX 4
#endif
#ifndef IN_MULTICAST
-#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U)
+#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U)
#endif
#ifndef IN_EXPERIMENTAL
@@ -126,73 +126,73 @@ static struct gai_afd {
#endif
#ifndef IN_LOOPBACKNET
-#define IN_LOOPBACKNET 127
+#define IN_LOOPBACKNET 127
#endif
static int get_name(const char *, struct gai_afd *,
- struct addrinfo **, char *, struct addrinfo *,
- int);
+ struct addrinfo **, char *, struct addrinfo *,
+ int);
static int get_addr(const char *, int, struct addrinfo **,
- struct addrinfo *, int);
+ struct addrinfo *, int);
static int str_isnumber(const char *);
-
+
static char *ai_errlist[] = {
- "success.",
- "address family for hostname not supported.", /* EAI_ADDRFAMILY */
- "temporary failure in name resolution.", /* EAI_AGAIN */
- "invalid value for ai_flags.", /* EAI_BADFLAGS */
- "non-recoverable failure in name resolution.", /* EAI_FAIL */
- "ai_family not supported.", /* EAI_FAMILY */
- "memory allocation failure.", /* EAI_MEMORY */
- "no address associated with hostname.", /* EAI_NODATA */
- "hostname nor servname provided, or not known.",/* EAI_NONAME */
- "servname not supported for ai_socktype.", /* EAI_SERVICE */
- "ai_socktype not supported.", /* EAI_SOCKTYPE */
- "system error returned in errno.", /* EAI_SYSTEM */
- "invalid value for hints.", /* EAI_BADHINTS */
- "resolved protocol is unknown.", /* EAI_PROTOCOL */
- "unknown error.", /* EAI_MAX */
+ "success.",
+ "address family for hostname not supported.", /* EAI_ADDRFAMILY */
+ "temporary failure in name resolution.", /* EAI_AGAIN */
+ "invalid value for ai_flags.", /* EAI_BADFLAGS */
+ "non-recoverable failure in name resolution.", /* EAI_FAIL */
+ "ai_family not supported.", /* EAI_FAMILY */
+ "memory allocation failure.", /* EAI_MEMORY */
+ "no address associated with hostname.", /* EAI_NODATA */
+ "hostname nor servname provided, or not known.",/* EAI_NONAME */
+ "servname not supported for ai_socktype.", /* EAI_SERVICE */
+ "ai_socktype not supported.", /* EAI_SOCKTYPE */
+ "system error returned in errno.", /* EAI_SYSTEM */
+ "invalid value for hints.", /* EAI_BADHINTS */
+ "resolved protocol is unknown.", /* EAI_PROTOCOL */
+ "unknown error.", /* EAI_MAX */
};
#define GET_CANONNAME(ai, str) \
if (pai->ai_flags & AI_CANONNAME) {\
- if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\
- strcpy((ai)->ai_canonname, (str));\
- } else {\
- error = EAI_MEMORY;\
- goto free;\
- }\
+ if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\
+ strcpy((ai)->ai_canonname, (str));\
+ } else {\
+ error = EAI_MEMORY;\
+ goto free;\
+ }\
}
#ifdef HAVE_SOCKADDR_SA_LEN
#define GET_AI(ai, gai_afd, addr, port) {\
- char *p;\
- if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
- ((gai_afd)->a_socklen)))\
- == NULL) goto free;\
- memcpy(ai, pai, sizeof(struct addrinfo));\
- (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
- memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
- (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\
- (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
- ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
- p = (char *)((ai)->ai_addr);\
- memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
+ char *p;\
+ if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
+ ((gai_afd)->a_socklen)))\
+ == NULL) goto free;\
+ memcpy(ai, pai, sizeof(struct addrinfo));\
+ (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
+ memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
+ (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\
+ (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
+ ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
+ p = (char *)((ai)->ai_addr);\
+ memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
}
#else
#define GET_AI(ai, gai_afd, addr, port) {\
- char *p;\
- if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
- ((gai_afd)->a_socklen)))\
- == NULL) goto free;\
- memcpy(ai, pai, sizeof(struct addrinfo));\
- (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
- memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
- (ai)->ai_addrlen = (gai_afd)->a_socklen;\
- (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
- ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
- p = (char *)((ai)->ai_addr);\
- memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
+ char *p;\
+ if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
+ ((gai_afd)->a_socklen)))\
+ == NULL) goto free;\
+ memcpy(ai, pai, sizeof(struct addrinfo));\
+ (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
+ memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
+ (ai)->ai_addrlen = (gai_afd)->a_socklen;\
+ (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
+ ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
+ p = (char *)((ai)->ai_addr);\
+ memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
}
#endif
@@ -201,438 +201,438 @@ if (pai->ai_flags & AI_CANONNAME) {\
char *
gai_strerror(int ecode)
{
- if (ecode < 0 || ecode > EAI_MAX)
- ecode = EAI_MAX;
- return ai_errlist[ecode];
+ if (ecode < 0 || ecode > EAI_MAX)
+ ecode = EAI_MAX;
+ return ai_errlist[ecode];
}
void
freeaddrinfo(struct addrinfo *ai)
{
- struct addrinfo *next;
-
- do {
- next = ai->ai_next;
- if (ai->ai_canonname)
- free(ai->ai_canonname);
- /* no need to free(ai->ai_addr) */
- free(ai);
- } while ((ai = next) != NULL);
+ struct addrinfo *next;
+
+ do {
+ next = ai->ai_next;
+ if (ai->ai_canonname)
+ free(ai->ai_canonname);
+ /* no need to free(ai->ai_addr) */
+ free(ai);
+ } while ((ai = next) != NULL);
}
static int
str_isnumber(const char *p)
{
- unsigned char *q = (unsigned char *)p;
- while (*q) {
- if (! isdigit(*q))
- return NO;
- q++;
- }
- return YES;
+ unsigned char *q = (unsigned char *)p;
+ while (*q) {
+ if (! isdigit(*q))
+ return NO;
+ q++;
+ }
+ return YES;
}
int
getaddrinfo(const char*hostname, const char*servname,
const struct addrinfo *hints, struct addrinfo **res)
{
- struct addrinfo sentinel;
- struct addrinfo *top = NULL;
- struct addrinfo *cur;
- int i, error = 0;
- char pton[PTON_MAX];
- struct addrinfo ai;
- struct addrinfo *pai;
- u_short port;
+ struct addrinfo sentinel;
+ struct addrinfo *top = NULL;
+ struct addrinfo *cur;
+ int i, error = 0;
+ char pton[PTON_MAX];
+ struct addrinfo ai;
+ struct addrinfo *pai;
+ u_short port;
#ifdef FAITH
- static int firsttime = 1;
-
- if (firsttime) {
- /* translator hack */
- {
- char *q = getenv("GAI");
- if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1)
- translate = YES;
- }
- firsttime = 0;
- }
+ static int firsttime = 1;
+
+ if (firsttime) {
+ /* translator hack */
+ {
+ char *q = getenv("GAI");
+ if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1)
+ translate = YES;
+ }
+ firsttime = 0;
+ }
#endif
- /* initialize file static vars */
- sentinel.ai_next = NULL;
- cur = &sentinel;
- pai = &ai;
- pai->ai_flags = 0;
- pai->ai_family = PF_UNSPEC;
- pai->ai_socktype = GAI_ANY;
- pai->ai_protocol = GAI_ANY;
- pai->ai_addrlen = 0;
- pai->ai_canonname = NULL;
- pai->ai_addr = NULL;
- pai->ai_next = NULL;
- port = GAI_ANY;
-
- if (hostname == NULL && servname == NULL)
- return EAI_NONAME;
- if (hints) {
- /* error check for hints */
- if (hints->ai_addrlen || hints->ai_canonname ||
- hints->ai_addr || hints->ai_next)
- ERR(EAI_BADHINTS); /* xxx */
- if (hints->ai_flags & ~AI_MASK)
- ERR(EAI_BADFLAGS);
- switch (hints->ai_family) {
- case PF_UNSPEC:
- case PF_INET:
+ /* initialize file static vars */
+ sentinel.ai_next = NULL;
+ cur = &sentinel;
+ pai = &ai;
+ pai->ai_flags = 0;
+ pai->ai_family = PF_UNSPEC;
+ pai->ai_socktype = GAI_ANY;
+ pai->ai_protocol = GAI_ANY;
+ pai->ai_addrlen = 0;
+ pai->ai_canonname = NULL;
+ pai->ai_addr = NULL;
+ pai->ai_next = NULL;
+ port = GAI_ANY;
+
+ if (hostname == NULL && servname == NULL)
+ return EAI_NONAME;
+ if (hints) {
+ /* error check for hints */
+ if (hints->ai_addrlen || hints->ai_canonname ||
+ hints->ai_addr || hints->ai_next)
+ ERR(EAI_BADHINTS); /* xxx */
+ if (hints->ai_flags & ~AI_MASK)
+ ERR(EAI_BADFLAGS);
+ switch (hints->ai_family) {
+ case PF_UNSPEC:
+ case PF_INET:
#ifdef ENABLE_IPV6
- case PF_INET6:
+ case PF_INET6:
#endif
- break;
- default:
- ERR(EAI_FAMILY);
- }
- memcpy(pai, hints, sizeof(*pai));
- switch (pai->ai_socktype) {
- case GAI_ANY:
- switch (pai->ai_protocol) {
- case GAI_ANY:
- break;
- case IPPROTO_UDP:
- pai->ai_socktype = SOCK_DGRAM;
- break;
- case IPPROTO_TCP:
- pai->ai_socktype = SOCK_STREAM;
- break;
- default:
- pai->ai_socktype = SOCK_RAW;
- break;
- }
- break;
- case SOCK_RAW:
- break;
- case SOCK_DGRAM:
- if (pai->ai_protocol != IPPROTO_UDP &&
- pai->ai_protocol != GAI_ANY)
- ERR(EAI_BADHINTS); /*xxx*/
- pai->ai_protocol = IPPROTO_UDP;
- break;
- case SOCK_STREAM:
- if (pai->ai_protocol != IPPROTO_TCP &&
- pai->ai_protocol != GAI_ANY)
- ERR(EAI_BADHINTS); /*xxx*/
- pai->ai_protocol = IPPROTO_TCP;
- break;
- default:
- ERR(EAI_SOCKTYPE);
- /* unreachable */
- }
- }
-
- /*
- * service port
- */
- if (servname) {
- if (str_isnumber(servname)) {
- if (pai->ai_socktype == GAI_ANY) {
- /* caller accept *GAI_ANY* socktype */
- pai->ai_socktype = SOCK_DGRAM;
- pai->ai_protocol = IPPROTO_UDP;
- }
- port = htons((u_short)atoi(servname));
- } else {
- struct servent *sp;
- char *proto;
-
- proto = NULL;
- switch (pai->ai_socktype) {
- case GAI_ANY:
- proto = NULL;
- break;
- case SOCK_DGRAM:
- proto = "udp";
- break;
- case SOCK_STREAM:
- proto = "tcp";
- break;
- default:
- fprintf(stderr, "panic!\n");
- break;
- }
- if ((sp = getservbyname(servname, proto)) == NULL)
- ERR(EAI_SERVICE);
- port = sp->s_port;
- if (pai->ai_socktype == GAI_ANY) {
- if (strcmp(sp->s_proto, "udp") == 0) {
- pai->ai_socktype = SOCK_DGRAM;
- pai->ai_protocol = IPPROTO_UDP;
- } else if (strcmp(sp->s_proto, "tcp") == 0) {
- pai->ai_socktype = SOCK_STREAM;
- pai->ai_protocol = IPPROTO_TCP;
- } else
- ERR(EAI_PROTOCOL); /*xxx*/
- }
- }
- }
-
- /*
- * hostname == NULL.
- * passive socket -> anyaddr (0.0.0.0 or ::)
- * non-passive socket -> localhost (127.0.0.1 or ::1)
- */
- if (hostname == NULL) {
- struct gai_afd *gai_afd;
-
- for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) {
- if (!(pai->ai_family == PF_UNSPEC
- || pai->ai_family == gai_afd->a_af)) {
- continue;
- }
-
- if (pai->ai_flags & AI_PASSIVE) {
- GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port);
- /* xxx meaningless?
- * GET_CANONNAME(cur->ai_next, "anyaddr");
- */
- } else {
- GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback,
- port);
- /* xxx meaningless?
- * GET_CANONNAME(cur->ai_next, "localhost");
- */
- }
- cur = cur->ai_next;
- }
- top = sentinel.ai_next;
- if (top)
- goto good;
- else
- ERR(EAI_FAMILY);
- }
-
- /* hostname as numeric name */
- for (i = 0; gai_afdl[i].a_af; i++) {
- if (inet_pton(gai_afdl[i].a_af, hostname, pton)) {
- u_long v4a;
+ break;
+ default:
+ ERR(EAI_FAMILY);
+ }
+ memcpy(pai, hints, sizeof(*pai));
+ switch (pai->ai_socktype) {
+ case GAI_ANY:
+ switch (pai->ai_protocol) {
+ case GAI_ANY:
+ break;
+ case IPPROTO_UDP:
+ pai->ai_socktype = SOCK_DGRAM;
+ break;
+ case IPPROTO_TCP:
+ pai->ai_socktype = SOCK_STREAM;
+ break;
+ default:
+ pai->ai_socktype = SOCK_RAW;
+ break;
+ }
+ break;
+ case SOCK_RAW:
+ break;
+ case SOCK_DGRAM:
+ if (pai->ai_protocol != IPPROTO_UDP &&
+ pai->ai_protocol != GAI_ANY)
+ ERR(EAI_BADHINTS); /*xxx*/
+ pai->ai_protocol = IPPROTO_UDP;
+ break;
+ case SOCK_STREAM:
+ if (pai->ai_protocol != IPPROTO_TCP &&
+ pai->ai_protocol != GAI_ANY)
+ ERR(EAI_BADHINTS); /*xxx*/
+ pai->ai_protocol = IPPROTO_TCP;
+ break;
+ default:
+ ERR(EAI_SOCKTYPE);
+ /* unreachable */
+ }
+ }
+
+ /*
+ * service port
+ */
+ if (servname) {
+ if (str_isnumber(servname)) {
+ if (pai->ai_socktype == GAI_ANY) {
+ /* caller accept *GAI_ANY* socktype */
+ pai->ai_socktype = SOCK_DGRAM;
+ pai->ai_protocol = IPPROTO_UDP;
+ }
+ port = htons((u_short)atoi(servname));
+ } else {
+ struct servent *sp;
+ char *proto;
+
+ proto = NULL;
+ switch (pai->ai_socktype) {
+ case GAI_ANY:
+ proto = NULL;
+ break;
+ case SOCK_DGRAM:
+ proto = "udp";
+ break;
+ case SOCK_STREAM:
+ proto = "tcp";
+ break;
+ default:
+ fprintf(stderr, "panic!\n");
+ break;
+ }
+ if ((sp = getservbyname(servname, proto)) == NULL)
+ ERR(EAI_SERVICE);
+ port = sp->s_port;
+ if (pai->ai_socktype == GAI_ANY) {
+ if (strcmp(sp->s_proto, "udp") == 0) {
+ pai->ai_socktype = SOCK_DGRAM;
+ pai->ai_protocol = IPPROTO_UDP;
+ } else if (strcmp(sp->s_proto, "tcp") == 0) {
+ pai->ai_socktype = SOCK_STREAM;
+ pai->ai_protocol = IPPROTO_TCP;
+ } else
+ ERR(EAI_PROTOCOL); /*xxx*/
+ }
+ }
+ }
+
+ /*
+ * hostname == NULL.
+ * passive socket -> anyaddr (0.0.0.0 or ::)
+ * non-passive socket -> localhost (127.0.0.1 or ::1)
+ */
+ if (hostname == NULL) {
+ struct gai_afd *gai_afd;
+
+ for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) {
+ if (!(pai->ai_family == PF_UNSPEC
+ || pai->ai_family == gai_afd->a_af)) {
+ continue;
+ }
+
+ if (pai->ai_flags & AI_PASSIVE) {
+ GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port);
+ /* xxx meaningless?
+ * GET_CANONNAME(cur->ai_next, "anyaddr");
+ */
+ } else {
+ GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback,
+ port);
+ /* xxx meaningless?
+ * GET_CANONNAME(cur->ai_next, "localhost");
+ */
+ }
+ cur = cur->ai_next;
+ }
+ top = sentinel.ai_next;
+ if (top)
+ goto good;
+ else
+ ERR(EAI_FAMILY);
+ }
+
+ /* hostname as numeric name */
+ for (i = 0; gai_afdl[i].a_af; i++) {
+ if (inet_pton(gai_afdl[i].a_af, hostname, pton)) {
+ u_long v4a;
#ifdef ENABLE_IPV6
- u_char pfx;
+ u_char pfx;
#endif
- switch (gai_afdl[i].a_af) {
- case AF_INET:
- v4a = ((struct in_addr *)pton)->s_addr;
- v4a = ntohl(v4a);
- if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
- pai->ai_flags &= ~AI_CANONNAME;
- v4a >>= IN_CLASSA_NSHIFT;
- if (v4a == 0 || v4a == IN_LOOPBACKNET)
- pai->ai_flags &= ~AI_CANONNAME;
- break;
+ switch (gai_afdl[i].a_af) {
+ case AF_INET:
+ v4a = ((struct in_addr *)pton)->s_addr;
+ v4a = ntohl(v4a);
+ if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
+ pai->ai_flags &= ~AI_CANONNAME;
+ v4a >>= IN_CLASSA_NSHIFT;
+ if (v4a == 0 || v4a == IN_LOOPBACKNET)
+ pai->ai_flags &= ~AI_CANONNAME;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- pfx = ((struct in6_addr *)pton)->s6_addr8[0];
- if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
- pai->ai_flags &= ~AI_CANONNAME;
- break;
+ case AF_INET6:
+ pfx = ((struct in6_addr *)pton)->s6_addr8[0];
+ if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
+ pai->ai_flags &= ~AI_CANONNAME;
+ break;
#endif
- }
-
- if (pai->ai_family == gai_afdl[i].a_af ||
- pai->ai_family == PF_UNSPEC) {
- if (! (pai->ai_flags & AI_CANONNAME)) {
- GET_AI(top, &gai_afdl[i], pton, port);
- goto good;
- }
- /*
- * if AI_CANONNAME and if reverse lookup
- * fail, return ai anyway to pacify
- * calling application.
- *
- * XXX getaddrinfo() is a name->address
- * translation function, and it looks strange
- * that we do addr->name translation here.
- */
- get_name(pton, &gai_afdl[i], &top, pton, pai, port);
- goto good;
- } else
- ERR(EAI_FAMILY); /*xxx*/
- }
- }
-
- if (pai->ai_flags & AI_NUMERICHOST)
- ERR(EAI_NONAME);
-
- /* hostname as alphabetical name */
- error = get_addr(hostname, pai->ai_family, &top, pai, port);
- if (error == 0) {
- if (top) {
+ }
+
+ if (pai->ai_family == gai_afdl[i].a_af ||
+ pai->ai_family == PF_UNSPEC) {
+ if (! (pai->ai_flags & AI_CANONNAME)) {
+ GET_AI(top, &gai_afdl[i], pton, port);
+ goto good;
+ }
+ /*
+ * if AI_CANONNAME and if reverse lookup
+ * fail, return ai anyway to pacify
+ * calling application.
+ *
+ * XXX getaddrinfo() is a name->address
+ * translation function, and it looks strange
+ * that we do addr->name translation here.
+ */
+ get_name(pton, &gai_afdl[i], &top, pton, pai, port);
+ goto good;
+ } else
+ ERR(EAI_FAMILY); /*xxx*/
+ }
+ }
+
+ if (pai->ai_flags & AI_NUMERICHOST)
+ ERR(EAI_NONAME);
+
+ /* hostname as alphabetical name */
+ error = get_addr(hostname, pai->ai_family, &top, pai, port);
+ if (error == 0) {
+ if (top) {
good:
- *res = top;
- return SUCCESS;
- } else
- error = EAI_FAIL;
- }
+ *res = top;
+ return SUCCESS;
+ } else
+ error = EAI_FAIL;
+ }
free:
- if (top)
- freeaddrinfo(top);
+ if (top)
+ freeaddrinfo(top);
bad:
- *res = NULL;
- return error;
+ *res = NULL;
+ return error;
}
static int
get_name(addr, gai_afd, res, numaddr, pai, port0)
- const char *addr;
- struct gai_afd *gai_afd;
- struct addrinfo **res;
- char *numaddr;
- struct addrinfo *pai;
- int port0;
+ const char *addr;
+ struct gai_afd *gai_afd;
+ struct addrinfo **res;
+ char *numaddr;
+ struct addrinfo *pai;
+ int port0;
{
- u_short port = port0 & 0xffff;
- struct hostent *hp;
- struct addrinfo *cur;
- int error = 0;
+ u_short port = port0 & 0xffff;
+ struct hostent *hp;
+ struct addrinfo *cur;
+ int error = 0;
#ifdef ENABLE_IPV6
- int h_error;
+ int h_error;
#endif
-
+
#ifdef ENABLE_IPV6
- hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error);
+ hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error);
#else
- hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET);
+ hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET);
#endif
- if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
- GET_AI(cur, gai_afd, hp->h_addr_list[0], port);
- GET_CANONNAME(cur, hp->h_name);
- } else
- GET_AI(cur, gai_afd, numaddr, port);
-
+ if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
+ GET_AI(cur, gai_afd, hp->h_addr_list[0], port);
+ GET_CANONNAME(cur, hp->h_name);
+ } else
+ GET_AI(cur, gai_afd, numaddr, port);
+
#ifdef ENABLE_IPV6
- if (hp)
- freehostent(hp);
+ if (hp)
+ freehostent(hp);
#endif
- *res = cur;
- return SUCCESS;
+ *res = cur;
+ return SUCCESS;
free:
- if (cur)
- freeaddrinfo(cur);
+ if (cur)
+ freeaddrinfo(cur);
#ifdef ENABLE_IPV6
- if (hp)
- freehostent(hp);
+ if (hp)
+ freehostent(hp);
#endif
/* bad: */
- *res = NULL;
- return error;
+ *res = NULL;
+ return error;
}
static int
get_addr(hostname, af, res, pai, port0)
- const char *hostname;
- int af;
- struct addrinfo **res;
- struct addrinfo *pai;
- int port0;
+ const char *hostname;
+ int af;
+ struct addrinfo **res;
+ struct addrinfo *pai;
+ int port0;
{
- u_short port = port0 & 0xffff;
- struct addrinfo sentinel;
- struct hostent *hp;
- struct addrinfo *top, *cur;
- struct gai_afd *gai_afd;
- int i, error = 0, h_error;
- char *ap;
-
- top = NULL;
- sentinel.ai_next = NULL;
- cur = &sentinel;
+ u_short port = port0 & 0xffff;
+ struct addrinfo sentinel;
+ struct hostent *hp;
+ struct addrinfo *top, *cur;
+ struct gai_afd *gai_afd;
+ int i, error = 0, h_error;
+ char *ap;
+
+ top = NULL;
+ sentinel.ai_next = NULL;
+ cur = &sentinel;
#ifdef ENABLE_IPV6
- if (af == AF_UNSPEC) {
- hp = getipnodebyname(hostname, AF_INET6,
- AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error);
- } else
- hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error);
+ if (af == AF_UNSPEC) {
+ hp = getipnodebyname(hostname, AF_INET6,
+ AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error);
+ } else
+ hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error);
#else
- hp = gethostbyname(hostname);
- h_error = h_errno;
+ hp = gethostbyname(hostname);
+ h_error = h_errno;
#endif
- if (hp == NULL) {
- switch (h_error) {
- case HOST_NOT_FOUND:
- case NO_DATA:
- error = EAI_NODATA;
- break;
- case TRY_AGAIN:
- error = EAI_AGAIN;
- break;
- case NO_RECOVERY:
- default:
- error = EAI_FAIL;
- break;
- }
- goto free;
- }
-
- if ((hp->h_name == NULL) || (hp->h_name[0] == 0) ||
- (hp->h_addr_list[0] == NULL)) {
- error = EAI_FAIL;
- goto free;
- }
-
- for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) {
- switch (af) {
+ if (hp == NULL) {
+ switch (h_error) {
+ case HOST_NOT_FOUND:
+ case NO_DATA:
+ error = EAI_NODATA;
+ break;
+ case TRY_AGAIN:
+ error = EAI_AGAIN;
+ break;
+ case NO_RECOVERY:
+ default:
+ error = EAI_FAIL;
+ break;
+ }
+ goto free;
+ }
+
+ if ((hp->h_name == NULL) || (hp->h_name[0] == 0) ||
+ (hp->h_addr_list[0] == NULL)) {
+ error = EAI_FAIL;
+ goto free;
+ }
+
+ for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) {
+ switch (af) {
#ifdef ENABLE_IPV6
- case AF_INET6:
- gai_afd = &gai_afdl[N_INET6];
- break;
+ case AF_INET6:
+ gai_afd = &gai_afdl[N_INET6];
+ break;
#endif
#ifndef ENABLE_IPV6
- default: /* AF_UNSPEC */
+ default: /* AF_UNSPEC */
#endif
- case AF_INET:
- gai_afd = &gai_afdl[N_INET];
- break;
+ case AF_INET:
+ gai_afd = &gai_afdl[N_INET];
+ break;
#ifdef ENABLE_IPV6
- default: /* AF_UNSPEC */
- if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
- ap += sizeof(struct in6_addr) -
- sizeof(struct in_addr);
- gai_afd = &gai_afdl[N_INET];
- } else
- gai_afd = &gai_afdl[N_INET6];
- break;
+ default: /* AF_UNSPEC */
+ if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
+ ap += sizeof(struct in6_addr) -
+ sizeof(struct in_addr);
+ gai_afd = &gai_afdl[N_INET];
+ } else
+ gai_afd = &gai_afdl[N_INET6];
+ break;
#endif
- }
+ }
#ifdef FAITH
- if (translate && gai_afd->a_af == AF_INET) {
- struct in6_addr *in6;
-
- GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port);
- in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr;
- memcpy(&in6->s6_addr32[0], &faith_prefix,
- sizeof(struct in6_addr) - sizeof(struct in_addr));
- memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr));
- } else
+ if (translate && gai_afd->a_af == AF_INET) {
+ struct in6_addr *in6;
+
+ GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port);
+ in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr;
+ memcpy(&in6->s6_addr32[0], &faith_prefix,
+ sizeof(struct in6_addr) - sizeof(struct in_addr));
+ memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr));
+ } else
#endif /* FAITH */
- GET_AI(cur->ai_next, gai_afd, ap, port);
- if (cur == &sentinel) {
- top = cur->ai_next;
- GET_CANONNAME(top, hp->h_name);
- }
- cur = cur->ai_next;
- }
+ GET_AI(cur->ai_next, gai_afd, ap, port);
+ if (cur == &sentinel) {
+ top = cur->ai_next;
+ GET_CANONNAME(top, hp->h_name);
+ }
+ cur = cur->ai_next;
+ }
#ifdef ENABLE_IPV6
- freehostent(hp);
+ freehostent(hp);
#endif
- *res = top;
- return SUCCESS;
+ *res = top;
+ return SUCCESS;
free:
- if (top)
- freeaddrinfo(top);
+ if (top)
+ freeaddrinfo(top);
#ifdef ENABLE_IPV6
- if (hp)
- freehostent(hp);
+ if (hp)
+ freehostent(hp);
#endif
/* bad: */
- *res = NULL;
- return error;
+ *res = NULL;
+ return error;
}
diff --git a/Modules/getbuildinfo.c b/Modules/getbuildinfo.c
index f4bd14a..3bac1c5 100644
--- a/Modules/getbuildinfo.c
+++ b/Modules/getbuildinfo.c
@@ -31,22 +31,22 @@
const char *
Py_GetBuildInfo(void)
{
- static char buildinfo[50];
- const char *revision = Py_SubversionRevision();
- const char *sep = *revision ? ":" : "";
- const char *branch = Py_SubversionShortBranch();
- PyOS_snprintf(buildinfo, sizeof(buildinfo),
- "%s%s%s, %.20s, %.9s", branch, sep, revision,
- DATE, TIME);
- return buildinfo;
+ static char buildinfo[50];
+ const char *revision = Py_SubversionRevision();
+ const char *sep = *revision ? ":" : "";
+ const char *branch = Py_SubversionShortBranch();
+ PyOS_snprintf(buildinfo, sizeof(buildinfo),
+ "%s%s%s, %.20s, %.9s", branch, sep, revision,
+ DATE, TIME);
+ return buildinfo;
}
const char *
_Py_svnversion(void)
{
- /* the following string can be modified by subwcrev.exe */
- static const char svnversion[] = SVNVERSION;
- if (svnversion[0] != '$')
- return svnversion; /* it was interpolated, or passed on command line */
- return "Unversioned directory";
+ /* the following string can be modified by subwcrev.exe */
+ static const char svnversion[] = SVNVERSION;
+ if (svnversion[0] != '$')
+ return svnversion; /* it was interpolated, or passed on command line */
+ return "Unversioned directory";
}
diff --git a/Modules/getnameinfo.c b/Modules/getnameinfo.c
index 0190a32..e9aeafb 100644
--- a/Modules/getnameinfo.c
+++ b/Modules/getnameinfo.c
@@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
@@ -13,7 +13,7 @@
* 3. Neither the name of the project 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 PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@@ -53,162 +53,162 @@
#define NO 0
static struct gni_afd {
- int a_af;
- int a_addrlen;
- int a_socklen;
- int a_off;
+ int a_af;
+ int a_addrlen;
+ int a_socklen;
+ int a_off;
} gni_afdl [] = {
#ifdef ENABLE_IPV6
- {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
- offsetof(struct sockaddr_in6, sin6_addr)},
+ {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
+ offsetof(struct sockaddr_in6, sin6_addr)},
#endif
- {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
- offsetof(struct sockaddr_in, sin_addr)},
- {0, 0, 0},
+ {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
+ offsetof(struct sockaddr_in, sin_addr)},
+ {0, 0, 0},
};
struct gni_sockinet {
- u_char si_len;
- u_char si_family;
- u_short si_port;
+ u_char si_len;
+ u_char si_family;
+ u_short si_port;
};
-#define ENI_NOSOCKET 0
-#define ENI_NOSERVNAME 1
-#define ENI_NOHOSTNAME 2
-#define ENI_MEMORY 3
-#define ENI_SYSTEM 4
-#define ENI_FAMILY 5
-#define ENI_SALEN 6
+#define ENI_NOSOCKET 0
+#define ENI_NOSERVNAME 1
+#define ENI_NOHOSTNAME 2
+#define ENI_MEMORY 3
+#define ENI_SYSTEM 4
+#define ENI_FAMILY 5
+#define ENI_SALEN 6
/* forward declaration to make gcc happy */
int getnameinfo(const struct sockaddr *, size_t, char *, size_t,
- char *, size_t, int);
+ char *, size_t, int);
int
getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
- const struct sockaddr *sa;
- size_t salen;
- char *host;
- size_t hostlen;
- char *serv;
- size_t servlen;
- int flags;
+ const struct sockaddr *sa;
+ size_t salen;
+ char *host;
+ size_t hostlen;
+ char *serv;
+ size_t servlen;
+ int flags;
{
- struct gni_afd *gni_afd;
- struct servent *sp;
- struct hostent *hp;
- u_short port;
- int family, len, i;
- char *addr, *p;
- u_long v4a;
+ struct gni_afd *gni_afd;
+ struct servent *sp;
+ struct hostent *hp;
+ u_short port;
+ int family, len, i;
+ char *addr, *p;
+ u_long v4a;
#ifdef ENABLE_IPV6
- u_char pfx;
+ u_char pfx;
#endif
- int h_error;
- char numserv[512];
- char numaddr[512];
+ int h_error;
+ char numserv[512];
+ char numaddr[512];
- if (sa == NULL)
- return ENI_NOSOCKET;
+ if (sa == NULL)
+ return ENI_NOSOCKET;
#ifdef HAVE_SOCKADDR_SA_LEN
- len = sa->sa_len;
- if (len != salen) return ENI_SALEN;
+ len = sa->sa_len;
+ if (len != salen) return ENI_SALEN;
#else
- len = salen;
+ len = salen;
#endif
-
- family = sa->sa_family;
- for (i = 0; gni_afdl[i].a_af; i++)
- if (gni_afdl[i].a_af == family) {
- gni_afd = &gni_afdl[i];
- goto found;
- }
- return ENI_FAMILY;
-
+
+ family = sa->sa_family;
+ for (i = 0; gni_afdl[i].a_af; i++)
+ if (gni_afdl[i].a_af == family) {
+ gni_afd = &gni_afdl[i];
+ goto found;
+ }
+ return ENI_FAMILY;
+
found:
- if (len != gni_afd->a_socklen) return ENI_SALEN;
-
- port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */
- addr = (char *)sa + gni_afd->a_off;
-
- if (serv == NULL || servlen == 0) {
- /* what we should do? */
- } else if (flags & NI_NUMERICSERV) {
- sprintf(numserv, "%d", ntohs(port));
- if (strlen(numserv) > servlen)
- return ENI_MEMORY;
- strcpy(serv, numserv);
- } else {
- sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
- if (sp) {
- if (strlen(sp->s_name) > servlen)
- return ENI_MEMORY;
- strcpy(serv, sp->s_name);
- } else
- return ENI_NOSERVNAME;
- }
-
- switch (sa->sa_family) {
- case AF_INET:
- v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
- if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
- flags |= NI_NUMERICHOST;
- v4a >>= IN_CLASSA_NSHIFT;
- if (v4a == 0 || v4a == IN_LOOPBACKNET)
- flags |= NI_NUMERICHOST;
- break;
+ if (len != gni_afd->a_socklen) return ENI_SALEN;
+
+ port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */
+ addr = (char *)sa + gni_afd->a_off;
+
+ if (serv == NULL || servlen == 0) {
+ /* what we should do? */
+ } else if (flags & NI_NUMERICSERV) {
+ sprintf(numserv, "%d", ntohs(port));
+ if (strlen(numserv) > servlen)
+ return ENI_MEMORY;
+ strcpy(serv, numserv);
+ } else {
+ sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
+ if (sp) {
+ if (strlen(sp->s_name) > servlen)
+ return ENI_MEMORY;
+ strcpy(serv, sp->s_name);
+ } else
+ return ENI_NOSERVNAME;
+ }
+
+ switch (sa->sa_family) {
+ case AF_INET:
+ v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
+ if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
+ flags |= NI_NUMERICHOST;
+ v4a >>= IN_CLASSA_NSHIFT;
+ if (v4a == 0 || v4a == IN_LOOPBACKNET)
+ flags |= NI_NUMERICHOST;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
- if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
- flags |= NI_NUMERICHOST;
- break;
+ case AF_INET6:
+ pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
+ if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
+ flags |= NI_NUMERICHOST;
+ break;
#endif
- }
- if (host == NULL || hostlen == 0) {
- /* what should we do? */
- } else if (flags & NI_NUMERICHOST) {
- if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
- == NULL)
- return ENI_SYSTEM;
- if (strlen(numaddr) > hostlen)
- return ENI_MEMORY;
- strcpy(host, numaddr);
- } else {
+ }
+ if (host == NULL || hostlen == 0) {
+ /* what should we do? */
+ } else if (flags & NI_NUMERICHOST) {
+ if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
+ == NULL)
+ return ENI_SYSTEM;
+ if (strlen(numaddr) > hostlen)
+ return ENI_MEMORY;
+ strcpy(host, numaddr);
+ } else {
#ifdef ENABLE_IPV6
- hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error);
+ hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error);
#else
- hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af);
- h_error = h_errno;
+ hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af);
+ h_error = h_errno;
#endif
- if (hp) {
- if (flags & NI_NOFQDN) {
- p = strchr(hp->h_name, '.');
- if (p) *p = '\0';
- }
- if (strlen(hp->h_name) > hostlen) {
+ if (hp) {
+ if (flags & NI_NOFQDN) {
+ p = strchr(hp->h_name, '.');
+ if (p) *p = '\0';
+ }
+ if (strlen(hp->h_name) > hostlen) {
#ifdef ENABLE_IPV6
- freehostent(hp);
+ freehostent(hp);
#endif
- return ENI_MEMORY;
- }
- strcpy(host, hp->h_name);
+ return ENI_MEMORY;
+ }
+ strcpy(host, hp->h_name);
#ifdef ENABLE_IPV6
- freehostent(hp);
+ freehostent(hp);
#endif
- } else {
- if (flags & NI_NAMEREQD)
- return ENI_NOHOSTNAME;
- if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
- == NULL)
- return ENI_NOHOSTNAME;
- if (strlen(numaddr) > hostlen)
- return ENI_MEMORY;
- strcpy(host, numaddr);
- }
- }
- return SUCCESS;
+ } else {
+ if (flags & NI_NAMEREQD)
+ return ENI_NOHOSTNAME;
+ if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
+ == NULL)
+ return ENI_NOHOSTNAME;
+ if (strlen(numaddr) > hostlen)
+ return ENI_MEMORY;
+ strcpy(host, numaddr);
+ }
+ }
+ return SUCCESS;
}
diff --git a/Modules/getpath.c b/Modules/getpath.c
index c6e50d3..a5b01ed 100644
--- a/Modules/getpath.c
+++ b/Modules/getpath.c
@@ -142,8 +142,8 @@ _wstat(const wchar_t* path, struct stat *buf)
char fname[PATH_MAX];
size_t res = wcstombs(fname, path, sizeof(fname));
if (res == (size_t)-1) {
- errno = EINVAL;
- return -1;
+ errno = EINVAL;
+ return -1;
}
return stat(fname, buf);
}
@@ -155,17 +155,17 @@ _wgetcwd(wchar_t *buf, size_t size)
{
char fname[PATH_MAX];
if (getcwd(fname, PATH_MAX) == NULL)
- return NULL;
+ return NULL;
if (mbstowcs(buf, fname, size) >= size) {
- errno = ERANGE;
- return NULL;
+ errno = ERANGE;
+ return NULL;
}
return buf;
}
#endif
#ifdef HAVE_READLINK
-int
+int
_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
{
char cbuf[PATH_MAX];
@@ -173,24 +173,24 @@ _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
int res;
size_t r1 = wcstombs(cpath, path, PATH_MAX);
if (r1 == (size_t)-1 || r1 >= PATH_MAX) {
- errno = EINVAL;
- return -1;
+ errno = EINVAL;
+ return -1;
}
res = (int)readlink(cpath, cbuf, PATH_MAX);
if (res == -1)
- return -1;
+ return -1;
if (res == PATH_MAX) {
- errno = EINVAL;
- return -1;
+ errno = EINVAL;
+ return -1;
}
cbuf[res] = '\0'; /* buf will be null terminated */
r1 = mbstowcs(buf, cbuf, bufsiz);
if (r1 == -1) {
- errno = EINVAL;
- return -1;
+ errno = EINVAL;
+ return -1;
}
return (int)r1;
-
+
}
#endif
@@ -279,7 +279,7 @@ joinpath(wchar_t *buffer, wchar_t *stuff)
buffer[n++] = SEP;
}
if (n > MAXPATHLEN)
- Py_FatalError("buffer overflow in getpath.c's joinpath()");
+ Py_FatalError("buffer overflow in getpath.c's joinpath()");
k = wcslen(stuff);
if (n + k > MAXPATHLEN)
k = MAXPATHLEN - n;
@@ -457,25 +457,25 @@ calculate_path(void)
#else
unsigned long nsexeclength = MAXPATHLEN;
#endif
- char execpath[MAXPATHLEN+1];
+ char execpath[MAXPATHLEN+1];
#endif
if (_path) {
- size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1);
- path = wpath;
- if (r == (size_t)-1 || r > MAXPATHLEN) {
- /* Could not convert PATH, or it's too long. */
- path = NULL;
- }
+ size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1);
+ path = wpath;
+ if (r == (size_t)-1 || r > MAXPATHLEN) {
+ /* Could not convert PATH, or it's too long. */
+ path = NULL;
+ }
}
- /* If there is no slash in the argv0 path, then we have to
- * assume python is on the user's $PATH, since there's no
- * other way to find a directory to start the search from. If
- * $PATH isn't exported, you lose.
- */
- if (wcschr(prog, SEP))
- wcsncpy(progpath, prog, MAXPATHLEN);
+ /* If there is no slash in the argv0 path, then we have to
+ * assume python is on the user's $PATH, since there's no
+ * other way to find a directory to start the search from. If
+ * $PATH isn't exported, you lose.
+ */
+ if (wcschr(prog, SEP))
+ wcsncpy(progpath, prog, MAXPATHLEN);
#ifdef __APPLE__
/* On Mac OS X, if a script uses an interpreter of the form
* "#!/opt/python2.3/bin/python", the kernel only passes "python"
@@ -487,52 +487,52 @@ calculate_path(void)
* will fail if a relative path was used. but in that case,
* absolutize() should help us out below
*/
- else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) {
- size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1);
- if (r == (size_t)-1 || r > MAXPATHLEN) {
- /* Could not convert execpath, or it's too long. */
- progpath[0] = '\0';
- }
- }
+ else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) {
+ size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1);
+ if (r == (size_t)-1 || r > MAXPATHLEN) {
+ /* Could not convert execpath, or it's too long. */
+ progpath[0] = '\0';
+ }
+ }
#endif /* __APPLE__ */
- else if (path) {
- while (1) {
- wchar_t *delim = wcschr(path, DELIM);
-
- if (delim) {
- size_t len = delim - path;
- if (len > MAXPATHLEN)
- len = MAXPATHLEN;
- wcsncpy(progpath, path, len);
- *(progpath + len) = '\0';
- }
- else
- wcsncpy(progpath, path, MAXPATHLEN);
-
- joinpath(progpath, prog);
- if (isxfile(progpath))
- break;
-
- if (!delim) {
- progpath[0] = L'\0';
- break;
- }
- path = delim + 1;
- }
- }
- else
- progpath[0] = '\0';
- if (progpath[0] != SEP && progpath[0] != '\0')
- absolutize(progpath);
- wcsncpy(argv0_path, progpath, MAXPATHLEN);
- argv0_path[MAXPATHLEN] = '\0';
+ else if (path) {
+ while (1) {
+ wchar_t *delim = wcschr(path, DELIM);
+
+ if (delim) {
+ size_t len = delim - path;
+ if (len > MAXPATHLEN)
+ len = MAXPATHLEN;
+ wcsncpy(progpath, path, len);
+ *(progpath + len) = '\0';
+ }
+ else
+ wcsncpy(progpath, path, MAXPATHLEN);
+
+ joinpath(progpath, prog);
+ if (isxfile(progpath))
+ break;
+
+ if (!delim) {
+ progpath[0] = L'\0';
+ break;
+ }
+ path = delim + 1;
+ }
+ }
+ else
+ progpath[0] = '\0';
+ if (progpath[0] != SEP && progpath[0] != '\0')
+ absolutize(progpath);
+ wcsncpy(argv0_path, progpath, MAXPATHLEN);
+ argv0_path[MAXPATHLEN] = '\0';
#ifdef WITH_NEXT_FRAMEWORK
- /* On Mac OS X we have a special case if we're running from a framework.
- ** This is because the python home should be set relative to the library,
- ** which is in the framework, not relative to the executable, which may
- ** be outside of the framework. Except when we're in the build directory...
- */
+ /* On Mac OS X we have a special case if we're running from a framework.
+ ** This is because the python home should be set relative to the library,
+ ** which is in the framework, not relative to the executable, which may
+ ** be outside of the framework. Except when we're in the build directory...
+ */
pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize"));
/* Use dylib functions to find out where the framework was loaded from */
buf = (wchar_t *)NSLibraryNameForModule(pythonModule);
@@ -604,7 +604,7 @@ calculate_path(void)
else
wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN);
joinpath(zip_path, L"lib/python00.zip");
- bufsz = wcslen(zip_path); /* Replace "00" with version */
+ bufsz = wcslen(zip_path); /* Replace "00" with version */
zip_path[bufsz - 6] = VERSION[0];
zip_path[bufsz - 5] = VERSION[2];
@@ -626,12 +626,12 @@ calculate_path(void)
bufsz = 0;
if (_rtpypath) {
- size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t));
- if (s == (size_t)-1 || s >=sizeof(rtpypath))
- /* XXX deal with errors more gracefully */
- _rtpypath = NULL;
- if (_rtpypath)
- bufsz += wcslen(rtpypath) + 1;
+ size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t));
+ if (s == (size_t)-1 || s >=sizeof(rtpypath))
+ /* XXX deal with errors more gracefully */
+ _rtpypath = NULL;
+ if (_rtpypath)
+ bufsz += wcslen(rtpypath) + 1;
}
prefixsz = wcslen(prefix) + 1;
@@ -718,10 +718,10 @@ calculate_path(void)
if (pfound > 0) {
reduce(prefix);
reduce(prefix);
- /* The prefix is the root directory, but reduce() chopped
- * off the "/". */
- if (!prefix[0])
- wcscpy(prefix, separator);
+ /* The prefix is the root directory, but reduce() chopped
+ * off the "/". */
+ if (!prefix[0])
+ wcscpy(prefix, separator);
}
else
wcsncpy(prefix, L"" PREFIX, MAXPATHLEN);
@@ -730,8 +730,8 @@ calculate_path(void)
reduce(exec_prefix);
reduce(exec_prefix);
reduce(exec_prefix);
- if (!exec_prefix[0])
- wcscpy(exec_prefix, separator);
+ if (!exec_prefix[0])
+ wcscpy(exec_prefix, separator);
}
else
wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN);
diff --git a/Modules/grpmodule.c b/Modules/grpmodule.c
index 912d139..d10a79d 100644
--- a/Modules/grpmodule.c
+++ b/Modules/grpmodule.c
@@ -10,8 +10,8 @@
static PyStructSequence_Field struct_group_type_fields[] = {
{"gr_name", "group name"},
{"gr_passwd", "password"},
- {"gr_gid", "group id"},
- {"gr_mem", "group memebers"},
+ {"gr_gid", "group id"},
+ {"gr_mem", "group memebers"},
{0}
};
@@ -64,10 +64,10 @@ mkgrent(struct group *p)
Py_INCREF(Py_None);
#else
if (p->gr_passwd)
- SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd));
+ SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd));
else {
- SET(setIndex++, Py_None);
- Py_INCREF(Py_None);
+ SET(setIndex++, Py_None);
+ Py_INCREF(Py_None);
}
#endif
SET(setIndex++, PyLong_FromLong((long) p->gr_gid));
@@ -91,12 +91,12 @@ grp_getgrgid(PyObject *self, PyObject *pyo_id)
py_int_id = PyNumber_Long(pyo_id);
if (!py_int_id)
- return NULL;
+ return NULL;
gid = PyLong_AS_LONG(py_int_id);
Py_DECREF(py_int_id);
if ((p = getgrgid(gid)) == NULL) {
- PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid);
+ PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid);
return NULL;
}
return mkgrent(p);
@@ -116,9 +116,9 @@ grp_getgrnam(PyObject *self, PyObject *args)
return NULL;
if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
goto out;
-
+
if ((p = getgrnam(name)) == NULL) {
- PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name);
+ PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name);
goto out;
}
retval = mkgrent(p);
@@ -151,18 +151,18 @@ grp_getgrall(PyObject *self, PyObject *ignore)
}
static PyMethodDef grp_methods[] = {
- {"getgrgid", grp_getgrgid, METH_O,
+ {"getgrgid", grp_getgrgid, METH_O,
"getgrgid(id) -> tuple\n\
Return the group database entry for the given numeric group ID. If\n\
id is not valid, raise KeyError."},
- {"getgrnam", grp_getgrnam, METH_VARARGS,
+ {"getgrnam", grp_getgrnam, METH_VARARGS,
"getgrnam(name) -> tuple\n\
Return the group database entry for the given group name. If\n\
name is not valid, raise KeyError."},
- {"getgrall", grp_getgrall, METH_NOARGS,
+ {"getgrall", grp_getgrall, METH_NOARGS,
"getgrall() -> list of tuples\n\
Return a list of all available group entries, in arbitrary order."},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(grp__doc__,
@@ -184,15 +184,15 @@ complete membership information.)");
static struct PyModuleDef grpmodule = {
- PyModuleDef_HEAD_INIT,
- "grp",
- grp__doc__,
- -1,
- grp_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "grp",
+ grp__doc__,
+ -1,
+ grp_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -204,7 +204,7 @@ PyInit_grp(void)
return NULL;
d = PyModule_GetDict(m);
if (!initialized)
- PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc);
+ PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc);
PyDict_SetItemString(d, "struct_group", (PyObject *) &StructGrpType);
initialized = 1;
return m;
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
index 74396b6..ad95047 100644
--- a/Modules/itertoolsmodule.c
+++ b/Modules/itertoolsmodule.c
@@ -2,7 +2,7 @@
#include "Python.h"
#include "structmember.h"
-/* Itertools module written and maintained
+/* Itertools module written and maintained
by Raymond D. Hettinger <python@rcn.com>
Copyright (c) 2003 Python Software Foundation.
All rights reserved.
@@ -12,12 +12,12 @@
/* groupby object ***********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *it;
- PyObject *keyfunc;
- PyObject *tgtkey;
- PyObject *currkey;
- PyObject *currvalue;
+ PyObject_HEAD
+ PyObject *it;
+ PyObject *keyfunc;
+ PyObject *tgtkey;
+ PyObject *currkey;
+ PyObject *currvalue;
} groupbyobject;
static PyTypeObject groupby_type;
@@ -26,112 +26,112 @@ static PyObject *_grouper_create(groupbyobject *, PyObject *);
static PyObject *
groupby_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- static char *kwargs[] = {"iterable", "key", NULL};
- groupbyobject *gbo;
- PyObject *it, *keyfunc = Py_None;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs,
- &it, &keyfunc))
- return NULL;
-
- gbo = (groupbyobject *)type->tp_alloc(type, 0);
- if (gbo == NULL)
- return NULL;
- gbo->tgtkey = NULL;
- gbo->currkey = NULL;
- gbo->currvalue = NULL;
- gbo->keyfunc = keyfunc;
- Py_INCREF(keyfunc);
- gbo->it = PyObject_GetIter(it);
- if (gbo->it == NULL) {
- Py_DECREF(gbo);
- return NULL;
- }
- return (PyObject *)gbo;
+ static char *kwargs[] = {"iterable", "key", NULL};
+ groupbyobject *gbo;
+ PyObject *it, *keyfunc = Py_None;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs,
+ &it, &keyfunc))
+ return NULL;
+
+ gbo = (groupbyobject *)type->tp_alloc(type, 0);
+ if (gbo == NULL)
+ return NULL;
+ gbo->tgtkey = NULL;
+ gbo->currkey = NULL;
+ gbo->currvalue = NULL;
+ gbo->keyfunc = keyfunc;
+ Py_INCREF(keyfunc);
+ gbo->it = PyObject_GetIter(it);
+ if (gbo->it == NULL) {
+ Py_DECREF(gbo);
+ return NULL;
+ }
+ return (PyObject *)gbo;
}
static void
groupby_dealloc(groupbyobject *gbo)
{
- PyObject_GC_UnTrack(gbo);
- Py_XDECREF(gbo->it);
- Py_XDECREF(gbo->keyfunc);
- Py_XDECREF(gbo->tgtkey);
- Py_XDECREF(gbo->currkey);
- Py_XDECREF(gbo->currvalue);
- Py_TYPE(gbo)->tp_free(gbo);
+ PyObject_GC_UnTrack(gbo);
+ Py_XDECREF(gbo->it);
+ Py_XDECREF(gbo->keyfunc);
+ Py_XDECREF(gbo->tgtkey);
+ Py_XDECREF(gbo->currkey);
+ Py_XDECREF(gbo->currvalue);
+ Py_TYPE(gbo)->tp_free(gbo);
}
static int
groupby_traverse(groupbyobject *gbo, visitproc visit, void *arg)
{
- Py_VISIT(gbo->it);
- Py_VISIT(gbo->keyfunc);
- Py_VISIT(gbo->tgtkey);
- Py_VISIT(gbo->currkey);
- Py_VISIT(gbo->currvalue);
- return 0;
+ Py_VISIT(gbo->it);
+ Py_VISIT(gbo->keyfunc);
+ Py_VISIT(gbo->tgtkey);
+ Py_VISIT(gbo->currkey);
+ Py_VISIT(gbo->currvalue);
+ return 0;
}
static PyObject *
groupby_next(groupbyobject *gbo)
{
- PyObject *newvalue, *newkey, *r, *grouper, *tmp;
-
- /* skip to next iteration group */
- for (;;) {
- if (gbo->currkey == NULL)
- /* pass */;
- else if (gbo->tgtkey == NULL)
- break;
- else {
- int rcmp;
-
- rcmp = PyObject_RichCompareBool(gbo->tgtkey,
- gbo->currkey, Py_EQ);
- if (rcmp == -1)
- return NULL;
- else if (rcmp == 0)
- break;
- }
-
- newvalue = PyIter_Next(gbo->it);
- if (newvalue == NULL)
- return NULL;
-
- if (gbo->keyfunc == Py_None) {
- newkey = newvalue;
- Py_INCREF(newvalue);
- } else {
- newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
- newvalue, NULL);
- if (newkey == NULL) {
- Py_DECREF(newvalue);
- return NULL;
- }
- }
-
- tmp = gbo->currkey;
- gbo->currkey = newkey;
- Py_XDECREF(tmp);
-
- tmp = gbo->currvalue;
- gbo->currvalue = newvalue;
- Py_XDECREF(tmp);
- }
-
- Py_INCREF(gbo->currkey);
- tmp = gbo->tgtkey;
- gbo->tgtkey = gbo->currkey;
- Py_XDECREF(tmp);
-
- grouper = _grouper_create(gbo, gbo->tgtkey);
- if (grouper == NULL)
- return NULL;
-
- r = PyTuple_Pack(2, gbo->currkey, grouper);
- Py_DECREF(grouper);
- return r;
+ PyObject *newvalue, *newkey, *r, *grouper, *tmp;
+
+ /* skip to next iteration group */
+ for (;;) {
+ if (gbo->currkey == NULL)
+ /* pass */;
+ else if (gbo->tgtkey == NULL)
+ break;
+ else {
+ int rcmp;
+
+ rcmp = PyObject_RichCompareBool(gbo->tgtkey,
+ gbo->currkey, Py_EQ);
+ if (rcmp == -1)
+ return NULL;
+ else if (rcmp == 0)
+ break;
+ }
+
+ newvalue = PyIter_Next(gbo->it);
+ if (newvalue == NULL)
+ return NULL;
+
+ if (gbo->keyfunc == Py_None) {
+ newkey = newvalue;
+ Py_INCREF(newvalue);
+ } else {
+ newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
+ newvalue, NULL);
+ if (newkey == NULL) {
+ Py_DECREF(newvalue);
+ return NULL;
+ }
+ }
+
+ tmp = gbo->currkey;
+ gbo->currkey = newkey;
+ Py_XDECREF(tmp);
+
+ tmp = gbo->currvalue;
+ gbo->currvalue = newvalue;
+ Py_XDECREF(tmp);
+ }
+
+ Py_INCREF(gbo->currkey);
+ tmp = gbo->tgtkey;
+ gbo->tgtkey = gbo->currkey;
+ Py_XDECREF(tmp);
+
+ grouper = _grouper_create(gbo, gbo->tgtkey);
+ if (grouper == NULL)
+ return NULL;
+
+ r = PyTuple_Pack(2, gbo->currkey, grouper);
+ Py_DECREF(grouper);
+ return r;
}
PyDoc_STRVAR(groupby_doc,
@@ -139,56 +139,56 @@ PyDoc_STRVAR(groupby_doc,
(key, sub-iterator) grouped by each value of key(value).\n");
static PyTypeObject groupby_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.groupby", /* tp_name */
- sizeof(groupbyobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)groupby_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- groupby_doc, /* tp_doc */
- (traverseproc)groupby_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)groupby_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- groupby_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.groupby", /* tp_name */
+ sizeof(groupbyobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)groupby_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ groupby_doc, /* tp_doc */
+ (traverseproc)groupby_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)groupby_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ groupby_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* _grouper object (internal) ************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *parent;
- PyObject *tgtkey;
+ PyObject_HEAD
+ PyObject *parent;
+ PyObject *tgtkey;
} _grouperobject;
static PyTypeObject _grouper_type;
@@ -196,129 +196,129 @@ static PyTypeObject _grouper_type;
static PyObject *
_grouper_create(groupbyobject *parent, PyObject *tgtkey)
{
- _grouperobject *igo;
+ _grouperobject *igo;
- igo = PyObject_GC_New(_grouperobject, &_grouper_type);
- if (igo == NULL)
- return NULL;
- igo->parent = (PyObject *)parent;
- Py_INCREF(parent);
- igo->tgtkey = tgtkey;
- Py_INCREF(tgtkey);
+ igo = PyObject_GC_New(_grouperobject, &_grouper_type);
+ if (igo == NULL)
+ return NULL;
+ igo->parent = (PyObject *)parent;
+ Py_INCREF(parent);
+ igo->tgtkey = tgtkey;
+ Py_INCREF(tgtkey);
- PyObject_GC_Track(igo);
- return (PyObject *)igo;
+ PyObject_GC_Track(igo);
+ return (PyObject *)igo;
}
static void
_grouper_dealloc(_grouperobject *igo)
{
- PyObject_GC_UnTrack(igo);
- Py_DECREF(igo->parent);
- Py_DECREF(igo->tgtkey);
- PyObject_GC_Del(igo);
+ PyObject_GC_UnTrack(igo);
+ Py_DECREF(igo->parent);
+ Py_DECREF(igo->tgtkey);
+ PyObject_GC_Del(igo);
}
static int
_grouper_traverse(_grouperobject *igo, visitproc visit, void *arg)
{
- Py_VISIT(igo->parent);
- Py_VISIT(igo->tgtkey);
- return 0;
+ Py_VISIT(igo->parent);
+ Py_VISIT(igo->tgtkey);
+ return 0;
}
static PyObject *
_grouper_next(_grouperobject *igo)
{
- groupbyobject *gbo = (groupbyobject *)igo->parent;
- PyObject *newvalue, *newkey, *r;
- int rcmp;
-
- if (gbo->currvalue == NULL) {
- newvalue = PyIter_Next(gbo->it);
- if (newvalue == NULL)
- return NULL;
-
- if (gbo->keyfunc == Py_None) {
- newkey = newvalue;
- Py_INCREF(newvalue);
- } else {
- newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
- newvalue, NULL);
- if (newkey == NULL) {
- Py_DECREF(newvalue);
- return NULL;
- }
- }
-
- assert(gbo->currkey == NULL);
- gbo->currkey = newkey;
- gbo->currvalue = newvalue;
- }
-
- assert(gbo->currkey != NULL);
- rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ);
- if (rcmp <= 0)
- /* got any error or current group is end */
- return NULL;
-
- r = gbo->currvalue;
- gbo->currvalue = NULL;
- Py_CLEAR(gbo->currkey);
-
- return r;
+ groupbyobject *gbo = (groupbyobject *)igo->parent;
+ PyObject *newvalue, *newkey, *r;
+ int rcmp;
+
+ if (gbo->currvalue == NULL) {
+ newvalue = PyIter_Next(gbo->it);
+ if (newvalue == NULL)
+ return NULL;
+
+ if (gbo->keyfunc == Py_None) {
+ newkey = newvalue;
+ Py_INCREF(newvalue);
+ } else {
+ newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
+ newvalue, NULL);
+ if (newkey == NULL) {
+ Py_DECREF(newvalue);
+ return NULL;
+ }
+ }
+
+ assert(gbo->currkey == NULL);
+ gbo->currkey = newkey;
+ gbo->currvalue = newvalue;
+ }
+
+ assert(gbo->currkey != NULL);
+ rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ);
+ if (rcmp <= 0)
+ /* got any error or current group is end */
+ return NULL;
+
+ r = gbo->currvalue;
+ gbo->currvalue = NULL;
+ Py_CLEAR(gbo->currkey);
+
+ return r;
}
static PyTypeObject _grouper_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools._grouper", /* tp_name */
- sizeof(_grouperobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)_grouper_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)_grouper_traverse,/* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)_grouper_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools._grouper", /* tp_name */
+ sizeof(_grouperobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)_grouper_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)_grouper_traverse,/* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)_grouper_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
-
+
/* tee object and with supporting function and objects ***************/
/* The teedataobject pre-allocates space for LINKCELLS number of objects.
To help the object fit neatly inside cache lines (space for 16 to 32
- pointers), the value should be a multiple of 16 minus space for
+ pointers), the value should be a multiple of 16 minus space for
the other structure members including PyHEAD overhead. The larger the
value, the less memory overhead per object and the less time spent
allocating/deallocating new links. The smaller the number, the less
@@ -327,18 +327,18 @@ static PyTypeObject _grouper_type = {
#define LINKCELLS 57
typedef struct {
- PyObject_HEAD
- PyObject *it;
- int numread;
- PyObject *nextlink;
- PyObject *(values[LINKCELLS]);
+ PyObject_HEAD
+ PyObject *it;
+ int numread;
+ PyObject *nextlink;
+ PyObject *(values[LINKCELLS]);
} teedataobject;
typedef struct {
- PyObject_HEAD
- teedataobject *dataobj;
- int index;
- PyObject *weakreflist;
+ PyObject_HEAD
+ teedataobject *dataobj;
+ int index;
+ PyObject *weakreflist;
} teeobject;
static PyTypeObject teedataobject_type;
@@ -346,123 +346,123 @@ static PyTypeObject teedataobject_type;
static PyObject *
teedataobject_new(PyObject *it)
{
- teedataobject *tdo;
+ teedataobject *tdo;
- tdo = PyObject_GC_New(teedataobject, &teedataobject_type);
- if (tdo == NULL)
- return NULL;
+ tdo = PyObject_GC_New(teedataobject, &teedataobject_type);
+ if (tdo == NULL)
+ return NULL;
- tdo->numread = 0;
- tdo->nextlink = NULL;
- Py_INCREF(it);
- tdo->it = it;
- PyObject_GC_Track(tdo);
- return (PyObject *)tdo;
+ tdo->numread = 0;
+ tdo->nextlink = NULL;
+ Py_INCREF(it);
+ tdo->it = it;
+ PyObject_GC_Track(tdo);
+ return (PyObject *)tdo;
}
static PyObject *
teedataobject_jumplink(teedataobject *tdo)
{
- if (tdo->nextlink == NULL)
- tdo->nextlink = teedataobject_new(tdo->it);
- Py_XINCREF(tdo->nextlink);
- return tdo->nextlink;
+ if (tdo->nextlink == NULL)
+ tdo->nextlink = teedataobject_new(tdo->it);
+ Py_XINCREF(tdo->nextlink);
+ return tdo->nextlink;
}
static PyObject *
teedataobject_getitem(teedataobject *tdo, int i)
{
- PyObject *value;
+ PyObject *value;
- assert(i < LINKCELLS);
- if (i < tdo->numread)
- value = tdo->values[i];
- else {
- /* this is the lead iterator, so fetch more data */
- assert(i == tdo->numread);
- value = PyIter_Next(tdo->it);
- if (value == NULL)
- return NULL;
- tdo->numread++;
- tdo->values[i] = value;
- }
- Py_INCREF(value);
- return value;
+ assert(i < LINKCELLS);
+ if (i < tdo->numread)
+ value = tdo->values[i];
+ else {
+ /* this is the lead iterator, so fetch more data */
+ assert(i == tdo->numread);
+ value = PyIter_Next(tdo->it);
+ if (value == NULL)
+ return NULL;
+ tdo->numread++;
+ tdo->values[i] = value;
+ }
+ Py_INCREF(value);
+ return value;
}
static int
teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg)
{
- int i;
- Py_VISIT(tdo->it);
- for (i = 0; i < tdo->numread; i++)
- Py_VISIT(tdo->values[i]);
- Py_VISIT(tdo->nextlink);
- return 0;
+ int i;
+ Py_VISIT(tdo->it);
+ for (i = 0; i < tdo->numread; i++)
+ Py_VISIT(tdo->values[i]);
+ Py_VISIT(tdo->nextlink);
+ return 0;
}
static int
teedataobject_clear(teedataobject *tdo)
{
- int i;
- Py_CLEAR(tdo->it);
- for (i=0 ; i<tdo->numread ; i++)
- Py_CLEAR(tdo->values[i]);
- Py_CLEAR(tdo->nextlink);
- return 0;
+ int i;
+ Py_CLEAR(tdo->it);
+ for (i=0 ; i<tdo->numread ; i++)
+ Py_CLEAR(tdo->values[i]);
+ Py_CLEAR(tdo->nextlink);
+ return 0;
}
static void
teedataobject_dealloc(teedataobject *tdo)
{
- PyObject_GC_UnTrack(tdo);
- teedataobject_clear(tdo);
- PyObject_GC_Del(tdo);
+ PyObject_GC_UnTrack(tdo);
+ teedataobject_clear(tdo);
+ PyObject_GC_Del(tdo);
}
PyDoc_STRVAR(teedataobject_doc, "Data container common to multiple tee objects.");
static PyTypeObject teedataobject_type = {
- PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
- "itertools.tee_dataobject", /* tp_name */
- sizeof(teedataobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)teedataobject_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- teedataobject_doc, /* tp_doc */
- (traverseproc)teedataobject_traverse, /* tp_traverse */
- (inquiry)teedataobject_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
+ "itertools.tee_dataobject", /* tp_name */
+ sizeof(teedataobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)teedataobject_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ teedataobject_doc, /* tp_doc */
+ (traverseproc)teedataobject_traverse, /* tp_traverse */
+ (inquiry)teedataobject_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -471,42 +471,42 @@ static PyTypeObject tee_type;
static PyObject *
tee_next(teeobject *to)
{
- PyObject *value, *link;
+ PyObject *value, *link;
- if (to->index >= LINKCELLS) {
- link = teedataobject_jumplink(to->dataobj);
- Py_DECREF(to->dataobj);
- to->dataobj = (teedataobject *)link;
- to->index = 0;
- }
- value = teedataobject_getitem(to->dataobj, to->index);
- if (value == NULL)
- return NULL;
- to->index++;
- return value;
+ if (to->index >= LINKCELLS) {
+ link = teedataobject_jumplink(to->dataobj);
+ Py_DECREF(to->dataobj);
+ to->dataobj = (teedataobject *)link;
+ to->index = 0;
+ }
+ value = teedataobject_getitem(to->dataobj, to->index);
+ if (value == NULL)
+ return NULL;
+ to->index++;
+ return value;
}
static int
tee_traverse(teeobject *to, visitproc visit, void *arg)
{
- Py_VISIT((PyObject *)to->dataobj);
- return 0;
+ Py_VISIT((PyObject *)to->dataobj);
+ return 0;
}
static PyObject *
tee_copy(teeobject *to)
{
- teeobject *newto;
+ teeobject *newto;
- newto = PyObject_GC_New(teeobject, &tee_type);
- if (newto == NULL)
- return NULL;
- Py_INCREF(to->dataobj);
- newto->dataobj = to->dataobj;
- newto->index = to->index;
- newto->weakreflist = NULL;
- PyObject_GC_Track(newto);
- return (PyObject *)newto;
+ newto = PyObject_GC_New(teeobject, &tee_type);
+ if (newto == NULL)
+ return NULL;
+ Py_INCREF(to->dataobj);
+ newto->dataobj = to->dataobj;
+ newto->index = to->index;
+ newto->weakreflist = NULL;
+ PyObject_GC_Track(newto);
+ return (PyObject *)newto;
}
PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator.");
@@ -514,154 +514,154 @@ PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator.");
static PyObject *
tee_fromiterable(PyObject *iterable)
{
- teeobject *to;
- PyObject *it = NULL;
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
- if (PyObject_TypeCheck(it, &tee_type)) {
- to = (teeobject *)tee_copy((teeobject *)it);
- goto done;
- }
-
- to = PyObject_GC_New(teeobject, &tee_type);
- if (to == NULL)
- goto done;
- to->dataobj = (teedataobject *)teedataobject_new(it);
- if (!to->dataobj) {
- PyObject_GC_Del(to);
- to = NULL;
- goto done;
- }
-
- to->index = 0;
- to->weakreflist = NULL;
- PyObject_GC_Track(to);
+ teeobject *to;
+ PyObject *it = NULL;
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+ if (PyObject_TypeCheck(it, &tee_type)) {
+ to = (teeobject *)tee_copy((teeobject *)it);
+ goto done;
+ }
+
+ to = PyObject_GC_New(teeobject, &tee_type);
+ if (to == NULL)
+ goto done;
+ to->dataobj = (teedataobject *)teedataobject_new(it);
+ if (!to->dataobj) {
+ PyObject_GC_Del(to);
+ to = NULL;
+ goto done;
+ }
+
+ to->index = 0;
+ to->weakreflist = NULL;
+ PyObject_GC_Track(to);
done:
- Py_XDECREF(it);
- return (PyObject *)to;
+ Py_XDECREF(it);
+ return (PyObject *)to;
}
static PyObject *
tee_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *iterable;
+ PyObject *iterable;
- if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable))
- return NULL;
- return tee_fromiterable(iterable);
+ if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable))
+ return NULL;
+ return tee_fromiterable(iterable);
}
static int
tee_clear(teeobject *to)
{
- if (to->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) to);
- Py_CLEAR(to->dataobj);
- return 0;
+ if (to->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) to);
+ Py_CLEAR(to->dataobj);
+ return 0;
}
static void
tee_dealloc(teeobject *to)
{
- PyObject_GC_UnTrack(to);
- tee_clear(to);
- PyObject_GC_Del(to);
+ PyObject_GC_UnTrack(to);
+ tee_clear(to);
+ PyObject_GC_Del(to);
}
PyDoc_STRVAR(teeobject_doc,
"Iterator wrapped to make it copyable");
static PyMethodDef tee_methods[] = {
- {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc},
- {NULL, NULL} /* sentinel */
+ {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject tee_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.tee", /* tp_name */
- sizeof(teeobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)tee_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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_HAVE_GC, /* tp_flags */
- teeobject_doc, /* tp_doc */
- (traverseproc)tee_traverse, /* tp_traverse */
- (inquiry)tee_clear, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(teeobject, weakreflist), /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)tee_next, /* tp_iternext */
- tee_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- tee_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.tee", /* tp_name */
+ sizeof(teeobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)tee_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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_HAVE_GC, /* tp_flags */
+ teeobject_doc, /* tp_doc */
+ (traverseproc)tee_traverse, /* tp_traverse */
+ (inquiry)tee_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(teeobject, weakreflist), /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)tee_next, /* tp_iternext */
+ tee_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ tee_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
static PyObject *
tee(PyObject *self, PyObject *args)
{
- Py_ssize_t i, n=2;
- PyObject *it, *iterable, *copyable, *result;
-
- if (!PyArg_ParseTuple(args, "O|n", &iterable, &n))
- return NULL;
- if (n < 0) {
- PyErr_SetString(PyExc_ValueError, "n must be >= 0");
- return NULL;
- }
- result = PyTuple_New(n);
- if (result == NULL)
- return NULL;
- if (n == 0)
- return result;
- it = PyObject_GetIter(iterable);
- if (it == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- if (!PyObject_HasAttrString(it, "__copy__")) {
- copyable = tee_fromiterable(it);
- Py_DECREF(it);
- if (copyable == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- } else
- copyable = it;
- PyTuple_SET_ITEM(result, 0, copyable);
- for (i=1 ; i<n ; i++) {
- copyable = PyObject_CallMethod(copyable, "__copy__", NULL);
- if (copyable == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, copyable);
- }
- return result;
+ Py_ssize_t i, n=2;
+ PyObject *it, *iterable, *copyable, *result;
+
+ if (!PyArg_ParseTuple(args, "O|n", &iterable, &n))
+ return NULL;
+ if (n < 0) {
+ PyErr_SetString(PyExc_ValueError, "n must be >= 0");
+ return NULL;
+ }
+ result = PyTuple_New(n);
+ if (result == NULL)
+ return NULL;
+ if (n == 0)
+ return result;
+ it = PyObject_GetIter(iterable);
+ if (it == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ if (!PyObject_HasAttrString(it, "__copy__")) {
+ copyable = tee_fromiterable(it);
+ Py_DECREF(it);
+ if (copyable == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ } else
+ copyable = it;
+ PyTuple_SET_ITEM(result, 0, copyable);
+ for (i=1 ; i<n ; i++) {
+ copyable = PyObject_CallMethod(copyable, "__copy__", NULL);
+ if (copyable == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, copyable);
+ }
+ return result;
}
PyDoc_STRVAR(tee_doc,
@@ -671,10 +671,10 @@ PyDoc_STRVAR(tee_doc,
/* cycle object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *it;
- PyObject *saved;
- int firstpass;
+ PyObject_HEAD
+ PyObject *it;
+ PyObject *saved;
+ int firstpass;
} cycleobject;
static PyTypeObject cycle_type;
@@ -682,91 +682,91 @@ static PyTypeObject cycle_type;
static PyObject *
cycle_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *it;
- PyObject *iterable;
- PyObject *saved;
- cycleobject *lz;
+ PyObject *it;
+ PyObject *iterable;
+ PyObject *saved;
+ cycleobject *lz;
- if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
- return NULL;
+ if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
+ return NULL;
- /* Get iterator. */
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
+ /* Get iterator. */
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
- saved = PyList_New(0);
- if (saved == NULL) {
- Py_DECREF(it);
- return NULL;
- }
+ saved = PyList_New(0);
+ if (saved == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
- /* create cycleobject structure */
- lz = (cycleobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- Py_DECREF(saved);
- return NULL;
- }
- lz->it = it;
- lz->saved = saved;
- lz->firstpass = 0;
+ /* create cycleobject structure */
+ lz = (cycleobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ Py_DECREF(saved);
+ return NULL;
+ }
+ lz->it = it;
+ lz->saved = saved;
+ lz->firstpass = 0;
- return (PyObject *)lz;
+ return (PyObject *)lz;
}
static void
cycle_dealloc(cycleobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->saved);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->saved);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
cycle_traverse(cycleobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->saved);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->saved);
+ return 0;
}
static PyObject *
cycle_next(cycleobject *lz)
{
- PyObject *item;
- PyObject *it;
- PyObject *tmp;
-
- while (1) {
- item = PyIter_Next(lz->it);
- if (item != NULL) {
- if (!lz->firstpass && PyList_Append(lz->saved, item)) {
- Py_DECREF(item);
- return NULL;
- }
- return item;
- }
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- return NULL;
- }
- if (PyList_Size(lz->saved) == 0)
- return NULL;
- it = PyObject_GetIter(lz->saved);
- if (it == NULL)
- return NULL;
- tmp = lz->it;
- lz->it = it;
- lz->firstpass = 1;
- Py_DECREF(tmp);
- }
+ PyObject *item;
+ PyObject *it;
+ PyObject *tmp;
+
+ while (1) {
+ item = PyIter_Next(lz->it);
+ if (item != NULL) {
+ if (!lz->firstpass && PyList_Append(lz->saved, item)) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ return item;
+ }
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ if (PyList_Size(lz->saved) == 0)
+ return NULL;
+ it = PyObject_GetIter(lz->saved);
+ if (it == NULL)
+ return NULL;
+ tmp = lz->it;
+ lz->it = it;
+ lz->firstpass = 1;
+ Py_DECREF(tmp);
+ }
}
PyDoc_STRVAR(cycle_doc,
@@ -776,57 +776,57 @@ Return elements from the iterable until it is exhausted.\n\
Then repeat the sequence indefinitely.");
static PyTypeObject cycle_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.cycle", /* tp_name */
- sizeof(cycleobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)cycle_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- cycle_doc, /* tp_doc */
- (traverseproc)cycle_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)cycle_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- cycle_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.cycle", /* tp_name */
+ sizeof(cycleobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)cycle_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ cycle_doc, /* tp_doc */
+ (traverseproc)cycle_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)cycle_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ cycle_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* dropwhile object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
- long start;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
+ long start;
} dropwhileobject;
static PyTypeObject dropwhile_type;
@@ -834,81 +834,81 @@ static PyTypeObject dropwhile_type;
static PyObject *
dropwhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- dropwhileobject *lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ dropwhileobject *lz;
- if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds))
- return NULL;
+ if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq))
+ return NULL;
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
- /* create dropwhileobject structure */
- lz = (dropwhileobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
- lz->start = 0;
+ /* create dropwhileobject structure */
+ lz = (dropwhileobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+ lz->start = 0;
- return (PyObject *)lz;
+ return (PyObject *)lz;
}
static void
dropwhile_dealloc(dropwhileobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
dropwhile_traverse(dropwhileobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
dropwhile_next(dropwhileobject *lz)
{
- PyObject *item, *good;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
- if (lz->start == 1)
- return item;
-
- good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- if (!ok) {
- lz->start = 1;
- return item;
- }
- Py_DECREF(item);
- }
+ PyObject *item, *good;
+ PyObject *it = lz->it;
+ long ok;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+ if (lz->start == 1)
+ return item;
+
+ good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ if (!ok) {
+ lz->start = 1;
+ return item;
+ }
+ Py_DECREF(item);
+ }
}
PyDoc_STRVAR(dropwhile_doc,
@@ -918,57 +918,57 @@ Drop items from the iterable while predicate(item) is true.\n\
Afterwards, return every element until the iterable is exhausted.");
static PyTypeObject dropwhile_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.dropwhile", /* tp_name */
- sizeof(dropwhileobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dropwhile_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- dropwhile_doc, /* tp_doc */
- (traverseproc)dropwhile_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dropwhile_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- dropwhile_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.dropwhile", /* tp_name */
+ sizeof(dropwhileobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dropwhile_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ dropwhile_doc, /* tp_doc */
+ (traverseproc)dropwhile_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dropwhile_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ dropwhile_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* takewhile object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
- long stop;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
+ long stop;
} takewhileobject;
static PyTypeObject takewhile_type;
@@ -976,78 +976,78 @@ static PyTypeObject takewhile_type;
static PyObject *
takewhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- takewhileobject *lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ takewhileobject *lz;
- if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds))
- return NULL;
+ if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq))
+ return NULL;
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
- /* create takewhileobject structure */
- lz = (takewhileobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
- lz->stop = 0;
+ /* create takewhileobject structure */
+ lz = (takewhileobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+ lz->stop = 0;
- return (PyObject *)lz;
+ return (PyObject *)lz;
}
static void
takewhile_dealloc(takewhileobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
takewhile_traverse(takewhileobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
takewhile_next(takewhileobject *lz)
{
- PyObject *item, *good;
- PyObject *it = lz->it;
- long ok;
+ PyObject *item, *good;
+ PyObject *it = lz->it;
+ long ok;
- if (lz->stop == 1)
- return NULL;
+ if (lz->stop == 1)
+ return NULL;
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL)
- return NULL;
+ item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (item == NULL)
+ return NULL;
- good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- if (ok)
- return item;
- Py_DECREF(item);
- lz->stop = 1;
- return NULL;
+ good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ if (ok)
+ return item;
+ Py_DECREF(item);
+ lz->stop = 1;
+ return NULL;
}
PyDoc_STRVAR(takewhile_doc,
@@ -1057,59 +1057,59 @@ Return successive entries from an iterable as long as the \n\
predicate evaluates to true for each entry.");
static PyTypeObject takewhile_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.takewhile", /* tp_name */
- sizeof(takewhileobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)takewhile_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- takewhile_doc, /* tp_doc */
- (traverseproc)takewhile_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)takewhile_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- takewhile_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.takewhile", /* tp_name */
+ sizeof(takewhileobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)takewhile_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ takewhile_doc, /* tp_doc */
+ (traverseproc)takewhile_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)takewhile_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ takewhile_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* islice object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *it;
- Py_ssize_t next;
- Py_ssize_t stop;
- Py_ssize_t step;
- Py_ssize_t cnt;
+ PyObject_HEAD
+ PyObject *it;
+ Py_ssize_t next;
+ Py_ssize_t stop;
+ Py_ssize_t step;
+ Py_ssize_t cnt;
} isliceobject;
static PyTypeObject islice_type;
@@ -1117,126 +1117,126 @@ static PyTypeObject islice_type;
static PyObject *
islice_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *seq;
- Py_ssize_t start=0, stop=-1, step=1;
- PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL;
- Py_ssize_t numargs;
- isliceobject *lz;
-
- if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3))
- return NULL;
-
- numargs = PyTuple_Size(args);
- if (numargs == 2) {
- if (a1 != Py_None) {
- stop = PyLong_AsSsize_t(a1);
- if (stop == -1) {
- if (PyErr_Occurred())
- PyErr_Clear();
- PyErr_SetString(PyExc_ValueError,
- "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.");
- return NULL;
- }
- }
- } else {
- if (a1 != Py_None)
- start = PyLong_AsSsize_t(a1);
- if (start == -1 && PyErr_Occurred())
- PyErr_Clear();
- if (a2 != Py_None) {
- stop = PyLong_AsSsize_t(a2);
- if (stop == -1) {
- if (PyErr_Occurred())
- PyErr_Clear();
- PyErr_SetString(PyExc_ValueError,
- "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.");
- return NULL;
- }
- }
- }
- if (start<0 || stop<-1) {
- PyErr_SetString(PyExc_ValueError,
- "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.");
- return NULL;
- }
-
- if (a3 != NULL) {
- if (a3 != Py_None)
- step = PyLong_AsSsize_t(a3);
- if (step == -1 && PyErr_Occurred())
- PyErr_Clear();
- }
- if (step<1) {
- PyErr_SetString(PyExc_ValueError,
- "Step for islice() must be a positive integer or None.");
- return NULL;
- }
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create isliceobject structure */
- lz = (isliceobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- lz->it = it;
- lz->next = start;
- lz->stop = stop;
- lz->step = step;
- lz->cnt = 0L;
-
- return (PyObject *)lz;
+ PyObject *seq;
+ Py_ssize_t start=0, stop=-1, step=1;
+ PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL;
+ Py_ssize_t numargs;
+ isliceobject *lz;
+
+ if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3))
+ return NULL;
+
+ numargs = PyTuple_Size(args);
+ if (numargs == 2) {
+ if (a1 != Py_None) {
+ stop = PyLong_AsSsize_t(a1);
+ if (stop == -1) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ PyErr_SetString(PyExc_ValueError,
+ "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.");
+ return NULL;
+ }
+ }
+ } else {
+ if (a1 != Py_None)
+ start = PyLong_AsSsize_t(a1);
+ if (start == -1 && PyErr_Occurred())
+ PyErr_Clear();
+ if (a2 != Py_None) {
+ stop = PyLong_AsSsize_t(a2);
+ if (stop == -1) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ PyErr_SetString(PyExc_ValueError,
+ "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.");
+ return NULL;
+ }
+ }
+ }
+ if (start<0 || stop<-1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.");
+ return NULL;
+ }
+
+ if (a3 != NULL) {
+ if (a3 != Py_None)
+ step = PyLong_AsSsize_t(a3);
+ if (step == -1 && PyErr_Occurred())
+ PyErr_Clear();
+ }
+ if (step<1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Step for islice() must be a positive integer or None.");
+ return NULL;
+ }
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create isliceobject structure */
+ lz = (isliceobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ lz->it = it;
+ lz->next = start;
+ lz->stop = stop;
+ lz->step = step;
+ lz->cnt = 0L;
+
+ return (PyObject *)lz;
}
static void
islice_dealloc(isliceobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
islice_traverse(isliceobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- return 0;
+ Py_VISIT(lz->it);
+ return 0;
}
static PyObject *
islice_next(isliceobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- Py_ssize_t oldnext;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- while (lz->cnt < lz->next) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
- Py_DECREF(item);
- lz->cnt++;
- }
- if (lz->stop != -1 && lz->cnt >= lz->stop)
- return NULL;
- item = iternext(it);
- if (item == NULL)
- return NULL;
- lz->cnt++;
- oldnext = lz->next;
- lz->next += lz->step;
- if (lz->next < oldnext) /* Check for overflow */
- lz->next = lz->stop;
- return item;
+ PyObject *item;
+ PyObject *it = lz->it;
+ Py_ssize_t oldnext;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ while (lz->cnt < lz->next) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+ Py_DECREF(item);
+ lz->cnt++;
+ }
+ if (lz->stop != -1 && lz->cnt >= lz->stop)
+ return NULL;
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+ lz->cnt++;
+ oldnext = lz->next;
+ lz->next += lz->step;
+ if (lz->next < oldnext) /* Check for overflow */
+ lz->next = lz->stop;
+ return item;
}
PyDoc_STRVAR(islice_doc,
@@ -1250,56 +1250,56 @@ skipped between successive calls. Works like a slice() on a list\n\
but returns an iterator.");
static PyTypeObject islice_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.islice", /* tp_name */
- sizeof(isliceobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)islice_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- islice_doc, /* tp_doc */
- (traverseproc)islice_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)islice_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- islice_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.islice", /* tp_name */
+ sizeof(isliceobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)islice_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ islice_doc, /* tp_doc */
+ (traverseproc)islice_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)islice_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ islice_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* starmap object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} starmapobject;
static PyTypeObject starmap_type;
@@ -1307,71 +1307,71 @@ static PyTypeObject starmap_type;
static PyObject *
starmap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- starmapobject *lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ starmapobject *lz;
- if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds))
- return NULL;
+ if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq))
+ return NULL;
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
- /* create starmapobject structure */
- lz = (starmapobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
+ /* create starmapobject structure */
+ lz = (starmapobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
- return (PyObject *)lz;
+ return (PyObject *)lz;
}
static void
starmap_dealloc(starmapobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
starmap_traverse(starmapobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
starmap_next(starmapobject *lz)
{
- PyObject *args;
- PyObject *result;
- PyObject *it = lz->it;
-
- args = (*Py_TYPE(it)->tp_iternext)(it);
- if (args == NULL)
- return NULL;
- if (!PyTuple_CheckExact(args)) {
- PyObject *newargs = PySequence_Tuple(args);
- Py_DECREF(args);
- if (newargs == NULL)
- return NULL;
- args = newargs;
- }
- result = PyObject_Call(lz->func, args, NULL);
- Py_DECREF(args);
- return result;
+ PyObject *args;
+ PyObject *result;
+ PyObject *it = lz->it;
+
+ args = (*Py_TYPE(it)->tp_iternext)(it);
+ if (args == NULL)
+ return NULL;
+ if (!PyTuple_CheckExact(args)) {
+ PyObject *newargs = PySequence_Tuple(args);
+ Py_DECREF(args);
+ if (newargs == NULL)
+ return NULL;
+ args = newargs;
+ }
+ result = PyObject_Call(lz->func, args, NULL);
+ Py_DECREF(args);
+ return result;
}
PyDoc_STRVAR(starmap_doc,
@@ -1381,152 +1381,152 @@ Return an iterator whose values are returned from the function evaluated\n\
with a argument tuple taken from the given sequence.");
static PyTypeObject starmap_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.starmap", /* tp_name */
- sizeof(starmapobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)starmap_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- starmap_doc, /* tp_doc */
- (traverseproc)starmap_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)starmap_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- starmap_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.starmap", /* tp_name */
+ sizeof(starmapobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)starmap_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ starmap_doc, /* tp_doc */
+ (traverseproc)starmap_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)starmap_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ starmap_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* chain object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *source; /* Iterator over input iterables */
- PyObject *active; /* Currently running input iterator */
+ PyObject_HEAD
+ PyObject *source; /* Iterator over input iterables */
+ PyObject *active; /* Currently running input iterator */
} chainobject;
static PyTypeObject chain_type;
-static PyObject *
+static PyObject *
chain_new_internal(PyTypeObject *type, PyObject *source)
{
- chainobject *lz;
+ chainobject *lz;
- lz = (chainobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(source);
- return NULL;
- }
-
- lz->source = source;
- lz->active = NULL;
- return (PyObject *)lz;
+ lz = (chainobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(source);
+ return NULL;
+ }
+
+ lz->source = source;
+ lz->active = NULL;
+ return (PyObject *)lz;
}
static PyObject *
chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *source;
+ PyObject *source;
+
+ if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
+ return NULL;
- if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
- return NULL;
-
- source = PyObject_GetIter(args);
- if (source == NULL)
- return NULL;
+ source = PyObject_GetIter(args);
+ if (source == NULL)
+ return NULL;
- return chain_new_internal(type, source);
+ return chain_new_internal(type, source);
}
static PyObject *
chain_new_from_iterable(PyTypeObject *type, PyObject *arg)
{
- PyObject *source;
-
- source = PyObject_GetIter(arg);
- if (source == NULL)
- return NULL;
+ PyObject *source;
+
+ source = PyObject_GetIter(arg);
+ if (source == NULL)
+ return NULL;
- return chain_new_internal(type, source);
+ return chain_new_internal(type, source);
}
static void
chain_dealloc(chainobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->active);
- Py_XDECREF(lz->source);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->active);
+ Py_XDECREF(lz->source);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
chain_traverse(chainobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->source);
- Py_VISIT(lz->active);
- return 0;
+ Py_VISIT(lz->source);
+ Py_VISIT(lz->active);
+ return 0;
}
static PyObject *
chain_next(chainobject *lz)
{
- PyObject *item;
-
- if (lz->source == NULL)
- return NULL; /* already stopped */
-
- if (lz->active == NULL) {
- PyObject *iterable = PyIter_Next(lz->source);
- if (iterable == NULL) {
- Py_CLEAR(lz->source);
- return NULL; /* no more input sources */
- }
- lz->active = PyObject_GetIter(iterable);
- Py_DECREF(iterable);
- if (lz->active == NULL) {
- Py_CLEAR(lz->source);
- return NULL; /* input not iterable */
- }
- }
- item = PyIter_Next(lz->active);
- if (item != NULL)
- return item;
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- return NULL; /* input raised an exception */
- }
- Py_CLEAR(lz->active);
- return chain_next(lz); /* recurse and use next active */
+ PyObject *item;
+
+ if (lz->source == NULL)
+ return NULL; /* already stopped */
+
+ if (lz->active == NULL) {
+ PyObject *iterable = PyIter_Next(lz->source);
+ if (iterable == NULL) {
+ Py_CLEAR(lz->source);
+ return NULL; /* no more input sources */
+ }
+ lz->active = PyObject_GetIter(iterable);
+ Py_DECREF(iterable);
+ if (lz->active == NULL) {
+ Py_CLEAR(lz->source);
+ return NULL; /* input not iterable */
+ }
+ }
+ item = PyIter_Next(lz->active);
+ if (item != NULL)
+ return item;
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ return NULL; /* input raised an exception */
+ }
+ Py_CLEAR(lz->active);
+ return chain_next(lz); /* recurse and use next active */
}
PyDoc_STRVAR(chain_doc,
@@ -1543,64 +1543,64 @@ Alternate chain() contructor taking a single iterable argument\n\
that evaluates lazily.");
static PyMethodDef chain_methods[] = {
- {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS,
- chain_from_iterable_doc},
- {NULL, NULL} /* sentinel */
+ {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS,
+ chain_from_iterable_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject chain_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.chain", /* tp_name */
- sizeof(chainobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)chain_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- chain_doc, /* tp_doc */
- (traverseproc)chain_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)chain_next, /* tp_iternext */
- chain_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- chain_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.chain", /* tp_name */
+ sizeof(chainobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)chain_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ chain_doc, /* tp_doc */
+ (traverseproc)chain_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)chain_next, /* tp_iternext */
+ chain_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ chain_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* product object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *pools; /* tuple of pool tuples */
- Py_ssize_t *indices; /* one index per pool */
- PyObject *result; /* most recently returned result tuple */
- int stopped; /* set to 1 when the product iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pools; /* tuple of pool tuples */
+ Py_ssize_t *indices; /* one index per pool */
+ PyObject *result; /* most recently returned result tuple */
+ int stopped; /* set to 1 when the product iterator is exhausted */
} productobject;
static PyTypeObject product_type;
@@ -1608,181 +1608,181 @@ static PyTypeObject product_type;
static PyObject *
product_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- productobject *lz;
- Py_ssize_t nargs, npools, repeat=1;
- PyObject *pools = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t i;
-
- if (kwds != NULL) {
- char *kwlist[] = {"repeat", 0};
- PyObject *tmpargs = PyTuple_New(0);
- if (tmpargs == NULL)
- return NULL;
- if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) {
- Py_DECREF(tmpargs);
- return NULL;
- }
- Py_DECREF(tmpargs);
- if (repeat < 0) {
- PyErr_SetString(PyExc_ValueError,
- "repeat argument cannot be negative");
- return NULL;
- }
- }
-
- assert(PyTuple_Check(args));
- nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args);
- npools = nargs * repeat;
-
- indices = PyMem_Malloc(npools * sizeof(Py_ssize_t));
- if (indices == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- pools = PyTuple_New(npools);
- if (pools == NULL)
- goto error;
-
- for (i=0; i < nargs ; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- PyObject *pool = PySequence_Tuple(item);
- if (pool == NULL)
- goto error;
- PyTuple_SET_ITEM(pools, i, pool);
- indices[i] = 0;
- }
- for ( ; i < npools; ++i) {
- PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs);
- Py_INCREF(pool);
- PyTuple_SET_ITEM(pools, i, pool);
- indices[i] = 0;
- }
-
- /* create productobject structure */
- lz = (productobject *)type->tp_alloc(type, 0);
- if (lz == NULL)
- goto error;
-
- lz->pools = pools;
- lz->indices = indices;
- lz->result = NULL;
- lz->stopped = 0;
-
- return (PyObject *)lz;
+ productobject *lz;
+ Py_ssize_t nargs, npools, repeat=1;
+ PyObject *pools = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t i;
+
+ if (kwds != NULL) {
+ char *kwlist[] = {"repeat", 0};
+ PyObject *tmpargs = PyTuple_New(0);
+ if (tmpargs == NULL)
+ return NULL;
+ if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) {
+ Py_DECREF(tmpargs);
+ return NULL;
+ }
+ Py_DECREF(tmpargs);
+ if (repeat < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "repeat argument cannot be negative");
+ return NULL;
+ }
+ }
+
+ assert(PyTuple_Check(args));
+ nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args);
+ npools = nargs * repeat;
+
+ indices = PyMem_Malloc(npools * sizeof(Py_ssize_t));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ pools = PyTuple_New(npools);
+ if (pools == NULL)
+ goto error;
+
+ for (i=0; i < nargs ; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *pool = PySequence_Tuple(item);
+ if (pool == NULL)
+ goto error;
+ PyTuple_SET_ITEM(pools, i, pool);
+ indices[i] = 0;
+ }
+ for ( ; i < npools; ++i) {
+ PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs);
+ Py_INCREF(pool);
+ PyTuple_SET_ITEM(pools, i, pool);
+ indices[i] = 0;
+ }
+
+ /* create productobject structure */
+ lz = (productobject *)type->tp_alloc(type, 0);
+ if (lz == NULL)
+ goto error;
+
+ lz->pools = pools;
+ lz->indices = indices;
+ lz->result = NULL;
+ lz->stopped = 0;
+
+ return (PyObject *)lz;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- Py_XDECREF(pools);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ Py_XDECREF(pools);
+ return NULL;
}
static void
product_dealloc(productobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->pools);
- Py_XDECREF(lz->result);
- if (lz->indices != NULL)
- PyMem_Free(lz->indices);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->pools);
+ Py_XDECREF(lz->result);
+ if (lz->indices != NULL)
+ PyMem_Free(lz->indices);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
product_traverse(productobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->pools);
- Py_VISIT(lz->result);
- return 0;
+ Py_VISIT(lz->pools);
+ Py_VISIT(lz->result);
+ return 0;
}
static PyObject *
product_next(productobject *lz)
{
- PyObject *pool;
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pools = lz->pools;
- PyObject *result = lz->result;
- Py_ssize_t npools = PyTuple_GET_SIZE(pools);
- Py_ssize_t i;
-
- if (lz->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, return an initial tuple filled with the
- first element from each pool. */
- result = PyTuple_New(npools);
- if (result == NULL)
- goto empty;
- lz->result = result;
- for (i=0; i < npools; i++) {
- pool = PyTuple_GET_ITEM(pools, i);
- if (PyTuple_GET_SIZE(pool) == 0)
- goto empty;
- elem = PyTuple_GET_ITEM(pool, 0);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- Py_ssize_t *indices = lz->indices;
-
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(npools);
- if (result == NULL)
- goto empty;
- lz->result = result;
- for (i=0; i < npools; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place */
- assert (npools==0 || Py_REFCNT(result) == 1);
-
- /* Update the pool indices right-to-left. Only advance to the
- next pool when the previous one rolls-over */
- for (i=npools-1 ; i >= 0 ; i--) {
- pool = PyTuple_GET_ITEM(pools, i);
- indices[i]++;
- if (indices[i] == PyTuple_GET_SIZE(pool)) {
- /* Roll-over and advance to next pool */
- indices[i] = 0;
- elem = PyTuple_GET_ITEM(pool, 0);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- } else {
- /* No rollover. Just increment and stop here. */
- elem = PyTuple_GET_ITEM(pool, indices[i]);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- break;
- }
- }
-
- /* If i is negative, then the indices have all rolled-over
- and we're done. */
- if (i < 0)
- goto empty;
- }
-
- Py_INCREF(result);
- return result;
+ PyObject *pool;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pools = lz->pools;
+ PyObject *result = lz->result;
+ Py_ssize_t npools = PyTuple_GET_SIZE(pools);
+ Py_ssize_t i;
+
+ if (lz->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, return an initial tuple filled with the
+ first element from each pool. */
+ result = PyTuple_New(npools);
+ if (result == NULL)
+ goto empty;
+ lz->result = result;
+ for (i=0; i < npools; i++) {
+ pool = PyTuple_GET_ITEM(pools, i);
+ if (PyTuple_GET_SIZE(pool) == 0)
+ goto empty;
+ elem = PyTuple_GET_ITEM(pool, 0);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ Py_ssize_t *indices = lz->indices;
+
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(npools);
+ if (result == NULL)
+ goto empty;
+ lz->result = result;
+ for (i=0; i < npools; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place */
+ assert (npools==0 || Py_REFCNT(result) == 1);
+
+ /* Update the pool indices right-to-left. Only advance to the
+ next pool when the previous one rolls-over */
+ for (i=npools-1 ; i >= 0 ; i--) {
+ pool = PyTuple_GET_ITEM(pools, i);
+ indices[i]++;
+ if (indices[i] == PyTuple_GET_SIZE(pool)) {
+ /* Roll-over and advance to next pool */
+ indices[i] = 0;
+ elem = PyTuple_GET_ITEM(pool, 0);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ } else {
+ /* No rollover. Just increment and stop here. */
+ elem = PyTuple_GET_ITEM(pool, indices[i]);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ break;
+ }
+ }
+
+ /* If i is negative, then the indices have all rolled-over
+ and we're done. */
+ if (i < 0)
+ goto empty;
+ }
+
+ Py_INCREF(result);
+ return result;
empty:
- lz->stopped = 1;
- return NULL;
+ lz->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(product_doc,
@@ -1800,59 +1800,59 @@ product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\n\
product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...");
static PyTypeObject product_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.product", /* tp_name */
- sizeof(productobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)product_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- product_doc, /* tp_doc */
- (traverseproc)product_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)product_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- product_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.product", /* tp_name */
+ sizeof(productobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)product_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ product_doc, /* tp_doc */
+ (traverseproc)product_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)product_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ product_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* combinations object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *pool; /* input converted to a tuple */
- Py_ssize_t *indices; /* one index per result element */
- PyObject *result; /* most recently returned result tuple */
- Py_ssize_t r; /* size of result tuple */
- int stopped; /* set to 1 when the combinations iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pool; /* input converted to a tuple */
+ Py_ssize_t *indices; /* one index per result element */
+ PyObject *result; /* most recently returned result tuple */
+ Py_ssize_t r; /* size of result tuple */
+ int stopped; /* set to 1 when the combinations iterator is exhausted */
} combinationsobject;
static PyTypeObject combinations_type;
@@ -1860,160 +1860,160 @@ static PyTypeObject combinations_type;
static PyObject *
combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- combinationsobject *co;
- Py_ssize_t n;
- Py_ssize_t r;
- PyObject *pool = NULL;
- PyObject *iterable = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t i;
- static char *kwargs[] = {"iterable", "r", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
- &iterable, &r))
- return NULL;
-
- pool = PySequence_Tuple(iterable);
- if (pool == NULL)
- goto error;
- n = PyTuple_GET_SIZE(pool);
- if (r < 0) {
- PyErr_SetString(PyExc_ValueError, "r must be non-negative");
- goto error;
- }
-
- indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
- if (indices == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- for (i=0 ; i<r ; i++)
- indices[i] = i;
-
- /* create combinationsobject structure */
- co = (combinationsobject *)type->tp_alloc(type, 0);
- if (co == NULL)
- goto error;
-
- co->pool = pool;
- co->indices = indices;
- co->result = NULL;
- co->r = r;
- co->stopped = r > n ? 1 : 0;
-
- return (PyObject *)co;
+ combinationsobject *co;
+ Py_ssize_t n;
+ Py_ssize_t r;
+ PyObject *pool = NULL;
+ PyObject *iterable = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t i;
+ static char *kwargs[] = {"iterable", "r", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
+ &iterable, &r))
+ return NULL;
+
+ pool = PySequence_Tuple(iterable);
+ if (pool == NULL)
+ goto error;
+ n = PyTuple_GET_SIZE(pool);
+ if (r < 0) {
+ PyErr_SetString(PyExc_ValueError, "r must be non-negative");
+ goto error;
+ }
+
+ indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ for (i=0 ; i<r ; i++)
+ indices[i] = i;
+
+ /* create combinationsobject structure */
+ co = (combinationsobject *)type->tp_alloc(type, 0);
+ if (co == NULL)
+ goto error;
+
+ co->pool = pool;
+ co->indices = indices;
+ co->result = NULL;
+ co->r = r;
+ co->stopped = r > n ? 1 : 0;
+
+ return (PyObject *)co;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- Py_XDECREF(pool);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ Py_XDECREF(pool);
+ return NULL;
}
static void
combinations_dealloc(combinationsobject *co)
{
- PyObject_GC_UnTrack(co);
- Py_XDECREF(co->pool);
- Py_XDECREF(co->result);
- if (co->indices != NULL)
- PyMem_Free(co->indices);
- Py_TYPE(co)->tp_free(co);
+ PyObject_GC_UnTrack(co);
+ Py_XDECREF(co->pool);
+ Py_XDECREF(co->result);
+ if (co->indices != NULL)
+ PyMem_Free(co->indices);
+ Py_TYPE(co)->tp_free(co);
}
static int
combinations_traverse(combinationsobject *co, visitproc visit, void *arg)
{
- Py_VISIT(co->pool);
- Py_VISIT(co->result);
- return 0;
+ Py_VISIT(co->pool);
+ Py_VISIT(co->result);
+ return 0;
}
static PyObject *
combinations_next(combinationsobject *co)
{
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pool = co->pool;
- Py_ssize_t *indices = co->indices;
- PyObject *result = co->result;
- Py_ssize_t n = PyTuple_GET_SIZE(pool);
- Py_ssize_t r = co->r;
- Py_ssize_t i, j, index;
-
- if (co->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, initialize result tuple using the indices */
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place
- * CPython's empty tuple is a singleton and cached in
- * PyTuple's freelist.
- */
- assert(r == 0 || Py_REFCNT(result) == 1);
-
- /* Scan indices right-to-left until finding one that is not
- at its maximum (i + n - r). */
- for (i=r-1 ; i >= 0 && indices[i] == i+n-r ; i--)
- ;
-
- /* If i is negative, then the indices are all at
- their maximum value and we're done. */
- if (i < 0)
- goto empty;
-
- /* Increment the current index which we know is not at its
- maximum. Then move back to the right setting each index
- to its lowest possible value (one higher than the index
- to its left -- this maintains the sort order invariant). */
- indices[i]++;
- for (j=i+1 ; j<r ; j++)
- indices[j] = indices[j-1] + 1;
-
- /* Update the result tuple for the new indices
- starting with i, the leftmost index that changed */
- for ( ; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- }
- }
-
- Py_INCREF(result);
- return result;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pool = co->pool;
+ Py_ssize_t *indices = co->indices;
+ PyObject *result = co->result;
+ Py_ssize_t n = PyTuple_GET_SIZE(pool);
+ Py_ssize_t r = co->r;
+ Py_ssize_t i, j, index;
+
+ if (co->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, initialize result tuple using the indices */
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place
+ * CPython's empty tuple is a singleton and cached in
+ * PyTuple's freelist.
+ */
+ assert(r == 0 || Py_REFCNT(result) == 1);
+
+ /* Scan indices right-to-left until finding one that is not
+ at its maximum (i + n - r). */
+ for (i=r-1 ; i >= 0 && indices[i] == i+n-r ; i--)
+ ;
+
+ /* If i is negative, then the indices are all at
+ their maximum value and we're done. */
+ if (i < 0)
+ goto empty;
+
+ /* Increment the current index which we know is not at its
+ maximum. Then move back to the right setting each index
+ to its lowest possible value (one higher than the index
+ to its left -- this maintains the sort order invariant). */
+ indices[i]++;
+ for (j=i+1 ; j<r ; j++)
+ indices[j] = indices[j-1] + 1;
+
+ /* Update the result tuple for the new indices
+ starting with i, the leftmost index that changed */
+ for ( ; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ }
+ }
+
+ Py_INCREF(result);
+ return result;
empty:
- co->stopped = 1;
- return NULL;
+ co->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(combinations_doc,
@@ -2023,47 +2023,47 @@ Return successive r-length combinations of elements in the iterable.\n\n\
combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)");
static PyTypeObject combinations_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.combinations", /* tp_name */
- sizeof(combinationsobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)combinations_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- combinations_doc, /* tp_doc */
- (traverseproc)combinations_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)combinations_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- combinations_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.combinations", /* tp_name */
+ sizeof(combinationsobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)combinations_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ combinations_doc, /* tp_doc */
+ (traverseproc)combinations_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)combinations_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ combinations_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -2071,37 +2071,37 @@ static PyTypeObject combinations_type = {
/* Equivalent to:
- def combinations_with_replacement(iterable, r):
- "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
- # number items returned: (n+r-1)! / r! / (n-1)!
- pool = tuple(iterable)
- n = len(pool)
- indices = [0] * r
- yield tuple(pool[i] for i in indices)
- while 1:
- for i in reversed(range(r)):
- if indices[i] != n - 1:
- break
- else:
- return
- indices[i:] = [indices[i] + 1] * (r - i)
- yield tuple(pool[i] for i in indices)
-
- def combinations_with_replacement2(iterable, r):
- 'Alternate version that filters from product()'
- pool = tuple(iterable)
- n = len(pool)
- for indices in product(range(n), repeat=r):
- if sorted(indices) == list(indices):
- yield tuple(pool[i] for i in indices)
+ def combinations_with_replacement(iterable, r):
+ "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
+ # number items returned: (n+r-1)! / r! / (n-1)!
+ pool = tuple(iterable)
+ n = len(pool)
+ indices = [0] * r
+ yield tuple(pool[i] for i in indices)
+ while 1:
+ for i in reversed(range(r)):
+ if indices[i] != n - 1:
+ break
+ else:
+ return
+ indices[i:] = [indices[i] + 1] * (r - i)
+ yield tuple(pool[i] for i in indices)
+
+ def combinations_with_replacement2(iterable, r):
+ 'Alternate version that filters from product()'
+ pool = tuple(iterable)
+ n = len(pool)
+ for indices in product(range(n), repeat=r):
+ if sorted(indices) == list(indices):
+ yield tuple(pool[i] for i in indices)
*/
typedef struct {
- PyObject_HEAD
- PyObject *pool; /* input converted to a tuple */
- Py_ssize_t *indices; /* one index per result element */
- PyObject *result; /* most recently returned result tuple */
- Py_ssize_t r; /* size of result tuple */
- int stopped; /* set to 1 when the cwr iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pool; /* input converted to a tuple */
+ Py_ssize_t *indices; /* one index per result element */
+ PyObject *result; /* most recently returned result tuple */
+ Py_ssize_t r; /* size of result tuple */
+ int stopped; /* set to 1 when the cwr iterator is exhausted */
} cwrobject;
static PyTypeObject cwr_type;
@@ -2109,156 +2109,156 @@ static PyTypeObject cwr_type;
static PyObject *
cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- cwrobject *co;
- Py_ssize_t n;
- Py_ssize_t r;
- PyObject *pool = NULL;
- PyObject *iterable = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t i;
- static char *kwargs[] = {"iterable", "r", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs,
- &iterable, &r))
- return NULL;
-
- pool = PySequence_Tuple(iterable);
- if (pool == NULL)
- goto error;
- n = PyTuple_GET_SIZE(pool);
- if (r < 0) {
- PyErr_SetString(PyExc_ValueError, "r must be non-negative");
- goto error;
- }
-
- indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
- if (indices == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- for (i=0 ; i<r ; i++)
- indices[i] = 0;
-
- /* create cwrobject structure */
- co = (cwrobject *)type->tp_alloc(type, 0);
- if (co == NULL)
- goto error;
-
- co->pool = pool;
- co->indices = indices;
- co->result = NULL;
- co->r = r;
- co->stopped = !n && r;
-
- return (PyObject *)co;
+ cwrobject *co;
+ Py_ssize_t n;
+ Py_ssize_t r;
+ PyObject *pool = NULL;
+ PyObject *iterable = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t i;
+ static char *kwargs[] = {"iterable", "r", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs,
+ &iterable, &r))
+ return NULL;
+
+ pool = PySequence_Tuple(iterable);
+ if (pool == NULL)
+ goto error;
+ n = PyTuple_GET_SIZE(pool);
+ if (r < 0) {
+ PyErr_SetString(PyExc_ValueError, "r must be non-negative");
+ goto error;
+ }
+
+ indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ for (i=0 ; i<r ; i++)
+ indices[i] = 0;
+
+ /* create cwrobject structure */
+ co = (cwrobject *)type->tp_alloc(type, 0);
+ if (co == NULL)
+ goto error;
+
+ co->pool = pool;
+ co->indices = indices;
+ co->result = NULL;
+ co->r = r;
+ co->stopped = !n && r;
+
+ return (PyObject *)co;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- Py_XDECREF(pool);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ Py_XDECREF(pool);
+ return NULL;
}
static void
cwr_dealloc(cwrobject *co)
{
- PyObject_GC_UnTrack(co);
- Py_XDECREF(co->pool);
- Py_XDECREF(co->result);
- if (co->indices != NULL)
- PyMem_Free(co->indices);
- Py_TYPE(co)->tp_free(co);
+ PyObject_GC_UnTrack(co);
+ Py_XDECREF(co->pool);
+ Py_XDECREF(co->result);
+ if (co->indices != NULL)
+ PyMem_Free(co->indices);
+ Py_TYPE(co)->tp_free(co);
}
static int
cwr_traverse(cwrobject *co, visitproc visit, void *arg)
{
- Py_VISIT(co->pool);
- Py_VISIT(co->result);
- return 0;
+ Py_VISIT(co->pool);
+ Py_VISIT(co->result);
+ return 0;
}
static PyObject *
cwr_next(cwrobject *co)
{
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pool = co->pool;
- Py_ssize_t *indices = co->indices;
- PyObject *result = co->result;
- Py_ssize_t n = PyTuple_GET_SIZE(pool);
- Py_ssize_t r = co->r;
- Py_ssize_t i, j, index;
-
- if (co->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, initialize result tuple using the indices */
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place CPython's
- empty tuple is a singleton and cached in PyTuple's freelist. */
- assert(r == 0 || Py_REFCNT(result) == 1);
-
- /* Scan indices right-to-left until finding one that is not
- * at its maximum (n-1). */
- for (i=r-1 ; i >= 0 && indices[i] == n-1; i--)
- ;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pool = co->pool;
+ Py_ssize_t *indices = co->indices;
+ PyObject *result = co->result;
+ Py_ssize_t n = PyTuple_GET_SIZE(pool);
+ Py_ssize_t r = co->r;
+ Py_ssize_t i, j, index;
+
+ if (co->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, initialize result tuple using the indices */
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place CPython's
+ empty tuple is a singleton and cached in PyTuple's freelist. */
+ assert(r == 0 || Py_REFCNT(result) == 1);
+
+ /* Scan indices right-to-left until finding one that is not
+ * at its maximum (n-1). */
+ for (i=r-1 ; i >= 0 && indices[i] == n-1; i--)
+ ;
+
+ /* If i is negative, then the indices are all at
+ their maximum value and we're done. */
+ if (i < 0)
+ goto empty;
+
+ /* Increment the current index which we know is not at its
+ maximum. Then set all to the right to the same value. */
+ indices[i]++;
+ for (j=i+1 ; j<r ; j++)
+ indices[j] = indices[j-1];
+
+ /* Update the result tuple for the new indices
+ starting with i, the leftmost index that changed */
+ for ( ; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ }
+ }
- /* If i is negative, then the indices are all at
- their maximum value and we're done. */
- if (i < 0)
- goto empty;
-
- /* Increment the current index which we know is not at its
- maximum. Then set all to the right to the same value. */
- indices[i]++;
- for (j=i+1 ; j<r ; j++)
- indices[j] = indices[j-1];
-
- /* Update the result tuple for the new indices
- starting with i, the leftmost index that changed */
- for ( ; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- }
- }
-
- Py_INCREF(result);
- return result;
+ Py_INCREF(result);
+ return result;
empty:
- co->stopped = 1;
- return NULL;
+ co->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(cwr_doc,
@@ -2269,52 +2269,52 @@ allowing individual elements to have successive repeats.\n\
combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC");
static PyTypeObject cwr_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.combinations_with_replacement", /* tp_name */
- sizeof(cwrobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)cwr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- cwr_doc, /* tp_doc */
- (traverseproc)cwr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)cwr_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- cwr_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.combinations_with_replacement", /* tp_name */
+ sizeof(cwrobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)cwr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ cwr_doc, /* tp_doc */
+ (traverseproc)cwr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)cwr_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ cwr_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* permutations object ************************************************************
-
+
def permutations(iterable, r=None):
'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)'
pool = tuple(iterable)
@@ -2324,28 +2324,28 @@ def permutations(iterable, r=None):
cycles = range(n-r+1, n+1)[::-1]
yield tuple(pool[i] for i in indices[:r])
while n:
- for i in reversed(range(r)):
- cycles[i] -= 1
- if cycles[i] == 0:
- indices[i:] = indices[i+1:] + indices[i:i+1]
- cycles[i] = n - i
- else:
- j = cycles[i]
- indices[i], indices[-j] = indices[-j], indices[i]
- yield tuple(pool[i] for i in indices[:r])
- break
+ for i in reversed(range(r)):
+ cycles[i] -= 1
+ if cycles[i] == 0:
+ indices[i:] = indices[i+1:] + indices[i:i+1]
+ cycles[i] = n - i
else:
- return
+ j = cycles[i]
+ indices[i], indices[-j] = indices[-j], indices[i]
+ yield tuple(pool[i] for i in indices[:r])
+ break
+ else:
+ return
*/
typedef struct {
- PyObject_HEAD
- PyObject *pool; /* input converted to a tuple */
- Py_ssize_t *indices; /* one index per element in the pool */
- Py_ssize_t *cycles; /* one rollover counter per element in the result */
- PyObject *result; /* most recently returned result tuple */
- Py_ssize_t r; /* size of result tuple */
- int stopped; /* set to 1 when the permutations iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pool; /* input converted to a tuple */
+ Py_ssize_t *indices; /* one index per element in the pool */
+ Py_ssize_t *cycles; /* one rollover counter per element in the result */
+ PyObject *result; /* most recently returned result tuple */
+ Py_ssize_t r; /* size of result tuple */
+ int stopped; /* set to 1 when the permutations iterator is exhausted */
} permutationsobject;
static PyTypeObject permutations_type;
@@ -2353,184 +2353,184 @@ static PyTypeObject permutations_type;
static PyObject *
permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- permutationsobject *po;
- Py_ssize_t n;
- Py_ssize_t r;
- PyObject *robj = Py_None;
- PyObject *pool = NULL;
- PyObject *iterable = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t *cycles = NULL;
- Py_ssize_t i;
- static char *kwargs[] = {"iterable", "r", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs,
- &iterable, &robj))
- return NULL;
-
- pool = PySequence_Tuple(iterable);
- if (pool == NULL)
- goto error;
- n = PyTuple_GET_SIZE(pool);
-
- r = n;
- if (robj != Py_None) {
- if (!PyLong_Check(robj)) {
- PyErr_SetString(PyExc_TypeError, "Expected int as r");
- goto error;
- }
- r = PyLong_AsSsize_t(robj);
- if (r == -1 && PyErr_Occurred())
- goto error;
- }
- if (r < 0) {
- PyErr_SetString(PyExc_ValueError, "r must be non-negative");
- goto error;
- }
-
- indices = PyMem_Malloc(n * sizeof(Py_ssize_t));
- cycles = PyMem_Malloc(r * sizeof(Py_ssize_t));
- if (indices == NULL || cycles == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- for (i=0 ; i<n ; i++)
- indices[i] = i;
- for (i=0 ; i<r ; i++)
- cycles[i] = n - i;
-
- /* create permutationsobject structure */
- po = (permutationsobject *)type->tp_alloc(type, 0);
- if (po == NULL)
- goto error;
-
- po->pool = pool;
- po->indices = indices;
- po->cycles = cycles;
- po->result = NULL;
- po->r = r;
- po->stopped = r > n ? 1 : 0;
-
- return (PyObject *)po;
+ permutationsobject *po;
+ Py_ssize_t n;
+ Py_ssize_t r;
+ PyObject *robj = Py_None;
+ PyObject *pool = NULL;
+ PyObject *iterable = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t *cycles = NULL;
+ Py_ssize_t i;
+ static char *kwargs[] = {"iterable", "r", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs,
+ &iterable, &robj))
+ return NULL;
+
+ pool = PySequence_Tuple(iterable);
+ if (pool == NULL)
+ goto error;
+ n = PyTuple_GET_SIZE(pool);
+
+ r = n;
+ if (robj != Py_None) {
+ if (!PyLong_Check(robj)) {
+ PyErr_SetString(PyExc_TypeError, "Expected int as r");
+ goto error;
+ }
+ r = PyLong_AsSsize_t(robj);
+ if (r == -1 && PyErr_Occurred())
+ goto error;
+ }
+ if (r < 0) {
+ PyErr_SetString(PyExc_ValueError, "r must be non-negative");
+ goto error;
+ }
+
+ indices = PyMem_Malloc(n * sizeof(Py_ssize_t));
+ cycles = PyMem_Malloc(r * sizeof(Py_ssize_t));
+ if (indices == NULL || cycles == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ for (i=0 ; i<n ; i++)
+ indices[i] = i;
+ for (i=0 ; i<r ; i++)
+ cycles[i] = n - i;
+
+ /* create permutationsobject structure */
+ po = (permutationsobject *)type->tp_alloc(type, 0);
+ if (po == NULL)
+ goto error;
+
+ po->pool = pool;
+ po->indices = indices;
+ po->cycles = cycles;
+ po->result = NULL;
+ po->r = r;
+ po->stopped = r > n ? 1 : 0;
+
+ return (PyObject *)po;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- if (cycles != NULL)
- PyMem_Free(cycles);
- Py_XDECREF(pool);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ if (cycles != NULL)
+ PyMem_Free(cycles);
+ Py_XDECREF(pool);
+ return NULL;
}
static void
permutations_dealloc(permutationsobject *po)
{
- PyObject_GC_UnTrack(po);
- Py_XDECREF(po->pool);
- Py_XDECREF(po->result);
- PyMem_Free(po->indices);
- PyMem_Free(po->cycles);
- Py_TYPE(po)->tp_free(po);
+ PyObject_GC_UnTrack(po);
+ Py_XDECREF(po->pool);
+ Py_XDECREF(po->result);
+ PyMem_Free(po->indices);
+ PyMem_Free(po->cycles);
+ Py_TYPE(po)->tp_free(po);
}
static int
permutations_traverse(permutationsobject *po, visitproc visit, void *arg)
{
- Py_VISIT(po->pool);
- Py_VISIT(po->result);
- return 0;
+ Py_VISIT(po->pool);
+ Py_VISIT(po->result);
+ return 0;
}
static PyObject *
permutations_next(permutationsobject *po)
{
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pool = po->pool;
- Py_ssize_t *indices = po->indices;
- Py_ssize_t *cycles = po->cycles;
- PyObject *result = po->result;
- Py_ssize_t n = PyTuple_GET_SIZE(pool);
- Py_ssize_t r = po->r;
- Py_ssize_t i, j, k, index;
-
- if (po->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, initialize result tuple using the indices */
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- po->result = result;
- for (i=0; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- if (n == 0)
- goto empty;
-
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- po->result = result;
- for (i=0; i<r ; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place */
- assert(r == 0 || Py_REFCNT(result) == 1);
-
- /* Decrement rightmost cycle, moving leftward upon zero rollover */
- for (i=r-1 ; i>=0 ; i--) {
- cycles[i] -= 1;
- if (cycles[i] == 0) {
- /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */
- index = indices[i];
- for (j=i ; j<n-1 ; j++)
- indices[j] = indices[j+1];
- indices[n-1] = index;
- cycles[i] = n - i;
- } else {
- j = cycles[i];
- index = indices[i];
- indices[i] = indices[n-j];
- indices[n-j] = index;
-
- for (k=i; k<r ; k++) {
- /* start with i, the leftmost element that changed */
- /* yield tuple(pool[k] for k in indices[:r]) */
- index = indices[k];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, k);
- PyTuple_SET_ITEM(result, k, elem);
- Py_DECREF(oldelem);
- }
- break;
- }
- }
- /* If i is negative, then the cycles have all
- rolled-over and we're done. */
- if (i < 0)
- goto empty;
- }
- Py_INCREF(result);
- return result;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pool = po->pool;
+ Py_ssize_t *indices = po->indices;
+ Py_ssize_t *cycles = po->cycles;
+ PyObject *result = po->result;
+ Py_ssize_t n = PyTuple_GET_SIZE(pool);
+ Py_ssize_t r = po->r;
+ Py_ssize_t i, j, k, index;
+
+ if (po->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, initialize result tuple using the indices */
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ po->result = result;
+ for (i=0; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ if (n == 0)
+ goto empty;
+
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ po->result = result;
+ for (i=0; i<r ; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place */
+ assert(r == 0 || Py_REFCNT(result) == 1);
+
+ /* Decrement rightmost cycle, moving leftward upon zero rollover */
+ for (i=r-1 ; i>=0 ; i--) {
+ cycles[i] -= 1;
+ if (cycles[i] == 0) {
+ /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */
+ index = indices[i];
+ for (j=i ; j<n-1 ; j++)
+ indices[j] = indices[j+1];
+ indices[n-1] = index;
+ cycles[i] = n - i;
+ } else {
+ j = cycles[i];
+ index = indices[i];
+ indices[i] = indices[n-j];
+ indices[n-j] = index;
+
+ for (k=i; k<r ; k++) {
+ /* start with i, the leftmost element that changed */
+ /* yield tuple(pool[k] for k in indices[:r]) */
+ index = indices[k];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, k);
+ PyTuple_SET_ITEM(result, k, elem);
+ Py_DECREF(oldelem);
+ }
+ break;
+ }
+ }
+ /* If i is negative, then the cycles have all
+ rolled-over and we're done. */
+ if (i < 0)
+ goto empty;
+ }
+ Py_INCREF(result);
+ return result;
empty:
- po->stopped = 1;
- return NULL;
+ po->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(permutations_doc,
@@ -2540,47 +2540,47 @@ Return successive r-length permutations of elements in the iterable.\n\n\
permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)");
static PyTypeObject permutations_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.permutations", /* tp_name */
- sizeof(permutationsobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)permutations_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- permutations_doc, /* tp_doc */
- (traverseproc)permutations_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)permutations_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- permutations_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.permutations", /* tp_name */
+ sizeof(permutationsobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)permutations_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ permutations_doc, /* tp_doc */
+ (traverseproc)permutations_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)permutations_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ permutations_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -2588,15 +2588,15 @@ static PyTypeObject permutations_type = {
/* Equivalent to:
- def compress(data, selectors):
- "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
- return (d for d, s in zip(data, selectors) if s)
+ def compress(data, selectors):
+ "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
+ return (d for d, s in zip(data, selectors) if s)
*/
typedef struct {
- PyObject_HEAD
- PyObject *data;
- PyObject *selectors;
+ PyObject_HEAD
+ PyObject *data;
+ PyObject *selectors;
} compressobject;
static PyTypeObject compress_type;
@@ -2604,86 +2604,86 @@ static PyTypeObject compress_type;
static PyObject *
compress_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *seq1, *seq2;
- PyObject *data=NULL, *selectors=NULL;
- compressobject *lz;
- static char *kwargs[] = {"data", "selectors", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2))
- return NULL;
-
- data = PyObject_GetIter(seq1);
- if (data == NULL)
- goto fail;
- selectors = PyObject_GetIter(seq2);
- if (selectors == NULL)
- goto fail;
-
- /* create compressobject structure */
- lz = (compressobject *)type->tp_alloc(type, 0);
- if (lz == NULL)
- goto fail;
- lz->data = data;
- lz->selectors = selectors;
- return (PyObject *)lz;
+ PyObject *seq1, *seq2;
+ PyObject *data=NULL, *selectors=NULL;
+ compressobject *lz;
+ static char *kwargs[] = {"data", "selectors", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2))
+ return NULL;
+
+ data = PyObject_GetIter(seq1);
+ if (data == NULL)
+ goto fail;
+ selectors = PyObject_GetIter(seq2);
+ if (selectors == NULL)
+ goto fail;
+
+ /* create compressobject structure */
+ lz = (compressobject *)type->tp_alloc(type, 0);
+ if (lz == NULL)
+ goto fail;
+ lz->data = data;
+ lz->selectors = selectors;
+ return (PyObject *)lz;
fail:
- Py_XDECREF(data);
- Py_XDECREF(selectors);
- return NULL;
+ Py_XDECREF(data);
+ Py_XDECREF(selectors);
+ return NULL;
}
static void
compress_dealloc(compressobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->data);
- Py_XDECREF(lz->selectors);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->data);
+ Py_XDECREF(lz->selectors);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
compress_traverse(compressobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->data);
- Py_VISIT(lz->selectors);
- return 0;
+ Py_VISIT(lz->data);
+ Py_VISIT(lz->selectors);
+ return 0;
}
static PyObject *
compress_next(compressobject *lz)
{
- PyObject *data = lz->data, *selectors = lz->selectors;
- PyObject *datum, *selector;
- PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext;
- PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext;
- int ok;
-
- while (1) {
- /* Steps: get datum, get selector, evaluate selector.
- Order is important (to match the pure python version
- in terms of which input gets a chance to raise an
- exception first).
- */
-
- datum = datanext(data);
- if (datum == NULL)
- return NULL;
-
- selector = selectornext(selectors);
- if (selector == NULL) {
- Py_DECREF(datum);
- return NULL;
- }
-
- ok = PyObject_IsTrue(selector);
- Py_DECREF(selector);
- if (ok == 1)
- return datum;
- Py_DECREF(datum);
- if (ok == -1)
- return NULL;
- }
+ PyObject *data = lz->data, *selectors = lz->selectors;
+ PyObject *datum, *selector;
+ PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext;
+ PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext;
+ int ok;
+
+ while (1) {
+ /* Steps: get datum, get selector, evaluate selector.
+ Order is important (to match the pure python version
+ in terms of which input gets a chance to raise an
+ exception first).
+ */
+
+ datum = datanext(data);
+ if (datum == NULL)
+ return NULL;
+
+ selector = selectornext(selectors);
+ if (selector == NULL) {
+ Py_DECREF(datum);
+ return NULL;
+ }
+
+ ok = PyObject_IsTrue(selector);
+ Py_DECREF(selector);
+ if (ok == 1)
+ return datum;
+ Py_DECREF(datum);
+ if (ok == -1)
+ return NULL;
+ }
}
PyDoc_STRVAR(compress_doc,
@@ -2694,56 +2694,56 @@ Forms a shorter iterator from selected data elements using the\n\
selectors to choose the data elements.");
static PyTypeObject compress_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.compress", /* tp_name */
- sizeof(compressobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)compress_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- compress_doc, /* tp_doc */
- (traverseproc)compress_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)compress_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- compress_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.compress", /* tp_name */
+ sizeof(compressobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)compress_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ compress_doc, /* tp_doc */
+ (traverseproc)compress_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)compress_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ compress_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* filterfalse object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} filterfalseobject;
static PyTypeObject filterfalse_type;
@@ -2751,83 +2751,83 @@ static PyTypeObject filterfalse_type;
static PyObject *
filterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- filterfalseobject *lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ filterfalseobject *lz;
- if (type == &filterfalse_type &&
- !_PyArg_NoKeywords("filterfalse()", kwds))
- return NULL;
+ if (type == &filterfalse_type &&
+ !_PyArg_NoKeywords("filterfalse()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq))
+ return NULL;
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
- /* create filterfalseobject structure */
- lz = (filterfalseobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
+ /* create filterfalseobject structure */
+ lz = (filterfalseobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
- return (PyObject *)lz;
+ return (PyObject *)lz;
}
static void
filterfalse_dealloc(filterfalseobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
filterfalse_traverse(filterfalseobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
filterfalse_next(filterfalseobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
-
- if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
- ok = PyObject_IsTrue(item);
- } else {
- PyObject *good;
- good = PyObject_CallFunctionObjArgs(lz->func,
- item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- }
- if (!ok)
- return item;
- Py_DECREF(item);
- }
+ PyObject *item;
+ PyObject *it = lz->it;
+ long ok;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+
+ if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
+ ok = PyObject_IsTrue(item);
+ } else {
+ PyObject *good;
+ good = PyObject_CallFunctionObjArgs(lz->func,
+ item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ }
+ if (!ok)
+ return item;
+ Py_DECREF(item);
+ }
}
PyDoc_STRVAR(filterfalse_doc,
@@ -2837,74 +2837,74 @@ Return those items of sequence for which function(item) is false.\n\
If function is None, return the items that are false.");
static PyTypeObject filterfalse_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.filterfalse", /* tp_name */
- sizeof(filterfalseobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)filterfalse_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- filterfalse_doc, /* tp_doc */
- (traverseproc)filterfalse_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)filterfalse_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- filterfalse_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.filterfalse", /* tp_name */
+ sizeof(filterfalseobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)filterfalse_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ filterfalse_doc, /* tp_doc */
+ (traverseproc)filterfalse_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)filterfalse_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ filterfalse_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* count object ************************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t cnt;
- PyObject *long_cnt;
- PyObject *long_step;
+ PyObject_HEAD
+ Py_ssize_t cnt;
+ PyObject *long_cnt;
+ PyObject *long_step;
} countobject;
/* Counting logic and invariants:
fast_mode: when cnt an integer < PY_SSIZE_T_MAX and no step is specified.
- assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1));
- Advances with: cnt += 1
- When count hits Y_SSIZE_T_MAX, switch to slow_mode.
+ assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1));
+ Advances with: cnt += 1
+ When count hits Y_SSIZE_T_MAX, switch to slow_mode.
slow_mode: when cnt == PY_SSIZE_T_MAX, step is not int(1), or cnt is a float.
- assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL);
- All counting is done with python objects (no overflows or underflows).
- Advances with: long_cnt += long_step
- Step may be zero -- effectively a slow version of repeat(cnt).
- Either long_cnt or long_step may be a float, Fraction, or Decimal.
+ assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL);
+ All counting is done with python objects (no overflows or underflows).
+ Advances with: long_cnt += long_step
+ Step may be zero -- effectively a slow version of repeat(cnt).
+ Either long_cnt or long_step may be a float, Fraction, or Decimal.
*/
static PyTypeObject count_type;
@@ -2912,221 +2912,221 @@ static PyTypeObject count_type;
static PyObject *
count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- countobject *lz;
- int slow_mode = 0;
- Py_ssize_t cnt = 0;
- PyObject *long_cnt = NULL;
- PyObject *long_step = NULL;
- static char *kwlist[] = {"start", "step", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count",
- kwlist, &long_cnt, &long_step))
- return NULL;
-
- if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) ||
- (long_step != NULL && !PyNumber_Check(long_step))) {
- PyErr_SetString(PyExc_TypeError, "a number is required");
- return NULL;
- }
-
- if (long_cnt != NULL) {
- cnt = PyLong_AsSsize_t(long_cnt);
- if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) {
- PyErr_Clear();
- slow_mode = 1;
- }
- Py_INCREF(long_cnt);
- } else {
- cnt = 0;
- long_cnt = PyLong_FromLong(0);
- }
-
- /* If not specified, step defaults to 1 */
- if (long_step == NULL) {
- long_step = PyLong_FromLong(1);
- if (long_step == NULL) {
- Py_DECREF(long_cnt);
- return NULL;
- }
- } else
- Py_INCREF(long_step);
-
- assert(long_cnt != NULL && long_step != NULL);
-
- /* Fast mode only works when the step is 1 */
- if (!PyLong_Check(long_step) ||
- PyLong_AS_LONG(long_step) != 1) {
- slow_mode = 1;
- }
-
- if (slow_mode)
- cnt = PY_SSIZE_T_MAX;
- else
- Py_CLEAR(long_cnt);
-
- assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) ||
- (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode));
- assert(slow_mode ||
- (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1));
-
- /* create countobject structure */
- lz = (countobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_XDECREF(long_cnt);
- return NULL;
- }
- lz->cnt = cnt;
- lz->long_cnt = long_cnt;
- lz->long_step = long_step;
-
- return (PyObject *)lz;
+ countobject *lz;
+ int slow_mode = 0;
+ Py_ssize_t cnt = 0;
+ PyObject *long_cnt = NULL;
+ PyObject *long_step = NULL;
+ static char *kwlist[] = {"start", "step", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count",
+ kwlist, &long_cnt, &long_step))
+ return NULL;
+
+ if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) ||
+ (long_step != NULL && !PyNumber_Check(long_step))) {
+ PyErr_SetString(PyExc_TypeError, "a number is required");
+ return NULL;
+ }
+
+ if (long_cnt != NULL) {
+ cnt = PyLong_AsSsize_t(long_cnt);
+ if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) {
+ PyErr_Clear();
+ slow_mode = 1;
+ }
+ Py_INCREF(long_cnt);
+ } else {
+ cnt = 0;
+ long_cnt = PyLong_FromLong(0);
+ }
+
+ /* If not specified, step defaults to 1 */
+ if (long_step == NULL) {
+ long_step = PyLong_FromLong(1);
+ if (long_step == NULL) {
+ Py_DECREF(long_cnt);
+ return NULL;
+ }
+ } else
+ Py_INCREF(long_step);
+
+ assert(long_cnt != NULL && long_step != NULL);
+
+ /* Fast mode only works when the step is 1 */
+ if (!PyLong_Check(long_step) ||
+ PyLong_AS_LONG(long_step) != 1) {
+ slow_mode = 1;
+ }
+
+ if (slow_mode)
+ cnt = PY_SSIZE_T_MAX;
+ else
+ Py_CLEAR(long_cnt);
+
+ assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) ||
+ (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode));
+ assert(slow_mode ||
+ (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1));
+
+ /* create countobject structure */
+ lz = (countobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_XDECREF(long_cnt);
+ return NULL;
+ }
+ lz->cnt = cnt;
+ lz->long_cnt = long_cnt;
+ lz->long_step = long_step;
+
+ return (PyObject *)lz;
}
static void
count_dealloc(countobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->long_cnt);
- Py_XDECREF(lz->long_step);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->long_cnt);
+ Py_XDECREF(lz->long_step);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
count_traverse(countobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->long_cnt);
- Py_VISIT(lz->long_step);
- return 0;
+ Py_VISIT(lz->long_cnt);
+ Py_VISIT(lz->long_step);
+ return 0;
}
static PyObject *
count_nextlong(countobject *lz)
{
- PyObject *long_cnt;
- PyObject *stepped_up;
+ PyObject *long_cnt;
+ PyObject *stepped_up;
- long_cnt = lz->long_cnt;
- if (long_cnt == NULL) {
- /* Switch to slow_mode */
- long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX);
- if (long_cnt == NULL)
- return NULL;
- }
- assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL);
+ long_cnt = lz->long_cnt;
+ if (long_cnt == NULL) {
+ /* Switch to slow_mode */
+ long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX);
+ if (long_cnt == NULL)
+ return NULL;
+ }
+ assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL);
- stepped_up = PyNumber_Add(long_cnt, lz->long_step);
- if (stepped_up == NULL)
- return NULL;
- lz->long_cnt = stepped_up;
- return long_cnt;
+ stepped_up = PyNumber_Add(long_cnt, lz->long_step);
+ if (stepped_up == NULL)
+ return NULL;
+ lz->long_cnt = stepped_up;
+ return long_cnt;
}
static PyObject *
count_next(countobject *lz)
{
- if (lz->cnt == PY_SSIZE_T_MAX)
- return count_nextlong(lz);
- return PyLong_FromSsize_t(lz->cnt++);
+ if (lz->cnt == PY_SSIZE_T_MAX)
+ return count_nextlong(lz);
+ return PyLong_FromSsize_t(lz->cnt++);
}
static PyObject *
count_repr(countobject *lz)
{
- if (lz->cnt != PY_SSIZE_T_MAX)
- return PyUnicode_FromFormat("count(%zd)", lz->cnt);
+ if (lz->cnt != PY_SSIZE_T_MAX)
+ return PyUnicode_FromFormat("count(%zd)", lz->cnt);
- if (PyLong_Check(lz->long_step)) {
- long step = PyLong_AsLong(lz->long_step);
- if (step == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- }
- if (step == 1) {
- /* Don't display step when it is an integer equal to 1 */
- return PyUnicode_FromFormat("count(%R)", lz->long_cnt);
- }
- }
- return PyUnicode_FromFormat("count(%R, %R)",
- lz->long_cnt, lz->long_step);
+ if (PyLong_Check(lz->long_step)) {
+ long step = PyLong_AsLong(lz->long_step);
+ if (step == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ }
+ if (step == 1) {
+ /* Don't display step when it is an integer equal to 1 */
+ return PyUnicode_FromFormat("count(%R)", lz->long_cnt);
+ }
+ }
+ return PyUnicode_FromFormat("count(%R, %R)",
+ lz->long_cnt, lz->long_step);
}
static PyObject *
count_reduce(countobject *lz)
{
- if (lz->cnt == PY_SSIZE_T_MAX)
- return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step);
- return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt);
+ if (lz->cnt == PY_SSIZE_T_MAX)
+ return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step);
+ return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt);
}
PyDoc_STRVAR(count_reduce_doc, "Return state information for pickling.");
static PyMethodDef count_methods[] = {
- {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS,
- count_reduce_doc},
- {NULL, NULL} /* sentinel */
+ {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS,
+ count_reduce_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(count_doc,
- "count(start=0, step=1]) --> count object\n\
+ "count(start=0, step=1]) --> count object\n\
\n\
Return a count object whose .__next__() method returns consecutive values.\n\
Equivalent to:\n\n\
def count(firstval=0, step=1):\n\
- x = firstval\n\
- while 1:\n\
- yield x\n\
- x += step\n");
+ x = firstval\n\
+ while 1:\n\
+ yield x\n\
+ x += step\n");
static PyTypeObject count_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.count", /* tp_name */
- sizeof(countobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)count_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)count_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- count_doc, /* tp_doc */
- (traverseproc)count_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)count_next, /* tp_iternext */
- count_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- count_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.count", /* tp_name */
+ sizeof(countobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)count_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)count_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ count_doc, /* tp_doc */
+ (traverseproc)count_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)count_next, /* tp_iternext */
+ count_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ count_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* repeat object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *element;
- Py_ssize_t cnt;
+ PyObject_HEAD
+ PyObject *element;
+ Py_ssize_t cnt;
} repeatobject;
static PyTypeObject repeat_type;
@@ -3134,77 +3134,77 @@ static PyTypeObject repeat_type;
static PyObject *
repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- repeatobject *ro;
- PyObject *element;
- Py_ssize_t cnt = -1;
- static char *kwargs[] = {"object", "times", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs,
- &element, &cnt))
- return NULL;
+ repeatobject *ro;
+ PyObject *element;
+ Py_ssize_t cnt = -1;
+ static char *kwargs[] = {"object", "times", NULL};
- if (PyTuple_Size(args) == 2 && cnt < 0)
- cnt = 0;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs,
+ &element, &cnt))
+ return NULL;
- ro = (repeatobject *)type->tp_alloc(type, 0);
- if (ro == NULL)
- return NULL;
- Py_INCREF(element);
- ro->element = element;
- ro->cnt = cnt;
- return (PyObject *)ro;
+ if (PyTuple_Size(args) == 2 && cnt < 0)
+ cnt = 0;
+
+ ro = (repeatobject *)type->tp_alloc(type, 0);
+ if (ro == NULL)
+ return NULL;
+ Py_INCREF(element);
+ ro->element = element;
+ ro->cnt = cnt;
+ return (PyObject *)ro;
}
static void
repeat_dealloc(repeatobject *ro)
{
- PyObject_GC_UnTrack(ro);
- Py_XDECREF(ro->element);
- Py_TYPE(ro)->tp_free(ro);
+ PyObject_GC_UnTrack(ro);
+ Py_XDECREF(ro->element);
+ Py_TYPE(ro)->tp_free(ro);
}
static int
repeat_traverse(repeatobject *ro, visitproc visit, void *arg)
{
- Py_VISIT(ro->element);
- return 0;
+ Py_VISIT(ro->element);
+ return 0;
}
static PyObject *
repeat_next(repeatobject *ro)
{
- if (ro->cnt == 0)
- return NULL;
- if (ro->cnt > 0)
- ro->cnt--;
- Py_INCREF(ro->element);
- return ro->element;
+ if (ro->cnt == 0)
+ return NULL;
+ if (ro->cnt > 0)
+ ro->cnt--;
+ Py_INCREF(ro->element);
+ return ro->element;
}
static PyObject *
repeat_repr(repeatobject *ro)
{
- if (ro->cnt == -1)
- return PyUnicode_FromFormat("repeat(%R)", ro->element);
- else
- return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt);
-}
+ if (ro->cnt == -1)
+ return PyUnicode_FromFormat("repeat(%R)", ro->element);
+ else
+ return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt);
+}
static PyObject *
repeat_len(repeatobject *ro)
{
- if (ro->cnt == -1) {
- PyErr_SetString(PyExc_TypeError, "len() of unsized object");
- return NULL;
- }
- return PyLong_FromSize_t(ro->cnt);
+ if (ro->cnt == -1) {
+ PyErr_SetString(PyExc_TypeError, "len() of unsized object");
+ return NULL;
+ }
+ return PyLong_FromSize_t(ro->cnt);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef repeat_methods[] = {
- {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(repeat_doc,
@@ -3213,47 +3213,47 @@ for the specified number of times. If not specified, returns the object\n\
endlessly.");
static PyTypeObject repeat_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.repeat", /* tp_name */
- sizeof(repeatobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)repeat_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)repeat_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- repeat_doc, /* tp_doc */
- (traverseproc)repeat_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)repeat_next, /* tp_iternext */
- repeat_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- repeat_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.repeat", /* tp_name */
+ sizeof(repeatobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)repeat_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)repeat_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ repeat_doc, /* tp_doc */
+ (traverseproc)repeat_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)repeat_next, /* tp_iternext */
+ repeat_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ repeat_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* ziplongest object ************************************************************/
@@ -3261,12 +3261,12 @@ static PyTypeObject repeat_type = {
#include "Python.h"
typedef struct {
- PyObject_HEAD
- Py_ssize_t tuplesize;
- Py_ssize_t numactive;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
- PyObject *fillvalue;
+ PyObject_HEAD
+ Py_ssize_t tuplesize;
+ Py_ssize_t numactive;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ PyObject *fillvalue;
} ziplongestobject;
static PyTypeObject ziplongest_type;
@@ -3274,159 +3274,159 @@ static PyTypeObject ziplongest_type;
static PyObject *
zip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- ziplongestobject *lz;
- Py_ssize_t i;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
- PyObject *fillvalue = Py_None;
- Py_ssize_t tuplesize = PySequence_Length(args);
-
- if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) {
- fillvalue = PyDict_GetItemString(kwds, "fillvalue");
- if (fillvalue == NULL || PyDict_Size(kwds) > 1) {
- PyErr_SetString(PyExc_TypeError,
- "zip_longest() got an unexpected keyword argument");
- return NULL;
- }
+ ziplongestobject *lz;
+ Py_ssize_t i;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ PyObject *fillvalue = Py_None;
+ Py_ssize_t tuplesize = PySequence_Length(args);
+
+ if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) {
+ fillvalue = PyDict_GetItemString(kwds, "fillvalue");
+ if (fillvalue == NULL || PyDict_Size(kwds) > 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "zip_longest() got an unexpected keyword argument");
+ return NULL;
}
-
- /* args must be a tuple */
- assert(PyTuple_Check(args));
-
- /* obtain iterators */
- ittuple = PyTuple_New(tuplesize);
- if (ittuple == NULL)
- return NULL;
- for (i=0; i < tuplesize; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- PyObject *it = PyObject_GetIter(item);
- if (it == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_Format(PyExc_TypeError,
- "zip_longest argument #%zd must support iteration",
- i+1);
- Py_DECREF(ittuple);
- return NULL;
- }
- PyTuple_SET_ITEM(ittuple, i, it);
- }
-
- /* create a result holder */
- result = PyTuple_New(tuplesize);
- if (result == NULL) {
- Py_DECREF(ittuple);
- return NULL;
- }
- for (i=0 ; i < tuplesize ; i++) {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(result, i, Py_None);
- }
-
- /* create ziplongestobject structure */
- lz = (ziplongestobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(ittuple);
- Py_DECREF(result);
- return NULL;
- }
- lz->ittuple = ittuple;
- lz->tuplesize = tuplesize;
- lz->numactive = tuplesize;
- lz->result = result;
- Py_INCREF(fillvalue);
- lz->fillvalue = fillvalue;
- return (PyObject *)lz;
+ }
+
+ /* args must be a tuple */
+ assert(PyTuple_Check(args));
+
+ /* obtain iterators */
+ ittuple = PyTuple_New(tuplesize);
+ if (ittuple == NULL)
+ return NULL;
+ for (i=0; i < tuplesize; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *it = PyObject_GetIter(item);
+ if (it == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_Format(PyExc_TypeError,
+ "zip_longest argument #%zd must support iteration",
+ i+1);
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(ittuple, i, it);
+ }
+
+ /* create a result holder */
+ result = PyTuple_New(tuplesize);
+ if (result == NULL) {
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ for (i=0 ; i < tuplesize ; i++) {
+ Py_INCREF(Py_None);
+ PyTuple_SET_ITEM(result, i, Py_None);
+ }
+
+ /* create ziplongestobject structure */
+ lz = (ziplongestobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(ittuple);
+ Py_DECREF(result);
+ return NULL;
+ }
+ lz->ittuple = ittuple;
+ lz->tuplesize = tuplesize;
+ lz->numactive = tuplesize;
+ lz->result = result;
+ Py_INCREF(fillvalue);
+ lz->fillvalue = fillvalue;
+ return (PyObject *)lz;
}
static void
zip_longest_dealloc(ziplongestobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->ittuple);
- Py_XDECREF(lz->result);
- Py_XDECREF(lz->fillvalue);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->ittuple);
+ Py_XDECREF(lz->result);
+ Py_XDECREF(lz->fillvalue);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
zip_longest_traverse(ziplongestobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->ittuple);
- Py_VISIT(lz->result);
- Py_VISIT(lz->fillvalue);
- return 0;
+ Py_VISIT(lz->ittuple);
+ Py_VISIT(lz->result);
+ Py_VISIT(lz->fillvalue);
+ return 0;
}
static PyObject *
zip_longest_next(ziplongestobject *lz)
{
- Py_ssize_t i;
- Py_ssize_t tuplesize = lz->tuplesize;
- PyObject *result = lz->result;
- PyObject *it;
- PyObject *item;
- PyObject *olditem;
-
- if (tuplesize == 0)
- return NULL;
- if (lz->numactive == 0)
- return NULL;
- if (Py_REFCNT(result) == 1) {
- Py_INCREF(result);
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- if (it == NULL) {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- } else {
- item = PyIter_Next(it);
- if (item == NULL) {
- lz->numactive -= 1;
- if (lz->numactive == 0 || PyErr_Occurred()) {
- lz->numactive = 0;
- Py_DECREF(result);
- return NULL;
- } else {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- PyTuple_SET_ITEM(lz->ittuple, i, NULL);
- Py_DECREF(it);
- }
- }
- }
- olditem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, item);
- Py_DECREF(olditem);
+ Py_ssize_t i;
+ Py_ssize_t tuplesize = lz->tuplesize;
+ PyObject *result = lz->result;
+ PyObject *it;
+ PyObject *item;
+ PyObject *olditem;
+
+ if (tuplesize == 0)
+ return NULL;
+ if (lz->numactive == 0)
+ return NULL;
+ if (Py_REFCNT(result) == 1) {
+ Py_INCREF(result);
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ if (it == NULL) {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ } else {
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ lz->numactive -= 1;
+ if (lz->numactive == 0 || PyErr_Occurred()) {
+ lz->numactive = 0;
+ Py_DECREF(result);
+ return NULL;
+ } else {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ PyTuple_SET_ITEM(lz->ittuple, i, NULL);
+ Py_DECREF(it);
+ }
}
- } else {
- result = PyTuple_New(tuplesize);
- if (result == NULL)
+ }
+ olditem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, item);
+ Py_DECREF(olditem);
+ }
+ } else {
+ result = PyTuple_New(tuplesize);
+ if (result == NULL)
+ return NULL;
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ if (it == NULL) {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ } else {
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ lz->numactive -= 1;
+ if (lz->numactive == 0 || PyErr_Occurred()) {
+ lz->numactive = 0;
+ Py_DECREF(result);
return NULL;
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- if (it == NULL) {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- } else {
- item = PyIter_Next(it);
- if (item == NULL) {
- lz->numactive -= 1;
- if (lz->numactive == 0 || PyErr_Occurred()) {
- lz->numactive = 0;
- Py_DECREF(result);
- return NULL;
- } else {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- PyTuple_SET_ITEM(lz->ittuple, i, NULL);
- Py_DECREF(it);
- }
- }
- }
- PyTuple_SET_ITEM(result, i, item);
+ } else {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ PyTuple_SET_ITEM(lz->ittuple, i, NULL);
+ Py_DECREF(it);
+ }
}
+ }
+ PyTuple_SET_ITEM(result, i, item);
}
- return result;
+ }
+ return result;
}
PyDoc_STRVAR(zip_longest_doc,
@@ -3441,47 +3441,47 @@ defaults to None or can be specified by a keyword argument.\n\
");
static PyTypeObject ziplongest_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.zip_longest", /* tp_name */
- sizeof(ziplongestobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)zip_longest_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- zip_longest_doc, /* tp_doc */
- (traverseproc)zip_longest_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)zip_longest_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- zip_longest_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.zip_longest", /* tp_name */
+ sizeof(ziplongestobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)zip_longest_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ zip_longest_doc, /* tp_doc */
+ (traverseproc)zip_longest_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)zip_longest_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ zip_longest_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* module level code ********************************************************/
@@ -3516,68 +3516,68 @@ combinations_with_replacement(p, r)\n\
static PyMethodDef module_methods[] = {
- {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc},
- {NULL, NULL} /* sentinel */
+ {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc},
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef itertoolsmodule = {
- PyModuleDef_HEAD_INIT,
- "itertools",
- module_doc,
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "itertools",
+ module_doc,
+ -1,
+ module_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_itertools(void)
{
- int i;
- PyObject *m;
- char *name;
- PyTypeObject *typelist[] = {
- &combinations_type,
- &cwr_type,
- &cycle_type,
- &dropwhile_type,
- &takewhile_type,
- &islice_type,
- &starmap_type,
- &chain_type,
- &compress_type,
- &filterfalse_type,
- &count_type,
- &ziplongest_type,
- &permutations_type,
- &product_type,
- &repeat_type,
- &groupby_type,
- NULL
- };
-
- Py_TYPE(&teedataobject_type) = &PyType_Type;
- m = PyModule_Create(&itertoolsmodule);
- if (m == NULL)
- return NULL;
-
- for (i=0 ; typelist[i] != NULL ; i++) {
- if (PyType_Ready(typelist[i]) < 0)
- return NULL;
- name = strchr(typelist[i]->tp_name, '.');
- assert (name != NULL);
- Py_INCREF(typelist[i]);
- PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
- }
-
- if (PyType_Ready(&teedataobject_type) < 0)
- return NULL;
- if (PyType_Ready(&tee_type) < 0)
- return NULL;
- if (PyType_Ready(&_grouper_type) < 0)
- return NULL;
- return m;
+ int i;
+ PyObject *m;
+ char *name;
+ PyTypeObject *typelist[] = {
+ &combinations_type,
+ &cwr_type,
+ &cycle_type,
+ &dropwhile_type,
+ &takewhile_type,
+ &islice_type,
+ &starmap_type,
+ &chain_type,
+ &compress_type,
+ &filterfalse_type,
+ &count_type,
+ &ziplongest_type,
+ &permutations_type,
+ &product_type,
+ &repeat_type,
+ &groupby_type,
+ NULL
+ };
+
+ Py_TYPE(&teedataobject_type) = &PyType_Type;
+ m = PyModule_Create(&itertoolsmodule);
+ if (m == NULL)
+ return NULL;
+
+ for (i=0 ; typelist[i] != NULL ; i++) {
+ if (PyType_Ready(typelist[i]) < 0)
+ return NULL;
+ name = strchr(typelist[i]->tp_name, '.');
+ assert (name != NULL);
+ Py_INCREF(typelist[i]);
+ PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
+ }
+
+ if (PyType_Ready(&teedataobject_type) < 0)
+ return NULL;
+ if (PyType_Ready(&tee_type) < 0)
+ return NULL;
+ if (PyType_Ready(&_grouper_type) < 0)
+ return NULL;
+ return m;
}
diff --git a/Modules/main.c b/Modules/main.c
index 24c36db..32139f6 100644
--- a/Modules/main.c
+++ b/Modules/main.c
@@ -105,20 +105,20 @@ PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
static FILE*
_wfopen(const wchar_t *path, const wchar_t *mode)
{
- char cpath[PATH_MAX];
- char cmode[10];
- size_t r;
- r = wcstombs(cpath, path, PATH_MAX);
- if (r == (size_t)-1 || r >= PATH_MAX) {
- errno = EINVAL;
- return NULL;
- }
- r = wcstombs(cmode, mode, 10);
- if (r == (size_t)-1 || r >= 10) {
- errno = EINVAL;
- return NULL;
- }
- return fopen(cpath, cmode);
+ char cpath[PATH_MAX];
+ char cmode[10];
+ size_t r;
+ r = wcstombs(cpath, path, PATH_MAX);
+ if (r == (size_t)-1 || r >= PATH_MAX) {
+ errno = EINVAL;
+ return NULL;
+ }
+ r = wcstombs(cmode, mode, 10);
+ if (r == (size_t)-1 || r >= 10) {
+ errno = EINVAL;
+ return NULL;
+ }
+ return fopen(cpath, cmode);
}
#endif
@@ -126,131 +126,131 @@ _wfopen(const wchar_t *path, const wchar_t *mode)
static int
usage(int exitcode, wchar_t* program)
{
- FILE *f = exitcode ? stderr : stdout;
-
- fprintf(f, usage_line, program);
- if (exitcode)
- fprintf(f, "Try `python -h' for more information.\n");
- else {
- fputs(usage_1, f);
- fputs(usage_2, f);
- fputs(usage_3, f);
- fprintf(f, usage_4, DELIM);
- fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
- }
+ FILE *f = exitcode ? stderr : stdout;
+
+ fprintf(f, usage_line, program);
+ if (exitcode)
+ fprintf(f, "Try `python -h' for more information.\n");
+ else {
+ fputs(usage_1, f);
+ fputs(usage_2, f);
+ fputs(usage_3, f);
+ fprintf(f, usage_4, DELIM);
+ fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
+ }
#if defined(__VMS)
- if (exitcode == 0) {
- /* suppress 'error' message */
- return 1;
- }
- else {
- /* STS$M_INHIB_MSG + SS$_ABORT */
- return 0x1000002c;
- }
+ if (exitcode == 0) {
+ /* suppress 'error' message */
+ return 1;
+ }
+ else {
+ /* STS$M_INHIB_MSG + SS$_ABORT */
+ return 0x1000002c;
+ }
#else
- return exitcode;
+ return exitcode;
#endif
- /*NOTREACHED*/
+ /*NOTREACHED*/
}
static void RunStartupFile(PyCompilerFlags *cf)
{
- char *startup = Py_GETENV("PYTHONSTARTUP");
- if (startup != NULL && startup[0] != '\0') {
- FILE *fp = fopen(startup, "r");
- if (fp != NULL) {
- (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
- PyErr_Clear();
- fclose(fp);
- } else {
- int save_errno;
-
- save_errno = errno;
- PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
- errno = save_errno;
- PyErr_SetFromErrnoWithFilename(PyExc_IOError,
- startup);
- PyErr_Print();
- PyErr_Clear();
- }
- }
+ char *startup = Py_GETENV("PYTHONSTARTUP");
+ if (startup != NULL && startup[0] != '\0') {
+ FILE *fp = fopen(startup, "r");
+ if (fp != NULL) {
+ (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
+ PyErr_Clear();
+ fclose(fp);
+ } else {
+ int save_errno;
+
+ save_errno = errno;
+ PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
+ errno = save_errno;
+ PyErr_SetFromErrnoWithFilename(PyExc_IOError,
+ startup);
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
}
static int RunModule(wchar_t *modname, int set_argv0)
{
- PyObject *module, *runpy, *runmodule, *runargs, *result;
- runpy = PyImport_ImportModule("runpy");
- if (runpy == NULL) {
- fprintf(stderr, "Could not import runpy module\n");
- return -1;
- }
- runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
- if (runmodule == NULL) {
- fprintf(stderr, "Could not access runpy._run_module_as_main\n");
- Py_DECREF(runpy);
- return -1;
- }
- module = PyUnicode_FromWideChar(modname, wcslen(modname));
- if (module == NULL) {
- fprintf(stderr, "Could not convert module name to unicode\n");
- Py_DECREF(runpy);
- Py_DECREF(runmodule);
- return -1;
- }
- runargs = Py_BuildValue("(Oi)", module, set_argv0);
- if (runargs == NULL) {
- fprintf(stderr,
- "Could not create arguments for runpy._run_module_as_main\n");
- Py_DECREF(runpy);
- Py_DECREF(runmodule);
- Py_DECREF(module);
- return -1;
- }
- result = PyObject_Call(runmodule, runargs, NULL);
- if (result == NULL) {
- PyErr_Print();
- }
- Py_DECREF(runpy);
- Py_DECREF(runmodule);
- Py_DECREF(module);
- Py_DECREF(runargs);
- if (result == NULL) {
- return -1;
- }
- Py_DECREF(result);
- return 0;
+ PyObject *module, *runpy, *runmodule, *runargs, *result;
+ runpy = PyImport_ImportModule("runpy");
+ if (runpy == NULL) {
+ fprintf(stderr, "Could not import runpy module\n");
+ return -1;
+ }
+ runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
+ if (runmodule == NULL) {
+ fprintf(stderr, "Could not access runpy._run_module_as_main\n");
+ Py_DECREF(runpy);
+ return -1;
+ }
+ module = PyUnicode_FromWideChar(modname, wcslen(modname));
+ if (module == NULL) {
+ fprintf(stderr, "Could not convert module name to unicode\n");
+ Py_DECREF(runpy);
+ Py_DECREF(runmodule);
+ return -1;
+ }
+ runargs = Py_BuildValue("(Oi)", module, set_argv0);
+ if (runargs == NULL) {
+ fprintf(stderr,
+ "Could not create arguments for runpy._run_module_as_main\n");
+ Py_DECREF(runpy);
+ Py_DECREF(runmodule);
+ Py_DECREF(module);
+ return -1;
+ }
+ result = PyObject_Call(runmodule, runargs, NULL);
+ if (result == NULL) {
+ PyErr_Print();
+ }
+ Py_DECREF(runpy);
+ Py_DECREF(runmodule);
+ Py_DECREF(module);
+ Py_DECREF(runargs);
+ if (result == NULL) {
+ return -1;
+ }
+ Py_DECREF(result);
+ return 0;
}
static int RunMainFromImporter(wchar_t *filename)
{
- PyObject *argv0 = NULL, *importer = NULL;
-
- if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) &&
- (importer = PyImport_GetImporter(argv0)) &&
- (importer->ob_type != &PyNullImporter_Type))
- {
- /* argv0 is usable as an import source, so
- put it in sys.path[0] and import __main__ */
- PyObject *sys_path = NULL;
- if ((sys_path = PySys_GetObject("path")) &&
- !PyList_SetItem(sys_path, 0, argv0))
- {
- Py_INCREF(argv0);
- Py_DECREF(importer);
- sys_path = NULL;
- return RunModule(L"__main__", 0) != 0;
- }
- }
- Py_XDECREF(argv0);
- Py_XDECREF(importer);
- if (PyErr_Occurred()) {
- PyErr_Print();
- return 1;
+ PyObject *argv0 = NULL, *importer = NULL;
+
+ if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) &&
+ (importer = PyImport_GetImporter(argv0)) &&
+ (importer->ob_type != &PyNullImporter_Type))
+ {
+ /* argv0 is usable as an import source, so
+ put it in sys.path[0] and import __main__ */
+ PyObject *sys_path = NULL;
+ if ((sys_path = PySys_GetObject("path")) &&
+ !PyList_SetItem(sys_path, 0, argv0))
+ {
+ Py_INCREF(argv0);
+ Py_DECREF(importer);
+ sys_path = NULL;
+ return RunModule(L"__main__", 0) != 0;
}
- else {
- return -1;
- }
+ }
+ Py_XDECREF(argv0);
+ Py_XDECREF(importer);
+ if (PyErr_Occurred()) {
+ PyErr_Print();
+ return 1;
+ }
+ else {
+ return -1;
+ }
}
@@ -259,437 +259,437 @@ static int RunMainFromImporter(wchar_t *filename)
int
Py_Main(int argc, wchar_t **argv)
{
- int c;
- int sts;
- wchar_t *command = NULL;
- wchar_t *filename = NULL;
- wchar_t *module = NULL;
- FILE *fp = stdin;
- char *p;
+ int c;
+ int sts;
+ wchar_t *command = NULL;
+ wchar_t *filename = NULL;
+ wchar_t *module = NULL;
+ FILE *fp = stdin;
+ char *p;
#ifdef MS_WINDOWS
- wchar_t *wp;
+ wchar_t *wp;
#endif
- int skipfirstline = 0;
- int stdin_is_interactive = 0;
- int help = 0;
- int version = 0;
- int saw_unbuffered_flag = 0;
- PyCompilerFlags cf;
-
- cf.cf_flags = 0;
-
- orig_argc = argc; /* For Py_GetArgcArgv() */
- orig_argv = argv;
-
- PySys_ResetWarnOptions();
-
- while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
- if (c == 'c') {
- size_t len;
- /* -c is the last option; following arguments
- that look like options are left for the
- command to interpret. */
-
- len = wcslen(_PyOS_optarg) + 1 + 1;
- command = (wchar_t *)malloc(sizeof(wchar_t) * len);
- if (command == NULL)
- Py_FatalError(
- "not enough memory to copy -c argument");
- wcscpy(command, _PyOS_optarg);
- command[len - 2] = '\n';
- command[len - 1] = 0;
- break;
- }
-
- if (c == 'm') {
- /* -m is the last option; following arguments
- that look like options are left for the
- module to interpret. */
- module = _PyOS_optarg;
- break;
- }
-
- switch (c) {
- case 'b':
- Py_BytesWarningFlag++;
- break;
-
- case 'd':
- Py_DebugFlag++;
- break;
-
- case 'i':
- Py_InspectFlag++;
- Py_InteractiveFlag++;
- break;
-
- /* case 'J': reserved for Jython */
-
- case 'O':
- Py_OptimizeFlag++;
- break;
-
- case 'B':
- Py_DontWriteBytecodeFlag++;
- break;
-
- case 's':
- Py_NoUserSiteDirectory++;
- break;
-
- case 'S':
- Py_NoSiteFlag++;
- break;
-
- case 'E':
- Py_IgnoreEnvironmentFlag++;
- break;
-
- case 't':
- /* ignored for backwards compatibility */
- break;
-
- case 'u':
- Py_UnbufferedStdioFlag = 1;
- saw_unbuffered_flag = 1;
- break;
-
- case 'v':
- Py_VerboseFlag++;
- break;
-
- case 'x':
- skipfirstline = 1;
- break;
-
- /* case 'X': reserved for implementation-specific arguments */
-
- case 'h':
- case '?':
- help++;
- break;
-
- case 'V':
- version++;
- break;
-
- case 'W':
- PySys_AddWarnOption(_PyOS_optarg);
- break;
-
- /* This space reserved for other options */
-
- default:
- return usage(2, argv[0]);
- /*NOTREACHED*/
-
- }
- }
-
- if (help)
- return usage(0, argv[0]);
-
- if (version) {
- fprintf(stderr, "Python %s\n", PY_VERSION);
- return 0;
- }
-
- if (!Py_InspectFlag &&
- (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
- Py_InspectFlag = 1;
- if (!saw_unbuffered_flag &&
- (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
- Py_UnbufferedStdioFlag = 1;
+ int skipfirstline = 0;
+ int stdin_is_interactive = 0;
+ int help = 0;
+ int version = 0;
+ int saw_unbuffered_flag = 0;
+ PyCompilerFlags cf;
+
+ cf.cf_flags = 0;
+
+ orig_argc = argc; /* For Py_GetArgcArgv() */
+ orig_argv = argv;
+
+ PySys_ResetWarnOptions();
+
+ while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
+ if (c == 'c') {
+ size_t len;
+ /* -c is the last option; following arguments
+ that look like options are left for the
+ command to interpret. */
+
+ len = wcslen(_PyOS_optarg) + 1 + 1;
+ command = (wchar_t *)malloc(sizeof(wchar_t) * len);
+ if (command == NULL)
+ Py_FatalError(
+ "not enough memory to copy -c argument");
+ wcscpy(command, _PyOS_optarg);
+ command[len - 2] = '\n';
+ command[len - 1] = 0;
+ break;
+ }
+
+ if (c == 'm') {
+ /* -m is the last option; following arguments
+ that look like options are left for the
+ module to interpret. */
+ module = _PyOS_optarg;
+ break;
+ }
+
+ switch (c) {
+ case 'b':
+ Py_BytesWarningFlag++;
+ break;
+
+ case 'd':
+ Py_DebugFlag++;
+ break;
+
+ case 'i':
+ Py_InspectFlag++;
+ Py_InteractiveFlag++;
+ break;
+
+ /* case 'J': reserved for Jython */
+
+ case 'O':
+ Py_OptimizeFlag++;
+ break;
+
+ case 'B':
+ Py_DontWriteBytecodeFlag++;
+ break;
+
+ case 's':
+ Py_NoUserSiteDirectory++;
+ break;
+
+ case 'S':
+ Py_NoSiteFlag++;
+ break;
+
+ case 'E':
+ Py_IgnoreEnvironmentFlag++;
+ break;
+
+ case 't':
+ /* ignored for backwards compatibility */
+ break;
+
+ case 'u':
+ Py_UnbufferedStdioFlag = 1;
+ saw_unbuffered_flag = 1;
+ break;
+
+ case 'v':
+ Py_VerboseFlag++;
+ break;
+
+ case 'x':
+ skipfirstline = 1;
+ break;
+
+ /* case 'X': reserved for implementation-specific arguments */
+
+ case 'h':
+ case '?':
+ help++;
+ break;
+
+ case 'V':
+ version++;
+ break;
+
+ case 'W':
+ PySys_AddWarnOption(_PyOS_optarg);
+ break;
+
+ /* This space reserved for other options */
+
+ default:
+ return usage(2, argv[0]);
+ /*NOTREACHED*/
+
+ }
+ }
- if (!Py_NoUserSiteDirectory &&
- (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
- Py_NoUserSiteDirectory = 1;
+ if (help)
+ return usage(0, argv[0]);
+
+ if (version) {
+ fprintf(stderr, "Python %s\n", PY_VERSION);
+ return 0;
+ }
+
+ if (!Py_InspectFlag &&
+ (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
+ Py_InspectFlag = 1;
+ if (!saw_unbuffered_flag &&
+ (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
+ Py_UnbufferedStdioFlag = 1;
+
+ if (!Py_NoUserSiteDirectory &&
+ (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
+ Py_NoUserSiteDirectory = 1;
#ifdef MS_WINDOWS
- if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) &&
- *wp != L'\0') {
- wchar_t *buf, *warning;
-
- buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t));
- if (buf == NULL)
- Py_FatalError(
- "not enough memory to copy PYTHONWARNINGS");
- wcscpy(buf, wp);
- for (warning = wcstok(buf, L",");
- warning != NULL;
- warning = wcstok(NULL, L",")) {
- PySys_AddWarnOption(warning);
- }
- free(buf);
- }
+ if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) &&
+ *wp != L'\0') {
+ wchar_t *buf, *warning;
+
+ buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t));
+ if (buf == NULL)
+ Py_FatalError(
+ "not enough memory to copy PYTHONWARNINGS");
+ wcscpy(buf, wp);
+ for (warning = wcstok(buf, L",");
+ warning != NULL;
+ warning = wcstok(NULL, L",")) {
+ PySys_AddWarnOption(warning);
+ }
+ free(buf);
+ }
#else
- if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
- char *buf, *oldloc;
- wchar_t *warning;
-
- /* settle for strtok here as there's no one standard
- C89 wcstok */
- buf = (char *)malloc(strlen(p) + 1);
- if (buf == NULL)
- Py_FatalError(
- "not enough memory to copy PYTHONWARNINGS");
- strcpy(buf, p);
- oldloc = strdup(setlocale(LC_ALL, NULL));
- setlocale(LC_ALL, "");
- for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) {
- if ((warning = _Py_char2wchar(p)) != NULL) {
- PySys_AddWarnOption(warning);
- PyMem_Free(warning);
- }
- }
- setlocale(LC_ALL, oldloc);
- free(oldloc);
- free(buf);
- }
+ if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
+ char *buf, *oldloc;
+ wchar_t *warning;
+
+ /* settle for strtok here as there's no one standard
+ C89 wcstok */
+ buf = (char *)malloc(strlen(p) + 1);
+ if (buf == NULL)
+ Py_FatalError(
+ "not enough memory to copy PYTHONWARNINGS");
+ strcpy(buf, p);
+ oldloc = strdup(setlocale(LC_ALL, NULL));
+ setlocale(LC_ALL, "");
+ for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) {
+ if ((warning = _Py_char2wchar(p)) != NULL) {
+ PySys_AddWarnOption(warning);
+ PyMem_Free(warning);
+ }
+ }
+ setlocale(LC_ALL, oldloc);
+ free(oldloc);
+ free(buf);
+ }
#endif
- if (command == NULL && module == NULL && _PyOS_optind < argc &&
- wcscmp(argv[_PyOS_optind], L"-") != 0)
- {
+ if (command == NULL && module == NULL && _PyOS_optind < argc &&
+ wcscmp(argv[_PyOS_optind], L"-") != 0)
+ {
#ifdef __VMS
- filename = decc$translate_vms(argv[_PyOS_optind]);
- if (filename == (char *)0 || filename == (char *)-1)
- filename = argv[_PyOS_optind];
+ filename = decc$translate_vms(argv[_PyOS_optind]);
+ if (filename == (char *)0 || filename == (char *)-1)
+ filename = argv[_PyOS_optind];
#else
- filename = argv[_PyOS_optind];
+ filename = argv[_PyOS_optind];
#endif
- }
+ }
- stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
+ stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
- if (Py_UnbufferedStdioFlag) {
+ if (Py_UnbufferedStdioFlag) {
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
- _setmode(fileno(stdin), O_BINARY);
- _setmode(fileno(stdout), O_BINARY);
+ _setmode(fileno(stdin), O_BINARY);
+ _setmode(fileno(stdout), O_BINARY);
#endif
#ifdef HAVE_SETVBUF
- setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
- setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
- setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
+ setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
+ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
+ setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
#else /* !HAVE_SETVBUF */
- setbuf(stdin, (char *)NULL);
- setbuf(stdout, (char *)NULL);
- setbuf(stderr, (char *)NULL);
+ setbuf(stdin, (char *)NULL);
+ setbuf(stdout, (char *)NULL);
+ setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
- }
- else if (Py_InteractiveFlag) {
+ }
+ else if (Py_InteractiveFlag) {
#ifdef MS_WINDOWS
- /* Doesn't have to have line-buffered -- use unbuffered */
- /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
- setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
+ /* Doesn't have to have line-buffered -- use unbuffered */
+ /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
+ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
#else /* !MS_WINDOWS */
#ifdef HAVE_SETVBUF
- setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
- setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
+ setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
+ setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
#endif /* HAVE_SETVBUF */
#endif /* !MS_WINDOWS */
- /* Leave stderr alone - it should be unbuffered anyway. */
- }
+ /* Leave stderr alone - it should be unbuffered anyway. */
+ }
#ifdef __VMS
- else {
- setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
- }
+ else {
+ setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
+ }
#endif /* __VMS */
#ifdef __APPLE__
- /* On MacOS X, when the Python interpreter is embedded in an
- application bundle, it gets executed by a bootstrapping script
- that does os.execve() with an argv[0] that's different from the
- actual Python executable. This is needed to keep the Finder happy,
- or rather, to work around Apple's overly strict requirements of
- the process name. However, we still need a usable sys.executable,
- so the actual executable path is passed in an environment variable.
- See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
- script. */
- if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') {
- wchar_t* buffer;
- size_t len = strlen(p);
- size_t r;
-
- buffer = malloc(len * sizeof(wchar_t));
- if (buffer == NULL) {
- Py_FatalError(
- "not enough memory to copy PYTHONEXECUTABLE");
- }
-
- r = mbstowcs(buffer, p, len);
- Py_SetProgramName(buffer);
- /* buffer is now handed off - do not free */
- } else {
- Py_SetProgramName(argv[0]);
- }
+ /* On MacOS X, when the Python interpreter is embedded in an
+ application bundle, it gets executed by a bootstrapping script
+ that does os.execve() with an argv[0] that's different from the
+ actual Python executable. This is needed to keep the Finder happy,
+ or rather, to work around Apple's overly strict requirements of
+ the process name. However, we still need a usable sys.executable,
+ so the actual executable path is passed in an environment variable.
+ See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
+ script. */
+ if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') {
+ wchar_t* buffer;
+ size_t len = strlen(p);
+ size_t r;
+
+ buffer = malloc(len * sizeof(wchar_t));
+ if (buffer == NULL) {
+ Py_FatalError(
+ "not enough memory to copy PYTHONEXECUTABLE");
+ }
+
+ r = mbstowcs(buffer, p, len);
+ Py_SetProgramName(buffer);
+ /* buffer is now handed off - do not free */
+ } else {
+ Py_SetProgramName(argv[0]);
+ }
#else
- Py_SetProgramName(argv[0]);
+ Py_SetProgramName(argv[0]);
#endif
- Py_Initialize();
-
- if (Py_VerboseFlag ||
- (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
- fprintf(stderr, "Python %s on %s\n",
- Py_GetVersion(), Py_GetPlatform());
- if (!Py_NoSiteFlag)
- fprintf(stderr, "%s\n", COPYRIGHT);
- }
-
- if (command != NULL) {
- /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
- _PyOS_optind--;
- argv[_PyOS_optind] = L"-c";
- }
-
- if (module != NULL) {
- /* Backup _PyOS_optind and force sys.argv[0] = '-c'
- so that PySys_SetArgv correctly sets sys.path[0] to ''*/
- _PyOS_optind--;
- argv[_PyOS_optind] = L"-c";
- }
-
- PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
-
- if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
- isatty(fileno(stdin))) {
- PyObject *v;
- v = PyImport_ImportModule("readline");
- if (v == NULL)
- PyErr_Clear();
- else
- Py_DECREF(v);
- }
-
- if (command) {
- PyObject *commandObj = PyUnicode_FromWideChar(
- command, wcslen(command));
- free(command);
- if (commandObj != NULL) {
- sts = PyRun_SimpleStringFlags(
- _PyUnicode_AsString(commandObj), &cf) != 0;
- }
- else {
- PyErr_Print();
- sts = 1;
- }
- Py_DECREF(commandObj);
- } else if (module) {
- sts = RunModule(module, 1);
- }
- else {
-
- if (filename == NULL && stdin_is_interactive) {
- Py_InspectFlag = 0; /* do exit on SystemExit */
- RunStartupFile(&cf);
- }
- /* XXX */
-
- sts = -1; /* keep track of whether we've already run __main__ */
-
- if (filename != NULL) {
- sts = RunMainFromImporter(filename);
- }
-
- if (sts==-1 && filename!=NULL) {
- if ((fp = _wfopen(filename, L"r")) == NULL) {
- char cfilename[PATH_MAX];
- size_t r = wcstombs(cfilename, filename, PATH_MAX);
- if (r == PATH_MAX)
- /* cfilename is not null-terminated;
- * forcefully null-terminating it
- * might break the shift state */
- strcpy(cfilename, "<file name too long>");
- if (r == ((size_t)-1))
- strcpy(cfilename, "<unprintable file name>");
- fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n",
- argv[0], cfilename, errno, strerror(errno));
-
- return 2;
- }
- else if (skipfirstline) {
- int ch;
- /* Push back first newline so line numbers
- remain the same */
- while ((ch = getc(fp)) != EOF) {
- if (ch == '\n') {
- (void)ungetc(ch, fp);
- break;
- }
- }
- }
- {
- /* XXX: does this work on Win/Win64? (see posix_fstat) */
- struct stat sb;
- if (fstat(fileno(fp), &sb) == 0 &&
- S_ISDIR(sb.st_mode)) {
- fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename);
- fclose(fp);
- return 1;
- }
- }
- }
-
- if (sts==-1) {
- PyObject *filenameObj = NULL;
- char *p_cfilename = "<stdin>";
- if (filename) {
- filenameObj = PyUnicode_FromWideChar(
- filename, wcslen(filename));
- if (filenameObj != NULL)
- p_cfilename = _PyUnicode_AsString(filenameObj);
- else
- p_cfilename = "<decoding error>";
- }
- /* call pending calls like signal handlers (SIGINT) */
- if (Py_MakePendingCalls() == -1) {
- PyErr_Print();
- sts = 1;
- } else {
- sts = PyRun_AnyFileExFlags(
- fp,
- p_cfilename,
- filename != NULL, &cf) != 0;
- }
- Py_XDECREF(filenameObj);
- }
-
- }
-
- /* Check this environment variable at the end, to give programs the
- * opportunity to set it from Python.
- */
- if (!Py_InspectFlag &&
- (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
- {
- Py_InspectFlag = 1;
- }
-
- if (Py_InspectFlag && stdin_is_interactive &&
- (filename != NULL || command != NULL || module != NULL)) {
- Py_InspectFlag = 0;
- /* XXX */
- sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
- }
-
- Py_Finalize();
+ Py_Initialize();
+
+ if (Py_VerboseFlag ||
+ (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
+ fprintf(stderr, "Python %s on %s\n",
+ Py_GetVersion(), Py_GetPlatform());
+ if (!Py_NoSiteFlag)
+ fprintf(stderr, "%s\n", COPYRIGHT);
+ }
+
+ if (command != NULL) {
+ /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
+ _PyOS_optind--;
+ argv[_PyOS_optind] = L"-c";
+ }
+
+ if (module != NULL) {
+ /* Backup _PyOS_optind and force sys.argv[0] = '-c'
+ so that PySys_SetArgv correctly sets sys.path[0] to ''*/
+ _PyOS_optind--;
+ argv[_PyOS_optind] = L"-c";
+ }
+
+ PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
+
+ if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
+ isatty(fileno(stdin))) {
+ PyObject *v;
+ v = PyImport_ImportModule("readline");
+ if (v == NULL)
+ PyErr_Clear();
+ else
+ Py_DECREF(v);
+ }
+
+ if (command) {
+ PyObject *commandObj = PyUnicode_FromWideChar(
+ command, wcslen(command));
+ free(command);
+ if (commandObj != NULL) {
+ sts = PyRun_SimpleStringFlags(
+ _PyUnicode_AsString(commandObj), &cf) != 0;
+ }
+ else {
+ PyErr_Print();
+ sts = 1;
+ }
+ Py_DECREF(commandObj);
+ } else if (module) {
+ sts = RunModule(module, 1);
+ }
+ else {
+
+ if (filename == NULL && stdin_is_interactive) {
+ Py_InspectFlag = 0; /* do exit on SystemExit */
+ RunStartupFile(&cf);
+ }
+ /* XXX */
+
+ sts = -1; /* keep track of whether we've already run __main__ */
+
+ if (filename != NULL) {
+ sts = RunMainFromImporter(filename);
+ }
+
+ if (sts==-1 && filename!=NULL) {
+ if ((fp = _wfopen(filename, L"r")) == NULL) {
+ char cfilename[PATH_MAX];
+ size_t r = wcstombs(cfilename, filename, PATH_MAX);
+ if (r == PATH_MAX)
+ /* cfilename is not null-terminated;
+ * forcefully null-terminating it
+ * might break the shift state */
+ strcpy(cfilename, "<file name too long>");
+ if (r == ((size_t)-1))
+ strcpy(cfilename, "<unprintable file name>");
+ fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n",
+ argv[0], cfilename, errno, strerror(errno));
+
+ return 2;
+ }
+ else if (skipfirstline) {
+ int ch;
+ /* Push back first newline so line numbers
+ remain the same */
+ while ((ch = getc(fp)) != EOF) {
+ if (ch == '\n') {
+ (void)ungetc(ch, fp);
+ break;
+ }
+ }
+ }
+ {
+ /* XXX: does this work on Win/Win64? (see posix_fstat) */
+ struct stat sb;
+ if (fstat(fileno(fp), &sb) == 0 &&
+ S_ISDIR(sb.st_mode)) {
+ fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename);
+ fclose(fp);
+ return 1;
+ }
+ }
+ }
+
+ if (sts==-1) {
+ PyObject *filenameObj = NULL;
+ char *p_cfilename = "<stdin>";
+ if (filename) {
+ filenameObj = PyUnicode_FromWideChar(
+ filename, wcslen(filename));
+ if (filenameObj != NULL)
+ p_cfilename = _PyUnicode_AsString(filenameObj);
+ else
+ p_cfilename = "<decoding error>";
+ }
+ /* call pending calls like signal handlers (SIGINT) */
+ if (Py_MakePendingCalls() == -1) {
+ PyErr_Print();
+ sts = 1;
+ } else {
+ sts = PyRun_AnyFileExFlags(
+ fp,
+ p_cfilename,
+ filename != NULL, &cf) != 0;
+ }
+ Py_XDECREF(filenameObj);
+ }
+
+ }
+
+ /* Check this environment variable at the end, to give programs the
+ * opportunity to set it from Python.
+ */
+ if (!Py_InspectFlag &&
+ (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
+ {
+ Py_InspectFlag = 1;
+ }
+
+ if (Py_InspectFlag && stdin_is_interactive &&
+ (filename != NULL || command != NULL || module != NULL)) {
+ Py_InspectFlag = 0;
+ /* XXX */
+ sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
+ }
+
+ Py_Finalize();
#ifdef __INSURE__
- /* Insure++ is a memory analysis tool that aids in discovering
- * memory leaks and other memory problems. On Python exit, the
- * interned string dictionaries are flagged as being in use at exit
- * (which it is). Under normal circumstances, this is fine because
- * the memory will be automatically reclaimed by the system. Under
- * memory debugging, it's a huge source of useless noise, so we
- * trade off slower shutdown for less distraction in the memory
- * reports. -baw
- */
- _Py_ReleaseInternedStrings();
- _Py_ReleaseInternedUnicodeStrings();
+ /* Insure++ is a memory analysis tool that aids in discovering
+ * memory leaks and other memory problems. On Python exit, the
+ * interned string dictionaries are flagged as being in use at exit
+ * (which it is). Under normal circumstances, this is fine because
+ * the memory will be automatically reclaimed by the system. Under
+ * memory debugging, it's a huge source of useless noise, so we
+ * trade off slower shutdown for less distraction in the memory
+ * reports. -baw
+ */
+ _Py_ReleaseInternedStrings();
+ _Py_ReleaseInternedUnicodeStrings();
#endif /* __INSURE__ */
- return sts;
+ return sts;
}
/* this is gonna seem *real weird*, but if you put some other code between
@@ -702,112 +702,112 @@ Py_Main(int argc, wchar_t **argv)
void
Py_GetArgcArgv(int *argc, wchar_t ***argv)
{
- *argc = orig_argc;
- *argv = orig_argv;
+ *argc = orig_argc;
+ *argv = orig_argv;
}
wchar_t*
_Py_char2wchar(char* arg)
{
- wchar_t *res;
+ wchar_t *res;
#ifdef HAVE_BROKEN_MBSTOWCS
- /* Some platforms have a broken implementation of
- * mbstowcs which does not count the characters that
- * would result from conversion. Use an upper bound.
- */
- size_t argsize = strlen(arg);
+ /* Some platforms have a broken implementation of
+ * mbstowcs which does not count the characters that
+ * would result from conversion. Use an upper bound.
+ */
+ size_t argsize = strlen(arg);
#else
- size_t argsize = mbstowcs(NULL, arg, 0);
+ size_t argsize = mbstowcs(NULL, arg, 0);
#endif
- size_t count;
- unsigned char *in;
- wchar_t *out;
+ size_t count;
+ unsigned char *in;
+ wchar_t *out;
#ifdef HAVE_MBRTOWC
- mbstate_t mbs;
+ mbstate_t mbs;
#endif
- if (argsize != (size_t)-1) {
- res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
- if (!res)
- goto oom;
- count = mbstowcs(res, arg, argsize+1);
- if (count != (size_t)-1) {
- wchar_t *tmp;
- /* Only use the result if it contains no
- surrogate characters. */
- for (tmp = res; *tmp != 0 &&
- (*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
- ;
- if (*tmp == 0)
- return res;
- }
- PyMem_Free(res);
- }
- /* Conversion failed. Fall back to escaping with surrogateescape. */
+ if (argsize != (size_t)-1) {
+ res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
+ if (!res)
+ goto oom;
+ count = mbstowcs(res, arg, argsize+1);
+ if (count != (size_t)-1) {
+ wchar_t *tmp;
+ /* Only use the result if it contains no
+ surrogate characters. */
+ for (tmp = res; *tmp != 0 &&
+ (*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
+ ;
+ if (*tmp == 0)
+ return res;
+ }
+ PyMem_Free(res);
+ }
+ /* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
- /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
-
- /* Overallocate; as multi-byte characters are in the argument, the
- actual output could use less memory. */
- argsize = strlen(arg) + 1;
- res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t));
- if (!res) goto oom;
- in = (unsigned char*)arg;
- out = res;
- memset(&mbs, 0, sizeof mbs);
- while (argsize) {
- size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
- if (converted == 0)
- /* Reached end of string; null char stored. */
- break;
- if (converted == (size_t)-2) {
- /* Incomplete character. This should never happen,
- since we provide everything that we have -
- unless there is a bug in the C library, or I
- misunderstood how mbrtowc works. */
- fprintf(stderr, "unexpected mbrtowc result -2\n");
- return NULL;
- }
- if (converted == (size_t)-1) {
- /* Conversion error. Escape as UTF-8b, and start over
- in the initial shift state. */
- *out++ = 0xdc00 + *in++;
- argsize--;
- memset(&mbs, 0, sizeof mbs);
- continue;
- }
- if (*out >= 0xd800 && *out <= 0xdfff) {
- /* Surrogate character. Escape the original
- byte sequence with surrogateescape. */
- argsize -= converted;
- while (converted--)
- *out++ = 0xdc00 + *in++;
- continue;
- }
- /* successfully converted some bytes */
- in += converted;
- argsize -= converted;
- out++;
- }
+ /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
+
+ /* Overallocate; as multi-byte characters are in the argument, the
+ actual output could use less memory. */
+ argsize = strlen(arg) + 1;
+ res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t));
+ if (!res) goto oom;
+ in = (unsigned char*)arg;
+ out = res;
+ memset(&mbs, 0, sizeof mbs);
+ while (argsize) {
+ size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
+ if (converted == 0)
+ /* Reached end of string; null char stored. */
+ break;
+ if (converted == (size_t)-2) {
+ /* Incomplete character. This should never happen,
+ since we provide everything that we have -
+ unless there is a bug in the C library, or I
+ misunderstood how mbrtowc works. */
+ fprintf(stderr, "unexpected mbrtowc result -2\n");
+ return NULL;
+ }
+ if (converted == (size_t)-1) {
+ /* Conversion error. Escape as UTF-8b, and start over
+ in the initial shift state. */
+ *out++ = 0xdc00 + *in++;
+ argsize--;
+ memset(&mbs, 0, sizeof mbs);
+ continue;
+ }
+ if (*out >= 0xd800 && *out <= 0xdfff) {
+ /* Surrogate character. Escape the original
+ byte sequence with surrogateescape. */
+ argsize -= converted;
+ while (converted--)
+ *out++ = 0xdc00 + *in++;
+ continue;
+ }
+ /* successfully converted some bytes */
+ in += converted;
+ argsize -= converted;
+ out++;
+ }
#else
- /* Cannot use C locale for escaping; manually escape as if charset
- is ASCII (i.e. escape all bytes > 128. This will still roundtrip
- correctly in the locale's charset, which must be an ASCII superset. */
- res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
- if (!res) goto oom;
- in = (unsigned char*)arg;
- out = res;
- while(*in)
- if(*in < 128)
- *out++ = *in++;
- else
- *out++ = 0xdc00 + *in++;
- *out = 0;
+ /* Cannot use C locale for escaping; manually escape as if charset
+ is ASCII (i.e. escape all bytes > 128. This will still roundtrip
+ correctly in the locale's charset, which must be an ASCII superset. */
+ res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
+ if (!res) goto oom;
+ in = (unsigned char*)arg;
+ out = res;
+ while(*in)
+ if(*in < 128)
+ *out++ = *in++;
+ else
+ *out++ = 0xdc00 + *in++;
+ *out = 0;
#endif
- return res;
+ return res;
oom:
- fprintf(stderr, "out of memory\n");
- return NULL;
+ fprintf(stderr, "out of memory\n");
+ return NULL;
}
#ifdef __cplusplus
diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c
index 87afdab..76d7906 100644
--- a/Modules/mathmodule.c
+++ b/Modules/mathmodule.c
@@ -73,36 +73,36 @@ static const double sqrtpi = 1.772453850905516027298167483341145182798;
static double
sinpi(double x)
{
- double y, r;
- int n;
- /* this function should only ever be called for finite arguments */
- assert(Py_IS_FINITE(x));
- y = fmod(fabs(x), 2.0);
- n = (int)round(2.0*y);
- assert(0 <= n && n <= 4);
- switch (n) {
- case 0:
- r = sin(pi*y);
- break;
- case 1:
- r = cos(pi*(y-0.5));
- break;
- case 2:
- /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
- -0.0 instead of 0.0 when y == 1.0. */
- r = sin(pi*(1.0-y));
- break;
- case 3:
- r = -cos(pi*(y-1.5));
- break;
- case 4:
- r = sin(pi*(y-2.0));
- break;
- default:
- assert(0); /* should never get here */
- r = -1.23e200; /* silence gcc warning */
- }
- return copysign(1.0, x)*r;
+ double y, r;
+ int n;
+ /* this function should only ever be called for finite arguments */
+ assert(Py_IS_FINITE(x));
+ y = fmod(fabs(x), 2.0);
+ n = (int)round(2.0*y);
+ assert(0 <= n && n <= 4);
+ switch (n) {
+ case 0:
+ r = sin(pi*y);
+ break;
+ case 1:
+ r = cos(pi*(y-0.5));
+ break;
+ case 2:
+ /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
+ -0.0 instead of 0.0 when y == 1.0. */
+ r = sin(pi*(1.0-y));
+ break;
+ case 3:
+ r = -cos(pi*(y-1.5));
+ break;
+ case 4:
+ r = sin(pi*(y-2.0));
+ break;
+ default:
+ assert(0); /* should never get here */
+ r = -1.23e200; /* silence gcc warning */
+ }
+ return copysign(1.0, x)*r;
}
/* Implementation of the real gamma function. In extensive but non-exhaustive
@@ -166,34 +166,34 @@ sinpi(double x)
static const double lanczos_g = 6.024680040776729583740234375;
static const double lanczos_g_minus_half = 5.524680040776729583740234375;
static const double lanczos_num_coeffs[LANCZOS_N] = {
- 23531376880.410759688572007674451636754734846804940,
- 42919803642.649098768957899047001988850926355848959,
- 35711959237.355668049440185451547166705960488635843,
- 17921034426.037209699919755754458931112671403265390,
- 6039542586.3520280050642916443072979210699388420708,
- 1439720407.3117216736632230727949123939715485786772,
- 248874557.86205415651146038641322942321632125127801,
- 31426415.585400194380614231628318205362874684987640,
- 2876370.6289353724412254090516208496135991145378768,
- 186056.26539522349504029498971604569928220784236328,
- 8071.6720023658162106380029022722506138218516325024,
- 210.82427775157934587250973392071336271166969580291,
- 2.5066282746310002701649081771338373386264310793408
+ 23531376880.410759688572007674451636754734846804940,
+ 42919803642.649098768957899047001988850926355848959,
+ 35711959237.355668049440185451547166705960488635843,
+ 17921034426.037209699919755754458931112671403265390,
+ 6039542586.3520280050642916443072979210699388420708,
+ 1439720407.3117216736632230727949123939715485786772,
+ 248874557.86205415651146038641322942321632125127801,
+ 31426415.585400194380614231628318205362874684987640,
+ 2876370.6289353724412254090516208496135991145378768,
+ 186056.26539522349504029498971604569928220784236328,
+ 8071.6720023658162106380029022722506138218516325024,
+ 210.82427775157934587250973392071336271166969580291,
+ 2.5066282746310002701649081771338373386264310793408
};
/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
static const double lanczos_den_coeffs[LANCZOS_N] = {
- 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
- 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
+ 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
+ 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
#define NGAMMA_INTEGRAL 23
static const double gamma_integral[NGAMMA_INTEGRAL] = {
- 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
- 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
- 1307674368000.0, 20922789888000.0, 355687428096000.0,
- 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
- 51090942171709440000.0, 1124000727777607680000.0,
+ 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
+ 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
+ 1307674368000.0, 20922789888000.0, 355687428096000.0,
+ 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
+ 51090942171709440000.0, 1124000727777607680000.0,
};
/* Lanczos' sum L_g(x), for positive x */
@@ -201,125 +201,125 @@ static const double gamma_integral[NGAMMA_INTEGRAL] = {
static double
lanczos_sum(double x)
{
- double num = 0.0, den = 0.0;
- int i;
- assert(x > 0.0);
- /* evaluate the rational function lanczos_sum(x). For large
- x, the obvious algorithm risks overflow, so we instead
- rescale the denominator and numerator of the rational
- function by x**(1-LANCZOS_N) and treat this as a
- rational function in 1/x. This also reduces the error for
- larger x values. The choice of cutoff point (5.0 below) is
- somewhat arbitrary; in tests, smaller cutoff values than
- this resulted in lower accuracy. */
- if (x < 5.0) {
- for (i = LANCZOS_N; --i >= 0; ) {
- num = num * x + lanczos_num_coeffs[i];
- den = den * x + lanczos_den_coeffs[i];
- }
- }
- else {
- for (i = 0; i < LANCZOS_N; i++) {
- num = num / x + lanczos_num_coeffs[i];
- den = den / x + lanczos_den_coeffs[i];
- }
- }
- return num/den;
+ double num = 0.0, den = 0.0;
+ int i;
+ assert(x > 0.0);
+ /* evaluate the rational function lanczos_sum(x). For large
+ x, the obvious algorithm risks overflow, so we instead
+ rescale the denominator and numerator of the rational
+ function by x**(1-LANCZOS_N) and treat this as a
+ rational function in 1/x. This also reduces the error for
+ larger x values. The choice of cutoff point (5.0 below) is
+ somewhat arbitrary; in tests, smaller cutoff values than
+ this resulted in lower accuracy. */
+ if (x < 5.0) {
+ for (i = LANCZOS_N; --i >= 0; ) {
+ num = num * x + lanczos_num_coeffs[i];
+ den = den * x + lanczos_den_coeffs[i];
+ }
+ }
+ else {
+ for (i = 0; i < LANCZOS_N; i++) {
+ num = num / x + lanczos_num_coeffs[i];
+ den = den / x + lanczos_den_coeffs[i];
+ }
+ }
+ return num/den;
}
static double
m_tgamma(double x)
{
- double absx, r, y, z, sqrtpow;
-
- /* special cases */
- if (!Py_IS_FINITE(x)) {
- if (Py_IS_NAN(x) || x > 0.0)
- return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
- else {
- errno = EDOM;
- return Py_NAN; /* tgamma(-inf) = nan, invalid */
- }
- }
- if (x == 0.0) {
- errno = EDOM;
- return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
- }
-
- /* integer arguments */
- if (x == floor(x)) {
- if (x < 0.0) {
- errno = EDOM; /* tgamma(n) = nan, invalid for */
- return Py_NAN; /* negative integers n */
- }
- if (x <= NGAMMA_INTEGRAL)
- return gamma_integral[(int)x - 1];
- }
- absx = fabs(x);
-
- /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
- if (absx < 1e-20) {
- r = 1.0/x;
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- return r;
- }
-
- /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
- x > 200, and underflows to +-0.0 for x < -200, not a negative
- integer. */
- if (absx > 200.0) {
- if (x < 0.0) {
- return 0.0/sinpi(x);
- }
- else {
- errno = ERANGE;
- return Py_HUGE_VAL;
- }
- }
-
- y = absx + lanczos_g_minus_half;
- /* compute error in sum */
- if (absx > lanczos_g_minus_half) {
- /* note: the correction can be foiled by an optimizing
- compiler that (incorrectly) thinks that an expression like
- a + b - a - b can be optimized to 0.0. This shouldn't
- happen in a standards-conforming compiler. */
- double q = y - absx;
- z = q - lanczos_g_minus_half;
- }
- else {
- double q = y - lanczos_g_minus_half;
- z = q - absx;
- }
- z = z * lanczos_g / y;
- if (x < 0.0) {
- r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
- r -= z * r;
- if (absx < 140.0) {
- r /= pow(y, absx - 0.5);
- }
- else {
- sqrtpow = pow(y, absx / 2.0 - 0.25);
- r /= sqrtpow;
- r /= sqrtpow;
- }
- }
- else {
- r = lanczos_sum(absx) / exp(y);
- r += z * r;
- if (absx < 140.0) {
- r *= pow(y, absx - 0.5);
- }
- else {
- sqrtpow = pow(y, absx / 2.0 - 0.25);
- r *= sqrtpow;
- r *= sqrtpow;
- }
- }
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- return r;
+ double absx, r, y, z, sqrtpow;
+
+ /* special cases */
+ if (!Py_IS_FINITE(x)) {
+ if (Py_IS_NAN(x) || x > 0.0)
+ return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
+ else {
+ errno = EDOM;
+ return Py_NAN; /* tgamma(-inf) = nan, invalid */
+ }
+ }
+ if (x == 0.0) {
+ errno = EDOM;
+ return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
+ }
+
+ /* integer arguments */
+ if (x == floor(x)) {
+ if (x < 0.0) {
+ errno = EDOM; /* tgamma(n) = nan, invalid for */
+ return Py_NAN; /* negative integers n */
+ }
+ if (x <= NGAMMA_INTEGRAL)
+ return gamma_integral[(int)x - 1];
+ }
+ absx = fabs(x);
+
+ /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
+ if (absx < 1e-20) {
+ r = 1.0/x;
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ return r;
+ }
+
+ /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
+ x > 200, and underflows to +-0.0 for x < -200, not a negative
+ integer. */
+ if (absx > 200.0) {
+ if (x < 0.0) {
+ return 0.0/sinpi(x);
+ }
+ else {
+ errno = ERANGE;
+ return Py_HUGE_VAL;
+ }
+ }
+
+ y = absx + lanczos_g_minus_half;
+ /* compute error in sum */
+ if (absx > lanczos_g_minus_half) {
+ /* note: the correction can be foiled by an optimizing
+ compiler that (incorrectly) thinks that an expression like
+ a + b - a - b can be optimized to 0.0. This shouldn't
+ happen in a standards-conforming compiler. */
+ double q = y - absx;
+ z = q - lanczos_g_minus_half;
+ }
+ else {
+ double q = y - lanczos_g_minus_half;
+ z = q - absx;
+ }
+ z = z * lanczos_g / y;
+ if (x < 0.0) {
+ r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
+ r -= z * r;
+ if (absx < 140.0) {
+ r /= pow(y, absx - 0.5);
+ }
+ else {
+ sqrtpow = pow(y, absx / 2.0 - 0.25);
+ r /= sqrtpow;
+ r /= sqrtpow;
+ }
+ }
+ else {
+ r = lanczos_sum(absx) / exp(y);
+ r += z * r;
+ if (absx < 140.0) {
+ r *= pow(y, absx - 0.5);
+ }
+ else {
+ sqrtpow = pow(y, absx / 2.0 - 0.25);
+ r *= sqrtpow;
+ r *= sqrtpow;
+ }
+ }
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ return r;
}
/*
@@ -330,49 +330,49 @@ m_tgamma(double x)
static double
m_lgamma(double x)
{
- double r, absx;
-
- /* special cases */
- if (!Py_IS_FINITE(x)) {
- if (Py_IS_NAN(x))
- return x; /* lgamma(nan) = nan */
- else
- return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
- }
-
- /* integer arguments */
- if (x == floor(x) && x <= 2.0) {
- if (x <= 0.0) {
- errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
- return Py_HUGE_VAL; /* integers n <= 0 */
- }
- else {
- return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
- }
- }
-
- absx = fabs(x);
- /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
- if (absx < 1e-20)
- return -log(absx);
-
- /* Lanczos' formula */
- if (x > 0.0) {
- /* we could save a fraction of a ulp in accuracy by having a
- second set of numerator coefficients for lanczos_sum that
- absorbed the exp(-lanczos_g) term, and throwing out the
- lanczos_g subtraction below; it's probably not worth it. */
- r = log(lanczos_sum(x)) - lanczos_g +
- (x-0.5)*(log(x+lanczos_g-0.5)-1);
- }
- else {
- r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
- (log(lanczos_sum(absx)) - lanczos_g +
- (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
- }
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- return r;
+ double r, absx;
+
+ /* special cases */
+ if (!Py_IS_FINITE(x)) {
+ if (Py_IS_NAN(x))
+ return x; /* lgamma(nan) = nan */
+ else
+ return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
+ }
+
+ /* integer arguments */
+ if (x == floor(x) && x <= 2.0) {
+ if (x <= 0.0) {
+ errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
+ return Py_HUGE_VAL; /* integers n <= 0 */
+ }
+ else {
+ return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
+ }
+ }
+
+ absx = fabs(x);
+ /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
+ if (absx < 1e-20)
+ return -log(absx);
+
+ /* Lanczos' formula */
+ if (x > 0.0) {
+ /* we could save a fraction of a ulp in accuracy by having a
+ second set of numerator coefficients for lanczos_sum that
+ absorbed the exp(-lanczos_g) term, and throwing out the
+ lanczos_g subtraction below; it's probably not worth it. */
+ r = log(lanczos_sum(x)) - lanczos_g +
+ (x-0.5)*(log(x+lanczos_g-0.5)-1);
+ }
+ else {
+ r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
+ (log(lanczos_sum(absx)) - lanczos_g +
+ (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
+ }
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ return r;
}
/*
@@ -428,17 +428,17 @@ m_lgamma(double x)
static double
m_erf_series(double x)
{
- double x2, acc, fk;
- int i;
-
- x2 = x * x;
- acc = 0.0;
- fk = (double)ERF_SERIES_TERMS + 0.5;
- for (i = 0; i < ERF_SERIES_TERMS; i++) {
- acc = 2.0 + x2 * acc / fk;
- fk -= 1.0;
- }
- return acc * x * exp(-x2) / sqrtpi;
+ double x2, acc, fk;
+ int i;
+
+ x2 = x * x;
+ acc = 0.0;
+ fk = (double)ERF_SERIES_TERMS + 0.5;
+ for (i = 0; i < ERF_SERIES_TERMS; i++) {
+ acc = 2.0 + x2 * acc / fk;
+ fk -= 1.0;
+ }
+ return acc * x * exp(-x2) / sqrtpi;
}
/*
@@ -453,26 +453,26 @@ m_erf_series(double x)
static double
m_erfc_contfrac(double x)
{
- double x2, a, da, p, p_last, q, q_last, b;
- int i;
-
- if (x >= ERFC_CONTFRAC_CUTOFF)
- return 0.0;
-
- x2 = x*x;
- a = 0.0;
- da = 0.5;
- p = 1.0; p_last = 0.0;
- q = da + x2; q_last = 1.0;
- for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
- double temp;
- a += da;
- da += 2.0;
- b = da + x2;
- temp = p; p = b*p - a*p_last; p_last = temp;
- temp = q; q = b*q - a*q_last; q_last = temp;
- }
- return p / q * x * exp(-x2) / sqrtpi;
+ double x2, a, da, p, p_last, q, q_last, b;
+ int i;
+
+ if (x >= ERFC_CONTFRAC_CUTOFF)
+ return 0.0;
+
+ x2 = x*x;
+ a = 0.0;
+ da = 0.5;
+ p = 1.0; p_last = 0.0;
+ q = da + x2; q_last = 1.0;
+ for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
+ double temp;
+ a += da;
+ da += 2.0;
+ b = da + x2;
+ temp = p; p = b*p - a*p_last; p_last = temp;
+ temp = q; q = b*q - a*q_last; q_last = temp;
+ }
+ return p / q * x * exp(-x2) / sqrtpi;
}
/* Error function erf(x), for general x */
@@ -480,17 +480,17 @@ m_erfc_contfrac(double x)
static double
m_erf(double x)
{
- double absx, cf;
-
- if (Py_IS_NAN(x))
- return x;
- absx = fabs(x);
- if (absx < ERF_SERIES_CUTOFF)
- return m_erf_series(x);
- else {
- cf = m_erfc_contfrac(absx);
- return x > 0.0 ? 1.0 - cf : cf - 1.0;
- }
+ double absx, cf;
+
+ if (Py_IS_NAN(x))
+ return x;
+ absx = fabs(x);
+ if (absx < ERF_SERIES_CUTOFF)
+ return m_erf_series(x);
+ else {
+ cf = m_erfc_contfrac(absx);
+ return x > 0.0 ? 1.0 - cf : cf - 1.0;
+ }
}
/* Complementary error function erfc(x), for general x. */
@@ -498,17 +498,17 @@ m_erf(double x)
static double
m_erfc(double x)
{
- double absx, cf;
-
- if (Py_IS_NAN(x))
- return x;
- absx = fabs(x);
- if (absx < ERF_SERIES_CUTOFF)
- return 1.0 - m_erf_series(x);
- else {
- cf = m_erfc_contfrac(absx);
- return x > 0.0 ? cf : 2.0 - cf;
- }
+ double absx, cf;
+
+ if (Py_IS_NAN(x))
+ return x;
+ absx = fabs(x);
+ if (absx < ERF_SERIES_CUTOFF)
+ return 1.0 - m_erf_series(x);
+ else {
+ cf = m_erfc_contfrac(absx);
+ return x > 0.0 ? cf : 2.0 - cf;
+ }
}
/*
@@ -522,29 +522,29 @@ m_erfc(double x)
static double
m_atan2(double y, double x)
{
- if (Py_IS_NAN(x) || Py_IS_NAN(y))
- return Py_NAN;
- if (Py_IS_INFINITY(y)) {
- if (Py_IS_INFINITY(x)) {
- if (copysign(1., x) == 1.)
- /* atan2(+-inf, +inf) == +-pi/4 */
- return copysign(0.25*Py_MATH_PI, y);
- else
- /* atan2(+-inf, -inf) == +-pi*3/4 */
- return copysign(0.75*Py_MATH_PI, y);
- }
- /* atan2(+-inf, x) == +-pi/2 for finite x */
- return copysign(0.5*Py_MATH_PI, y);
- }
- if (Py_IS_INFINITY(x) || y == 0.) {
- if (copysign(1., x) == 1.)
- /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
- return copysign(0., y);
- else
- /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
- return copysign(Py_MATH_PI, y);
- }
- return atan2(y, x);
+ if (Py_IS_NAN(x) || Py_IS_NAN(y))
+ return Py_NAN;
+ if (Py_IS_INFINITY(y)) {
+ if (Py_IS_INFINITY(x)) {
+ if (copysign(1., x) == 1.)
+ /* atan2(+-inf, +inf) == +-pi/4 */
+ return copysign(0.25*Py_MATH_PI, y);
+ else
+ /* atan2(+-inf, -inf) == +-pi*3/4 */
+ return copysign(0.75*Py_MATH_PI, y);
+ }
+ /* atan2(+-inf, x) == +-pi/2 for finite x */
+ return copysign(0.5*Py_MATH_PI, y);
+ }
+ if (Py_IS_INFINITY(x) || y == 0.) {
+ if (copysign(1., x) == 1.)
+ /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
+ return copysign(0., y);
+ else
+ /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
+ return copysign(Py_MATH_PI, y);
+ }
+ return atan2(y, x);
}
/*
@@ -557,45 +557,45 @@ m_atan2(double y, double x)
static double
m_log(double x)
{
- if (Py_IS_FINITE(x)) {
- if (x > 0.0)
- return log(x);
- errno = EDOM;
- if (x == 0.0)
- return -Py_HUGE_VAL; /* log(0) = -inf */
- else
- return Py_NAN; /* log(-ve) = nan */
- }
- else if (Py_IS_NAN(x))
- return x; /* log(nan) = nan */
- else if (x > 0.0)
- return x; /* log(inf) = inf */
- else {
- errno = EDOM;
- return Py_NAN; /* log(-inf) = nan */
- }
+ if (Py_IS_FINITE(x)) {
+ if (x > 0.0)
+ return log(x);
+ errno = EDOM;
+ if (x == 0.0)
+ return -Py_HUGE_VAL; /* log(0) = -inf */
+ else
+ return Py_NAN; /* log(-ve) = nan */
+ }
+ else if (Py_IS_NAN(x))
+ return x; /* log(nan) = nan */
+ else if (x > 0.0)
+ return x; /* log(inf) = inf */
+ else {
+ errno = EDOM;
+ return Py_NAN; /* log(-inf) = nan */
+ }
}
static double
m_log10(double x)
{
- if (Py_IS_FINITE(x)) {
- if (x > 0.0)
- return log10(x);
- errno = EDOM;
- if (x == 0.0)
- return -Py_HUGE_VAL; /* log10(0) = -inf */
- else
- return Py_NAN; /* log10(-ve) = nan */
- }
- else if (Py_IS_NAN(x))
- return x; /* log10(nan) = nan */
- else if (x > 0.0)
- return x; /* log10(inf) = inf */
- else {
- errno = EDOM;
- return Py_NAN; /* log10(-inf) = nan */
- }
+ if (Py_IS_FINITE(x)) {
+ if (x > 0.0)
+ return log10(x);
+ errno = EDOM;
+ if (x == 0.0)
+ return -Py_HUGE_VAL; /* log10(0) = -inf */
+ else
+ return Py_NAN; /* log10(-ve) = nan */
+ }
+ else if (Py_IS_NAN(x))
+ return x; /* log10(nan) = nan */
+ else if (x > 0.0)
+ return x; /* log10(inf) = inf */
+ else {
+ errno = EDOM;
+ return Py_NAN; /* log10(-inf) = nan */
+ }
}
@@ -606,37 +606,37 @@ m_log10(double x)
static int
is_error(double x)
{
- int result = 1; /* presumption of guilt */
- assert(errno); /* non-zero errno is a precondition for calling */
- if (errno == EDOM)
- PyErr_SetString(PyExc_ValueError, "math domain error");
-
- else if (errno == ERANGE) {
- /* ANSI C generally requires libm functions to set ERANGE
- * on overflow, but also generally *allows* them to set
- * ERANGE on underflow too. There's no consistency about
- * the latter across platforms.
- * Alas, C99 never requires that errno be set.
- * Here we suppress the underflow errors (libm functions
- * should return a zero on underflow, and +- HUGE_VAL on
- * overflow, so testing the result for zero suffices to
- * distinguish the cases).
- *
- * On some platforms (Ubuntu/ia64) it seems that errno can be
- * set to ERANGE for subnormal results that do *not* underflow
- * to zero. So to be safe, we'll ignore ERANGE whenever the
- * function result is less than one in absolute value.
- */
- if (fabs(x) < 1.0)
- result = 0;
- else
- PyErr_SetString(PyExc_OverflowError,
- "math range error");
- }
- else
- /* Unexpected math error */
- PyErr_SetFromErrno(PyExc_ValueError);
- return result;
+ int result = 1; /* presumption of guilt */
+ assert(errno); /* non-zero errno is a precondition for calling */
+ if (errno == EDOM)
+ PyErr_SetString(PyExc_ValueError, "math domain error");
+
+ else if (errno == ERANGE) {
+ /* ANSI C generally requires libm functions to set ERANGE
+ * on overflow, but also generally *allows* them to set
+ * ERANGE on underflow too. There's no consistency about
+ * the latter across platforms.
+ * Alas, C99 never requires that errno be set.
+ * Here we suppress the underflow errors (libm functions
+ * should return a zero on underflow, and +- HUGE_VAL on
+ * overflow, so testing the result for zero suffices to
+ * distinguish the cases).
+ *
+ * On some platforms (Ubuntu/ia64) it seems that errno can be
+ * set to ERANGE for subnormal results that do *not* underflow
+ * to zero. So to be safe, we'll ignore ERANGE whenever the
+ * function result is less than one in absolute value.
+ */
+ if (fabs(x) < 1.0)
+ result = 0;
+ else
+ PyErr_SetString(PyExc_OverflowError,
+ "math range error");
+ }
+ else
+ /* Unexpected math error */
+ PyErr_SetFromErrno(PyExc_ValueError);
+ return result;
}
/*
@@ -674,33 +674,33 @@ math_1_to_whatever(PyObject *arg, double (*func) (double),
PyObject *(*from_double_func) (double),
int can_overflow)
{
- double x, r;
- x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("in math_1", return 0);
- r = (*func)(x);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
- PyErr_SetString(PyExc_ValueError,
- "math domain error"); /* invalid arg */
- return NULL;
- }
- if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
- if (can_overflow)
- PyErr_SetString(PyExc_OverflowError,
- "math range error"); /* overflow */
- else
- PyErr_SetString(PyExc_ValueError,
- "math domain error"); /* singularity */
- return NULL;
- }
- if (Py_IS_FINITE(r) && errno && is_error(r))
- /* this branch unnecessary on most platforms */
- return NULL;
-
- return (*from_double_func)(r);
+ double x, r;
+ x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("in math_1", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
+ PyErr_SetString(PyExc_ValueError,
+ "math domain error"); /* invalid arg */
+ return NULL;
+ }
+ if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
+ if (can_overflow)
+ PyErr_SetString(PyExc_OverflowError,
+ "math range error"); /* overflow */
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "math domain error"); /* singularity */
+ return NULL;
+ }
+ if (Py_IS_FINITE(r) && errno && is_error(r))
+ /* this branch unnecessary on most platforms */
+ return NULL;
+
+ return (*from_double_func)(r);
}
/* variant of math_1, to be used when the function being wrapped is known to
@@ -710,17 +710,17 @@ math_1_to_whatever(PyObject *arg, double (*func) (double),
static PyObject *
math_1a(PyObject *arg, double (*func) (double))
{
- double x, r;
- x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("in math_1a", return 0);
- r = (*func)(x);
- PyFPE_END_PROTECT(r);
- if (errno && is_error(r))
- return NULL;
- return PyFloat_FromDouble(r);
+ double x, r;
+ x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("in math_1a", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (errno && is_error(r))
+ return NULL;
+ return PyFloat_FromDouble(r);
}
/*
@@ -753,65 +753,65 @@ math_1a(PyObject *arg, double (*func) (double))
static PyObject *
math_1(PyObject *arg, double (*func) (double), int can_overflow)
{
- return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
+ return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
}
static PyObject *
math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
{
- return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
+ return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
}
static PyObject *
math_2(PyObject *args, double (*func) (double, double), char *funcname)
{
- PyObject *ox, *oy;
- double x, y, r;
- if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("in math_2", return 0);
- r = (*func)(x, y);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
- errno = EDOM;
- else
- errno = 0;
- }
- else if (Py_IS_INFINITY(r)) {
- if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
- errno = ERANGE;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double x, y, r;
+ if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("in math_2", return 0);
+ r = (*func)(x, y);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else if (Py_IS_INFINITY(r)) {
+ if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
+ errno = ERANGE;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
-#define FUNC1(funcname, func, can_overflow, docstring) \
- static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
- return math_1(args, func, can_overflow); \
- }\
- PyDoc_STRVAR(math_##funcname##_doc, docstring);
+#define FUNC1(funcname, func, can_overflow, docstring) \
+ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
+ return math_1(args, func, can_overflow); \
+ }\
+ PyDoc_STRVAR(math_##funcname##_doc, docstring);
-#define FUNC1A(funcname, func, docstring) \
- static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
- return math_1a(args, func); \
- }\
- PyDoc_STRVAR(math_##funcname##_doc, docstring);
+#define FUNC1A(funcname, func, docstring) \
+ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
+ return math_1a(args, func); \
+ }\
+ PyDoc_STRVAR(math_##funcname##_doc, docstring);
#define FUNC2(funcname, func, docstring) \
- static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
- return math_2(args, func, #funcname); \
- }\
- PyDoc_STRVAR(math_##funcname##_doc, docstring);
+ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
+ return math_2(args, func, #funcname); \
+ }\
+ PyDoc_STRVAR(math_##funcname##_doc, docstring);
FUNC1(acos, acos, 0,
"acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
@@ -830,25 +830,25 @@ FUNC1(atanh, m_atanh, 0,
"atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
static PyObject * math_ceil(PyObject *self, PyObject *number) {
- static PyObject *ceil_str = NULL;
- PyObject *method;
-
- if (ceil_str == NULL) {
- ceil_str = PyUnicode_InternFromString("__ceil__");
- if (ceil_str == NULL)
- return NULL;
- }
-
- method = _PyType_Lookup(Py_TYPE(number), ceil_str);
- if (method == NULL)
- return math_1_to_int(number, ceil, 0);
- else
- return PyObject_CallFunction(method, "O", number);
+ static PyObject *ceil_str = NULL;
+ PyObject *method;
+
+ if (ceil_str == NULL) {
+ ceil_str = PyUnicode_InternFromString("__ceil__");
+ if (ceil_str == NULL)
+ return NULL;
+ }
+
+ method = _PyType_Lookup(Py_TYPE(number), ceil_str);
+ if (method == NULL)
+ return math_1_to_int(number, ceil, 0);
+ else
+ return PyObject_CallFunction(method, "O", number);
}
PyDoc_STRVAR(math_ceil_doc,
- "ceil(x)\n\nReturn the ceiling of x as an int.\n"
- "This is the smallest integral value >= x.");
+ "ceil(x)\n\nReturn the ceiling of x as an int.\n"
+ "This is the smallest integral value >= x.");
FUNC2(copysign, copysign,
"copysign(x, y)\n\nReturn x with the sign of y.")
@@ -870,25 +870,25 @@ FUNC1(fabs, fabs, 0,
"fabs(x)\n\nReturn the absolute value of the float x.")
static PyObject * math_floor(PyObject *self, PyObject *number) {
- static PyObject *floor_str = NULL;
- PyObject *method;
-
- if (floor_str == NULL) {
- floor_str = PyUnicode_InternFromString("__floor__");
- if (floor_str == NULL)
- return NULL;
- }
-
- method = _PyType_Lookup(Py_TYPE(number), floor_str);
- if (method == NULL)
- return math_1_to_int(number, floor, 0);
- else
- return PyObject_CallFunction(method, "O", number);
+ static PyObject *floor_str = NULL;
+ PyObject *method;
+
+ if (floor_str == NULL) {
+ floor_str = PyUnicode_InternFromString("__floor__");
+ if (floor_str == NULL)
+ return NULL;
+ }
+
+ method = _PyType_Lookup(Py_TYPE(number), floor_str);
+ if (method == NULL)
+ return math_1_to_int(number, floor, 0);
+ else
+ return PyObject_CallFunction(method, "O", number);
}
PyDoc_STRVAR(math_floor_doc,
- "floor(x)\n\nReturn the floor of x as an int.\n"
- "This is the largest integral value <= x.");
+ "floor(x)\n\nReturn the floor of x as an int.\n"
+ "This is the largest integral value <= x.");
FUNC1A(gamma, m_tgamma,
"gamma(x)\n\nGamma function at x.")
@@ -928,7 +928,7 @@ FUNC1(tanh, tanh, 0,
Also, the volatile declaration forces the values to be stored in memory as
regular doubles instead of extended long precision (80-bit) values. This
prevents double rounding because any addition or subtraction of two doubles
- can be resolved exactly into double-sized hi and lo values. As long as the
+ can be resolved exactly into double-sized hi and lo values. As long as the
hi value gets forced into a double before yr and lo are computed, the extra
bits in downstream extended precision operations (x87 for example) will be
exactly zero and therefore can be losslessly stored back into a double,
@@ -951,27 +951,27 @@ static int /* non-zero on error */
_fsum_realloc(double **p_ptr, Py_ssize_t n,
double *ps, Py_ssize_t *m_ptr)
{
- void *v = NULL;
- Py_ssize_t m = *m_ptr;
-
- m += m; /* double */
- if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
- double *p = *p_ptr;
- if (p == ps) {
- v = PyMem_Malloc(sizeof(double) * m);
- if (v != NULL)
- memcpy(v, ps, sizeof(double) * n);
- }
- else
- v = PyMem_Realloc(p, sizeof(double) * m);
- }
- if (v == NULL) { /* size overflow or no memory */
- PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
- return 1;
- }
- *p_ptr = (double*) v;
- *m_ptr = m;
- return 0;
+ void *v = NULL;
+ Py_ssize_t m = *m_ptr;
+
+ m += m; /* double */
+ if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
+ double *p = *p_ptr;
+ if (p == ps) {
+ v = PyMem_Malloc(sizeof(double) * m);
+ if (v != NULL)
+ memcpy(v, ps, sizeof(double) * n);
+ }
+ else
+ v = PyMem_Realloc(p, sizeof(double) * m);
+ }
+ if (v == NULL) { /* size overflow or no memory */
+ PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
+ return 1;
+ }
+ *p_ptr = (double*) v;
+ *m_ptr = m;
+ return 0;
}
/* Full precision summation of a sequence of floats.
@@ -979,17 +979,17 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n,
def msum(iterable):
partials = [] # sorted, non-overlapping partial sums
for x in iterable:
- i = 0
- for y in partials:
- if abs(x) < abs(y):
- x, y = y, x
- hi = x + y
- lo = y - (hi - x)
- if lo:
- partials[i] = lo
- i += 1
- x = hi
- partials[i:] = [x]
+ i = 0
+ for y in partials:
+ if abs(x) < abs(y):
+ x, y = y, x
+ hi = x + y
+ lo = y - (hi - x)
+ if lo:
+ partials[i] = lo
+ i += 1
+ x = hi
+ partials[i:] = [x]
return sum_exact(partials)
Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
@@ -1007,119 +1007,119 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n,
static PyObject*
math_fsum(PyObject *self, PyObject *seq)
{
- PyObject *item, *iter, *sum = NULL;
- Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
- double x, y, t, ps[NUM_PARTIALS], *p = ps;
- double xsave, special_sum = 0.0, inf_sum = 0.0;
- volatile double hi, yr, lo;
-
- iter = PyObject_GetIter(seq);
- if (iter == NULL)
- return NULL;
-
- PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
-
- for(;;) { /* for x in iterable */
- assert(0 <= n && n <= m);
- assert((m == NUM_PARTIALS && p == ps) ||
- (m > NUM_PARTIALS && p != NULL));
-
- item = PyIter_Next(iter);
- if (item == NULL) {
- if (PyErr_Occurred())
- goto _fsum_error;
- break;
- }
- x = PyFloat_AsDouble(item);
- Py_DECREF(item);
- if (PyErr_Occurred())
- goto _fsum_error;
-
- xsave = x;
- for (i = j = 0; j < n; j++) { /* for y in partials */
- y = p[j];
- if (fabs(x) < fabs(y)) {
- t = x; x = y; y = t;
- }
- hi = x + y;
- yr = hi - x;
- lo = y - yr;
- if (lo != 0.0)
- p[i++] = lo;
- x = hi;
- }
-
- n = i; /* ps[i:] = [x] */
- if (x != 0.0) {
- if (! Py_IS_FINITE(x)) {
- /* a nonfinite x could arise either as
- a result of intermediate overflow, or
- as a result of a nan or inf in the
- summands */
- if (Py_IS_FINITE(xsave)) {
- PyErr_SetString(PyExc_OverflowError,
- "intermediate overflow in fsum");
- goto _fsum_error;
- }
- if (Py_IS_INFINITY(xsave))
- inf_sum += xsave;
- special_sum += xsave;
- /* reset partials */
- n = 0;
- }
- else if (n >= m && _fsum_realloc(&p, n, ps, &m))
- goto _fsum_error;
- else
- p[n++] = x;
- }
- }
-
- if (special_sum != 0.0) {
- if (Py_IS_NAN(inf_sum))
- PyErr_SetString(PyExc_ValueError,
- "-inf + inf in fsum");
- else
- sum = PyFloat_FromDouble(special_sum);
- goto _fsum_error;
- }
-
- hi = 0.0;
- if (n > 0) {
- hi = p[--n];
- /* sum_exact(ps, hi) from the top, stop when the sum becomes
- inexact. */
- while (n > 0) {
- x = hi;
- y = p[--n];
- assert(fabs(y) < fabs(x));
- hi = x + y;
- yr = hi - x;
- lo = y - yr;
- if (lo != 0.0)
- break;
- }
- /* Make half-even rounding work across multiple partials.
- Needed so that sum([1e-16, 1, 1e16]) will round-up the last
- digit to two instead of down to zero (the 1e-16 makes the 1
- slightly closer to two). With a potential 1 ULP rounding
- error fixed-up, math.fsum() can guarantee commutativity. */
- if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
- (lo > 0.0 && p[n-1] > 0.0))) {
- y = lo * 2.0;
- x = hi + y;
- yr = x - hi;
- if (y == yr)
- hi = x;
- }
- }
- sum = PyFloat_FromDouble(hi);
+ PyObject *item, *iter, *sum = NULL;
+ Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
+ double x, y, t, ps[NUM_PARTIALS], *p = ps;
+ double xsave, special_sum = 0.0, inf_sum = 0.0;
+ volatile double hi, yr, lo;
+
+ iter = PyObject_GetIter(seq);
+ if (iter == NULL)
+ return NULL;
+
+ PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
+
+ for(;;) { /* for x in iterable */
+ assert(0 <= n && n <= m);
+ assert((m == NUM_PARTIALS && p == ps) ||
+ (m > NUM_PARTIALS && p != NULL));
+
+ item = PyIter_Next(iter);
+ if (item == NULL) {
+ if (PyErr_Occurred())
+ goto _fsum_error;
+ break;
+ }
+ x = PyFloat_AsDouble(item);
+ Py_DECREF(item);
+ if (PyErr_Occurred())
+ goto _fsum_error;
+
+ xsave = x;
+ for (i = j = 0; j < n; j++) { /* for y in partials */
+ y = p[j];
+ if (fabs(x) < fabs(y)) {
+ t = x; x = y; y = t;
+ }
+ hi = x + y;
+ yr = hi - x;
+ lo = y - yr;
+ if (lo != 0.0)
+ p[i++] = lo;
+ x = hi;
+ }
+
+ n = i; /* ps[i:] = [x] */
+ if (x != 0.0) {
+ if (! Py_IS_FINITE(x)) {
+ /* a nonfinite x could arise either as
+ a result of intermediate overflow, or
+ as a result of a nan or inf in the
+ summands */
+ if (Py_IS_FINITE(xsave)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "intermediate overflow in fsum");
+ goto _fsum_error;
+ }
+ if (Py_IS_INFINITY(xsave))
+ inf_sum += xsave;
+ special_sum += xsave;
+ /* reset partials */
+ n = 0;
+ }
+ else if (n >= m && _fsum_realloc(&p, n, ps, &m))
+ goto _fsum_error;
+ else
+ p[n++] = x;
+ }
+ }
+
+ if (special_sum != 0.0) {
+ if (Py_IS_NAN(inf_sum))
+ PyErr_SetString(PyExc_ValueError,
+ "-inf + inf in fsum");
+ else
+ sum = PyFloat_FromDouble(special_sum);
+ goto _fsum_error;
+ }
+
+ hi = 0.0;
+ if (n > 0) {
+ hi = p[--n];
+ /* sum_exact(ps, hi) from the top, stop when the sum becomes
+ inexact. */
+ while (n > 0) {
+ x = hi;
+ y = p[--n];
+ assert(fabs(y) < fabs(x));
+ hi = x + y;
+ yr = hi - x;
+ lo = y - yr;
+ if (lo != 0.0)
+ break;
+ }
+ /* Make half-even rounding work across multiple partials.
+ Needed so that sum([1e-16, 1, 1e16]) will round-up the last
+ digit to two instead of down to zero (the 1e-16 makes the 1
+ slightly closer to two). With a potential 1 ULP rounding
+ error fixed-up, math.fsum() can guarantee commutativity. */
+ if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
+ (lo > 0.0 && p[n-1] > 0.0))) {
+ y = lo * 2.0;
+ x = hi + y;
+ yr = x - hi;
+ if (y == yr)
+ hi = x;
+ }
+ }
+ sum = PyFloat_FromDouble(hi);
_fsum_error:
- PyFPE_END_PROTECT(hi)
- Py_DECREF(iter);
- if (p != ps)
- PyMem_Free(p);
- return sum;
+ PyFPE_END_PROTECT(hi)
+ Py_DECREF(iter);
+ if (p != ps)
+ PyMem_Free(p);
+ return sum;
}
#undef NUM_PARTIALS
@@ -1132,53 +1132,53 @@ Assumes IEEE-754 floating point arithmetic.");
static PyObject *
math_factorial(PyObject *self, PyObject *arg)
{
- long i, x;
- PyObject *result, *iobj, *newresult;
-
- if (PyFloat_Check(arg)) {
- PyObject *lx;
- double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
- if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
- PyErr_SetString(PyExc_ValueError,
- "factorial() only accepts integral values");
- return NULL;
- }
- lx = PyLong_FromDouble(dx);
- if (lx == NULL)
- return NULL;
- x = PyLong_AsLong(lx);
- Py_DECREF(lx);
- }
- else
- x = PyLong_AsLong(arg);
-
- if (x == -1 && PyErr_Occurred())
- return NULL;
- if (x < 0) {
- PyErr_SetString(PyExc_ValueError,
- "factorial() not defined for negative values");
- return NULL;
- }
-
- result = (PyObject *)PyLong_FromLong(1);
- if (result == NULL)
- return NULL;
- for (i=1 ; i<=x ; i++) {
- iobj = (PyObject *)PyLong_FromLong(i);
- if (iobj == NULL)
- goto error;
- newresult = PyNumber_Multiply(result, iobj);
- Py_DECREF(iobj);
- if (newresult == NULL)
- goto error;
- Py_DECREF(result);
- result = newresult;
- }
- return result;
+ long i, x;
+ PyObject *result, *iobj, *newresult;
+
+ if (PyFloat_Check(arg)) {
+ PyObject *lx;
+ double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
+ if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
+ PyErr_SetString(PyExc_ValueError,
+ "factorial() only accepts integral values");
+ return NULL;
+ }
+ lx = PyLong_FromDouble(dx);
+ if (lx == NULL)
+ return NULL;
+ x = PyLong_AsLong(lx);
+ Py_DECREF(lx);
+ }
+ else
+ x = PyLong_AsLong(arg);
+
+ if (x == -1 && PyErr_Occurred())
+ return NULL;
+ if (x < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "factorial() not defined for negative values");
+ return NULL;
+ }
+
+ result = (PyObject *)PyLong_FromLong(1);
+ if (result == NULL)
+ return NULL;
+ for (i=1 ; i<=x ; i++) {
+ iobj = (PyObject *)PyLong_FromLong(i);
+ if (iobj == NULL)
+ goto error;
+ newresult = PyNumber_Multiply(result, iobj);
+ Py_DECREF(iobj);
+ if (newresult == NULL)
+ goto error;
+ Py_DECREF(result);
+ result = newresult;
+ }
+ return result;
error:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
PyDoc_STRVAR(math_factorial_doc,
@@ -1189,28 +1189,28 @@ PyDoc_STRVAR(math_factorial_doc,
static PyObject *
math_trunc(PyObject *self, PyObject *number)
{
- static PyObject *trunc_str = NULL;
- PyObject *trunc;
-
- if (Py_TYPE(number)->tp_dict == NULL) {
- if (PyType_Ready(Py_TYPE(number)) < 0)
- return NULL;
- }
-
- if (trunc_str == NULL) {
- trunc_str = PyUnicode_InternFromString("__trunc__");
- if (trunc_str == NULL)
- return NULL;
- }
-
- trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
- if (trunc == NULL) {
- PyErr_Format(PyExc_TypeError,
- "type %.100s doesn't define __trunc__ method",
- Py_TYPE(number)->tp_name);
- return NULL;
- }
- return PyObject_CallFunctionObjArgs(trunc, number, NULL);
+ static PyObject *trunc_str = NULL;
+ PyObject *trunc;
+
+ if (Py_TYPE(number)->tp_dict == NULL) {
+ if (PyType_Ready(Py_TYPE(number)) < 0)
+ return NULL;
+ }
+
+ if (trunc_str == NULL) {
+ trunc_str = PyUnicode_InternFromString("__trunc__");
+ if (trunc_str == NULL)
+ return NULL;
+ }
+
+ trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
+ if (trunc == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "type %.100s doesn't define __trunc__ method",
+ Py_TYPE(number)->tp_name);
+ return NULL;
+ }
+ return PyObject_CallFunctionObjArgs(trunc, number, NULL);
}
PyDoc_STRVAR(math_trunc_doc,
@@ -1221,21 +1221,21 @@ PyDoc_STRVAR(math_trunc_doc,
static PyObject *
math_frexp(PyObject *self, PyObject *arg)
{
- int i;
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- /* deal with special cases directly, to sidestep platform
- differences */
- if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
- i = 0;
- }
- else {
- PyFPE_START_PROTECT("in math_frexp", return 0);
- x = frexp(x, &i);
- PyFPE_END_PROTECT(x);
- }
- return Py_BuildValue("(di)", x, i);
+ int i;
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ /* deal with special cases directly, to sidestep platform
+ differences */
+ if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
+ i = 0;
+ }
+ else {
+ PyFPE_START_PROTECT("in math_frexp", return 0);
+ x = frexp(x, &i);
+ PyFPE_END_PROTECT(x);
+ }
+ return Py_BuildValue("(di)", x, i);
}
PyDoc_STRVAR(math_frexp_doc,
@@ -1248,53 +1248,53 @@ PyDoc_STRVAR(math_frexp_doc,
static PyObject *
math_ldexp(PyObject *self, PyObject *args)
{
- double x, r;
- PyObject *oexp;
- long exp;
- int overflow;
- if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
- return NULL;
-
- if (PyLong_Check(oexp)) {
- /* on overflow, replace exponent with either LONG_MAX
- or LONG_MIN, depending on the sign. */
- exp = PyLong_AsLongAndOverflow(oexp, &overflow);
- if (exp == -1 && PyErr_Occurred())
- return NULL;
- if (overflow)
- exp = overflow < 0 ? LONG_MIN : LONG_MAX;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "Expected an int or long as second argument "
- "to ldexp.");
- return NULL;
- }
-
- if (x == 0. || !Py_IS_FINITE(x)) {
- /* NaNs, zeros and infinities are returned unchanged */
- r = x;
- errno = 0;
- } else if (exp > INT_MAX) {
- /* overflow */
- r = copysign(Py_HUGE_VAL, x);
- errno = ERANGE;
- } else if (exp < INT_MIN) {
- /* underflow to +-0 */
- r = copysign(0., x);
- errno = 0;
- } else {
- errno = 0;
- PyFPE_START_PROTECT("in math_ldexp", return 0);
- r = ldexp(x, (int)exp);
- PyFPE_END_PROTECT(r);
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- }
-
- if (errno && is_error(r))
- return NULL;
- return PyFloat_FromDouble(r);
+ double x, r;
+ PyObject *oexp;
+ long exp;
+ int overflow;
+ if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
+ return NULL;
+
+ if (PyLong_Check(oexp)) {
+ /* on overflow, replace exponent with either LONG_MAX
+ or LONG_MIN, depending on the sign. */
+ exp = PyLong_AsLongAndOverflow(oexp, &overflow);
+ if (exp == -1 && PyErr_Occurred())
+ return NULL;
+ if (overflow)
+ exp = overflow < 0 ? LONG_MIN : LONG_MAX;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected an int or long as second argument "
+ "to ldexp.");
+ return NULL;
+ }
+
+ if (x == 0. || !Py_IS_FINITE(x)) {
+ /* NaNs, zeros and infinities are returned unchanged */
+ r = x;
+ errno = 0;
+ } else if (exp > INT_MAX) {
+ /* overflow */
+ r = copysign(Py_HUGE_VAL, x);
+ errno = ERANGE;
+ } else if (exp < INT_MIN) {
+ /* underflow to +-0 */
+ r = copysign(0., x);
+ errno = 0;
+ } else {
+ errno = 0;
+ PyFPE_START_PROTECT("in math_ldexp", return 0);
+ r = ldexp(x, (int)exp);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ }
+
+ if (errno && is_error(r))
+ return NULL;
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_ldexp_doc,
@@ -1304,23 +1304,23 @@ Return x * (2**i).");
static PyObject *
math_modf(PyObject *self, PyObject *arg)
{
- double y, x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- /* some platforms don't do the right thing for NaNs and
- infinities, so we take care of special cases directly. */
- if (!Py_IS_FINITE(x)) {
- if (Py_IS_INFINITY(x))
- return Py_BuildValue("(dd)", copysign(0., x), x);
- else if (Py_IS_NAN(x))
- return Py_BuildValue("(dd)", x, x);
- }
-
- errno = 0;
- PyFPE_START_PROTECT("in math_modf", return 0);
- x = modf(x, &y);
- PyFPE_END_PROTECT(x);
- return Py_BuildValue("(dd)", x, y);
+ double y, x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ /* some platforms don't do the right thing for NaNs and
+ infinities, so we take care of special cases directly. */
+ if (!Py_IS_FINITE(x)) {
+ if (Py_IS_INFINITY(x))
+ return Py_BuildValue("(dd)", copysign(0., x), x);
+ else if (Py_IS_NAN(x))
+ return Py_BuildValue("(dd)", x, x);
+ }
+
+ errno = 0;
+ PyFPE_START_PROTECT("in math_modf", return 0);
+ x = modf(x, &y);
+ PyFPE_END_PROTECT(x);
+ return Py_BuildValue("(dd)", x, y);
}
PyDoc_STRVAR(math_modf_doc,
@@ -1341,56 +1341,56 @@ PyDoc_STRVAR(math_modf_doc,
static PyObject*
loghelper(PyObject* arg, double (*func)(double), char *funcname)
{
- /* If it is long, do it ourselves. */
- if (PyLong_Check(arg)) {
- double x;
- Py_ssize_t e;
- x = _PyLong_Frexp((PyLongObject *)arg, &e);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- if (x <= 0.0) {
- PyErr_SetString(PyExc_ValueError,
- "math domain error");
- return NULL;
- }
- /* Special case for log(1), to make sure we get an
- exact result there. */
- if (e == 1 && x == 0.5)
- return PyFloat_FromDouble(0.0);
- /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
- x = func(x) + func(2.0) * e;
- return PyFloat_FromDouble(x);
- }
-
- /* Else let libm handle it by itself. */
- return math_1(arg, func, 0);
+ /* If it is long, do it ourselves. */
+ if (PyLong_Check(arg)) {
+ double x;
+ Py_ssize_t e;
+ x = _PyLong_Frexp((PyLongObject *)arg, &e);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ if (x <= 0.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "math domain error");
+ return NULL;
+ }
+ /* Special case for log(1), to make sure we get an
+ exact result there. */
+ if (e == 1 && x == 0.5)
+ return PyFloat_FromDouble(0.0);
+ /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
+ x = func(x) + func(2.0) * e;
+ return PyFloat_FromDouble(x);
+ }
+
+ /* Else let libm handle it by itself. */
+ return math_1(arg, func, 0);
}
static PyObject *
math_log(PyObject *self, PyObject *args)
{
- PyObject *arg;
- PyObject *base = NULL;
- PyObject *num, *den;
- PyObject *ans;
-
- if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
- return NULL;
-
- num = loghelper(arg, m_log, "log");
- if (num == NULL || base == NULL)
- return num;
-
- den = loghelper(base, m_log, "log");
- if (den == NULL) {
- Py_DECREF(num);
- return NULL;
- }
-
- ans = PyNumber_TrueDivide(num, den);
- Py_DECREF(num);
- Py_DECREF(den);
- return ans;
+ PyObject *arg;
+ PyObject *base = NULL;
+ PyObject *num, *den;
+ PyObject *ans;
+
+ if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
+ return NULL;
+
+ num = loghelper(arg, m_log, "log");
+ if (num == NULL || base == NULL)
+ return num;
+
+ den = loghelper(base, m_log, "log");
+ if (den == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+
+ ans = PyNumber_TrueDivide(num, den);
+ Py_DECREF(num);
+ Py_DECREF(den);
+ return ans;
}
PyDoc_STRVAR(math_log_doc,
@@ -1401,7 +1401,7 @@ If the base not specified, returns the natural logarithm (base e) of x.");
static PyObject *
math_log10(PyObject *self, PyObject *arg)
{
- return loghelper(arg, m_log10, "log10");
+ return loghelper(arg, m_log10, "log10");
}
PyDoc_STRVAR(math_log10_doc,
@@ -1410,31 +1410,31 @@ PyDoc_STRVAR(math_log10_doc,
static PyObject *
math_fmod(PyObject *self, PyObject *args)
{
- PyObject *ox, *oy;
- double r, x, y;
- if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
- /* fmod(x, +/-Inf) returns x for finite x. */
- if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
- return PyFloat_FromDouble(x);
- errno = 0;
- PyFPE_START_PROTECT("in math_fmod", return 0);
- r = fmod(x, y);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
- errno = EDOM;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double r, x, y;
+ if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+ /* fmod(x, +/-Inf) returns x for finite x. */
+ if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
+ return PyFloat_FromDouble(x);
+ errno = 0;
+ PyFPE_START_PROTECT("in math_fmod", return 0);
+ r = fmod(x, y);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_fmod_doc,
@@ -1444,39 +1444,39 @@ PyDoc_STRVAR(math_fmod_doc,
static PyObject *
math_hypot(PyObject *self, PyObject *args)
{
- PyObject *ox, *oy;
- double r, x, y;
- if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
- /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
- if (Py_IS_INFINITY(x))
- return PyFloat_FromDouble(fabs(x));
- if (Py_IS_INFINITY(y))
- return PyFloat_FromDouble(fabs(y));
- errno = 0;
- PyFPE_START_PROTECT("in math_hypot", return 0);
- r = hypot(x, y);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
- errno = EDOM;
- else
- errno = 0;
- }
- else if (Py_IS_INFINITY(r)) {
- if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
- errno = ERANGE;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double r, x, y;
+ if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+ /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
+ if (Py_IS_INFINITY(x))
+ return PyFloat_FromDouble(fabs(x));
+ if (Py_IS_INFINITY(y))
+ return PyFloat_FromDouble(fabs(y));
+ errno = 0;
+ PyFPE_START_PROTECT("in math_hypot", return 0);
+ r = hypot(x, y);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else if (Py_IS_INFINITY(r)) {
+ if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
+ errno = ERANGE;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_hypot_doc,
@@ -1491,79 +1491,79 @@ PyDoc_STRVAR(math_hypot_doc,
static PyObject *
math_pow(PyObject *self, PyObject *args)
{
- PyObject *ox, *oy;
- double r, x, y;
- int odd_y;
-
- if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
-
- /* deal directly with IEEE specials, to cope with problems on various
- platforms whose semantics don't exactly match C99 */
- r = 0.; /* silence compiler warning */
- if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
- errno = 0;
- if (Py_IS_NAN(x))
- r = y == 0. ? 1. : x; /* NaN**0 = 1 */
- else if (Py_IS_NAN(y))
- r = x == 1. ? 1. : y; /* 1**NaN = 1 */
- else if (Py_IS_INFINITY(x)) {
- odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
- if (y > 0.)
- r = odd_y ? x : fabs(x);
- else if (y == 0.)
- r = 1.;
- else /* y < 0. */
- r = odd_y ? copysign(0., x) : 0.;
- }
- else if (Py_IS_INFINITY(y)) {
- if (fabs(x) == 1.0)
- r = 1.;
- else if (y > 0. && fabs(x) > 1.0)
- r = y;
- else if (y < 0. && fabs(x) < 1.0) {
- r = -y; /* result is +inf */
- if (x == 0.) /* 0**-inf: divide-by-zero */
- errno = EDOM;
- }
- else
- r = 0.;
- }
- }
- else {
- /* let libm handle finite**finite */
- errno = 0;
- PyFPE_START_PROTECT("in math_pow", return 0);
- r = pow(x, y);
- PyFPE_END_PROTECT(r);
- /* a NaN result should arise only from (-ve)**(finite
- non-integer); in this case we want to raise ValueError. */
- if (!Py_IS_FINITE(r)) {
- if (Py_IS_NAN(r)) {
- errno = EDOM;
- }
- /*
- an infinite result here arises either from:
- (A) (+/-0.)**negative (-> divide-by-zero)
- (B) overflow of x**y with x and y finite
- */
- else if (Py_IS_INFINITY(r)) {
- if (x == 0.)
- errno = EDOM;
- else
- errno = ERANGE;
- }
- }
- }
-
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double r, x, y;
+ int odd_y;
+
+ if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+
+ /* deal directly with IEEE specials, to cope with problems on various
+ platforms whose semantics don't exactly match C99 */
+ r = 0.; /* silence compiler warning */
+ if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
+ errno = 0;
+ if (Py_IS_NAN(x))
+ r = y == 0. ? 1. : x; /* NaN**0 = 1 */
+ else if (Py_IS_NAN(y))
+ r = x == 1. ? 1. : y; /* 1**NaN = 1 */
+ else if (Py_IS_INFINITY(x)) {
+ odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
+ if (y > 0.)
+ r = odd_y ? x : fabs(x);
+ else if (y == 0.)
+ r = 1.;
+ else /* y < 0. */
+ r = odd_y ? copysign(0., x) : 0.;
+ }
+ else if (Py_IS_INFINITY(y)) {
+ if (fabs(x) == 1.0)
+ r = 1.;
+ else if (y > 0. && fabs(x) > 1.0)
+ r = y;
+ else if (y < 0. && fabs(x) < 1.0) {
+ r = -y; /* result is +inf */
+ if (x == 0.) /* 0**-inf: divide-by-zero */
+ errno = EDOM;
+ }
+ else
+ r = 0.;
+ }
+ }
+ else {
+ /* let libm handle finite**finite */
+ errno = 0;
+ PyFPE_START_PROTECT("in math_pow", return 0);
+ r = pow(x, y);
+ PyFPE_END_PROTECT(r);
+ /* a NaN result should arise only from (-ve)**(finite
+ non-integer); in this case we want to raise ValueError. */
+ if (!Py_IS_FINITE(r)) {
+ if (Py_IS_NAN(r)) {
+ errno = EDOM;
+ }
+ /*
+ an infinite result here arises either from:
+ (A) (+/-0.)**negative (-> divide-by-zero)
+ (B) overflow of x**y with x and y finite
+ */
+ else if (Py_IS_INFINITY(r)) {
+ if (x == 0.)
+ errno = EDOM;
+ else
+ errno = ERANGE;
+ }
+ }
+ }
+
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_pow_doc,
@@ -1575,10 +1575,10 @@ static const double radToDeg = 180.0 / Py_MATH_PI;
static PyObject *
math_degrees(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x * radToDeg);
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x * radToDeg);
}
PyDoc_STRVAR(math_degrees_doc,
@@ -1588,10 +1588,10 @@ Convert angle x from radians to degrees.");
static PyObject *
math_radians(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x * degToRad);
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x * degToRad);
}
PyDoc_STRVAR(math_radians_doc,
@@ -1601,10 +1601,10 @@ Convert angle x from degrees to radians.");
static PyObject *
math_isnan(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_NAN(x));
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_NAN(x));
}
PyDoc_STRVAR(math_isnan_doc,
@@ -1614,10 +1614,10 @@ Check if float x is not a number (NaN).");
static PyObject *
math_isinf(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_INFINITY(x));
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_INFINITY(x));
}
PyDoc_STRVAR(math_isinf_doc,
@@ -1625,47 +1625,47 @@ PyDoc_STRVAR(math_isinf_doc,
Check if float x is infinite (positive or negative).");
static PyMethodDef math_methods[] = {
- {"acos", math_acos, METH_O, math_acos_doc},
- {"acosh", math_acosh, METH_O, math_acosh_doc},
- {"asin", math_asin, METH_O, math_asin_doc},
- {"asinh", math_asinh, METH_O, math_asinh_doc},
- {"atan", math_atan, METH_O, math_atan_doc},
- {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
- {"atanh", math_atanh, METH_O, math_atanh_doc},
- {"ceil", math_ceil, METH_O, math_ceil_doc},
- {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
- {"cos", math_cos, METH_O, math_cos_doc},
- {"cosh", math_cosh, METH_O, math_cosh_doc},
- {"degrees", math_degrees, METH_O, math_degrees_doc},
- {"erf", math_erf, METH_O, math_erf_doc},
- {"erfc", math_erfc, METH_O, math_erfc_doc},
- {"exp", math_exp, METH_O, math_exp_doc},
- {"expm1", math_expm1, METH_O, math_expm1_doc},
- {"fabs", math_fabs, METH_O, math_fabs_doc},
- {"factorial", math_factorial, METH_O, math_factorial_doc},
- {"floor", math_floor, METH_O, math_floor_doc},
- {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
- {"frexp", math_frexp, METH_O, math_frexp_doc},
- {"fsum", math_fsum, METH_O, math_fsum_doc},
- {"gamma", math_gamma, METH_O, math_gamma_doc},
- {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
- {"isinf", math_isinf, METH_O, math_isinf_doc},
- {"isnan", math_isnan, METH_O, math_isnan_doc},
- {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
- {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
- {"log", math_log, METH_VARARGS, math_log_doc},
- {"log1p", math_log1p, METH_O, math_log1p_doc},
- {"log10", math_log10, METH_O, math_log10_doc},
- {"modf", math_modf, METH_O, math_modf_doc},
- {"pow", math_pow, METH_VARARGS, math_pow_doc},
- {"radians", math_radians, METH_O, math_radians_doc},
- {"sin", math_sin, METH_O, math_sin_doc},
- {"sinh", math_sinh, METH_O, math_sinh_doc},
- {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
- {"tan", math_tan, METH_O, math_tan_doc},
- {"tanh", math_tanh, METH_O, math_tanh_doc},
- {"trunc", math_trunc, METH_O, math_trunc_doc},
- {NULL, NULL} /* sentinel */
+ {"acos", math_acos, METH_O, math_acos_doc},
+ {"acosh", math_acosh, METH_O, math_acosh_doc},
+ {"asin", math_asin, METH_O, math_asin_doc},
+ {"asinh", math_asinh, METH_O, math_asinh_doc},
+ {"atan", math_atan, METH_O, math_atan_doc},
+ {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
+ {"atanh", math_atanh, METH_O, math_atanh_doc},
+ {"ceil", math_ceil, METH_O, math_ceil_doc},
+ {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
+ {"cos", math_cos, METH_O, math_cos_doc},
+ {"cosh", math_cosh, METH_O, math_cosh_doc},
+ {"degrees", math_degrees, METH_O, math_degrees_doc},
+ {"erf", math_erf, METH_O, math_erf_doc},
+ {"erfc", math_erfc, METH_O, math_erfc_doc},
+ {"exp", math_exp, METH_O, math_exp_doc},
+ {"expm1", math_expm1, METH_O, math_expm1_doc},
+ {"fabs", math_fabs, METH_O, math_fabs_doc},
+ {"factorial", math_factorial, METH_O, math_factorial_doc},
+ {"floor", math_floor, METH_O, math_floor_doc},
+ {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
+ {"frexp", math_frexp, METH_O, math_frexp_doc},
+ {"fsum", math_fsum, METH_O, math_fsum_doc},
+ {"gamma", math_gamma, METH_O, math_gamma_doc},
+ {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
+ {"isinf", math_isinf, METH_O, math_isinf_doc},
+ {"isnan", math_isnan, METH_O, math_isnan_doc},
+ {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
+ {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
+ {"log", math_log, METH_VARARGS, math_log_doc},
+ {"log1p", math_log1p, METH_O, math_log1p_doc},
+ {"log10", math_log10, METH_O, math_log10_doc},
+ {"modf", math_modf, METH_O, math_modf_doc},
+ {"pow", math_pow, METH_VARARGS, math_pow_doc},
+ {"radians", math_radians, METH_O, math_radians_doc},
+ {"sin", math_sin, METH_O, math_sin_doc},
+ {"sinh", math_sinh, METH_O, math_sinh_doc},
+ {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
+ {"tan", math_tan, METH_O, math_tan_doc},
+ {"tanh", math_tanh, METH_O, math_tanh_doc},
+ {"trunc", math_trunc, METH_O, math_trunc_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1675,29 +1675,29 @@ PyDoc_STRVAR(module_doc,
static struct PyModuleDef mathmodule = {
- PyModuleDef_HEAD_INIT,
- "math",
- module_doc,
- -1,
- math_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "math",
+ module_doc,
+ -1,
+ math_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_math(void)
{
- PyObject *m;
+ PyObject *m;
- m = PyModule_Create(&mathmodule);
- if (m == NULL)
- goto finally;
+ m = PyModule_Create(&mathmodule);
+ if (m == NULL)
+ goto finally;
- PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
- PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
+ PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
+ PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
finally:
- return m;
+ return m;
}
diff --git a/Modules/md5module.c b/Modules/md5module.c
index 6476bb7..d217dc8 100644
--- a/Modules/md5module.c
+++ b/Modules/md5module.c
@@ -23,8 +23,8 @@
/* Some useful types */
#if SIZEOF_INT == 4
-typedef unsigned int MD5_INT32; /* 32-bit integer */
-typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
+typedef unsigned int MD5_INT32; /* 32-bit integer */
+typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -127,7 +127,7 @@ static void md5_compress(struct md5_state *md5, unsigned char *buf)
for (i = 0; i < 16; i++) {
LOAD32L(W[i], buf + (4*i));
}
-
+
/* copy state */
a = md5->state[0];
b = md5->state[1];
@@ -386,21 +386,21 @@ MD5_hexdigest(MD5object *self, PyObject *unused)
/* Create a new string */
retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyUnicode_AS_UNICODE(retval);
if (!hex_digest) {
- Py_DECREF(retval);
- return NULL;
+ Py_DECREF(retval);
+ return NULL;
}
/* Make hex version of the digest */
for(i=j=0; i<MD5_DIGESTSIZE; i++) {
char c;
c = (digest[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = (digest[i] & 0xf);
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
return retval;
@@ -414,7 +414,7 @@ MD5_update(MD5object *self, PyObject *args)
{
PyObject *obj;
Py_buffer buf;
-
+
if (!PyArg_ParseTuple(args, "O:update", &obj))
return NULL;
@@ -428,11 +428,11 @@ MD5_update(MD5object *self, PyObject *args)
}
static PyMethodDef MD5_methods[] = {
- {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
- {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
+ {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
+ {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
{"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__},
- {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -472,13 +472,13 @@ static PyGetSetDef MD5_getseters[] = {
static PyTypeObject MD5type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_md5.md5", /*tp_name*/
- sizeof(MD5object), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_md5.md5", /*tp_name*/
+ sizeof(MD5object), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- MD5_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ MD5_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@@ -494,13 +494,13 @@ static PyTypeObject MD5type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- MD5_methods, /* tp_methods */
- NULL, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ MD5_methods, /* tp_methods */
+ NULL, /* tp_members */
MD5_getseters, /* tp_getset */
};
@@ -553,7 +553,7 @@ MD5_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef MD5_functions[] = {
{"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -563,15 +563,15 @@ static struct PyMethodDef MD5_functions[] = {
static struct PyModuleDef _md5module = {
- PyModuleDef_HEAD_INIT,
- "_md5",
- NULL,
- -1,
- MD5_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_md5",
+ NULL,
+ -1,
+ MD5_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c
index 9d6d6af..9714ddf 100644
--- a/Modules/mmapmodule.c
+++ b/Modules/mmapmodule.c
@@ -30,18 +30,18 @@
static int
my_getpagesize(void)
{
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- return si.dwPageSize;
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwPageSize;
}
static int
my_getallocationgranularity (void)
{
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- return si.dwAllocationGranularity;
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwAllocationGranularity;
}
#endif
@@ -54,7 +54,7 @@ my_getallocationgranularity (void)
static int
my_getpagesize(void)
{
- return sysconf(_SC_PAGESIZE);
+ return sysconf(_SC_PAGESIZE);
}
#define my_getallocationgranularity my_getpagesize
@@ -79,31 +79,31 @@ static PyObject *mmap_module_error;
typedef enum
{
- ACCESS_DEFAULT,
- ACCESS_READ,
- ACCESS_WRITE,
- ACCESS_COPY
+ ACCESS_DEFAULT,
+ ACCESS_READ,
+ ACCESS_WRITE,
+ ACCESS_COPY
} access_mode;
typedef struct {
- PyObject_HEAD
- char * data;
- size_t size;
- size_t pos; /* relative to offset */
- size_t offset;
- int exports;
+ PyObject_HEAD
+ char * data;
+ size_t size;
+ size_t pos; /* relative to offset */
+ size_t offset;
+ int exports;
#ifdef MS_WINDOWS
- HANDLE map_handle;
- HANDLE file_handle;
- char * tagname;
+ HANDLE map_handle;
+ HANDLE file_handle;
+ char * tagname;
#endif
#ifdef UNIX
- int fd;
+ int fd;
#endif
- access_mode access;
+ access_mode access;
} mmap_object;
@@ -111,331 +111,331 @@ static void
mmap_object_dealloc(mmap_object *m_obj)
{
#ifdef MS_WINDOWS
- if (m_obj->data != NULL)
- UnmapViewOfFile (m_obj->data);
- if (m_obj->map_handle != NULL)
- CloseHandle (m_obj->map_handle);
- if (m_obj->file_handle != INVALID_HANDLE_VALUE)
- CloseHandle (m_obj->file_handle);
- if (m_obj->tagname)
- PyMem_Free(m_obj->tagname);
+ if (m_obj->data != NULL)
+ UnmapViewOfFile (m_obj->data);
+ if (m_obj->map_handle != NULL)
+ CloseHandle (m_obj->map_handle);
+ if (m_obj->file_handle != INVALID_HANDLE_VALUE)
+ CloseHandle (m_obj->file_handle);
+ if (m_obj->tagname)
+ PyMem_Free(m_obj->tagname);
#endif /* MS_WINDOWS */
#ifdef UNIX
- if (m_obj->fd >= 0)
- (void) close(m_obj->fd);
- if (m_obj->data!=NULL) {
- msync(m_obj->data, m_obj->size, MS_SYNC);
- munmap(m_obj->data, m_obj->size);
- }
+ if (m_obj->fd >= 0)
+ (void) close(m_obj->fd);
+ if (m_obj->data!=NULL) {
+ msync(m_obj->data, m_obj->size, MS_SYNC);
+ munmap(m_obj->data, m_obj->size);
+ }
#endif /* UNIX */
- Py_TYPE(m_obj)->tp_free((PyObject*)m_obj);
+ Py_TYPE(m_obj)->tp_free((PyObject*)m_obj);
}
static PyObject *
mmap_close_method(mmap_object *self, PyObject *unused)
{
- if (self->exports > 0) {
- PyErr_SetString(PyExc_BufferError, "cannot close "\
- "exported pointers exist");
- return NULL;
- }
+ if (self->exports > 0) {
+ PyErr_SetString(PyExc_BufferError, "cannot close "\
+ "exported pointers exist");
+ return NULL;
+ }
#ifdef MS_WINDOWS
- /* For each resource we maintain, we need to check
- the value is valid, and if so, free the resource
- and set the member value to an invalid value so
- the dealloc does not attempt to resource clearing
- again.
- TODO - should we check for errors in the close operations???
- */
- if (self->data != NULL) {
- UnmapViewOfFile(self->data);
- self->data = NULL;
- }
- if (self->map_handle != NULL) {
- CloseHandle(self->map_handle);
- self->map_handle = NULL;
- }
- if (self->file_handle != INVALID_HANDLE_VALUE) {
- CloseHandle(self->file_handle);
- self->file_handle = INVALID_HANDLE_VALUE;
- }
+ /* For each resource we maintain, we need to check
+ the value is valid, and if so, free the resource
+ and set the member value to an invalid value so
+ the dealloc does not attempt to resource clearing
+ again.
+ TODO - should we check for errors in the close operations???
+ */
+ if (self->data != NULL) {
+ UnmapViewOfFile(self->data);
+ self->data = NULL;
+ }
+ if (self->map_handle != NULL) {
+ CloseHandle(self->map_handle);
+ self->map_handle = NULL;
+ }
+ if (self->file_handle != INVALID_HANDLE_VALUE) {
+ CloseHandle(self->file_handle);
+ self->file_handle = INVALID_HANDLE_VALUE;
+ }
#endif /* MS_WINDOWS */
#ifdef UNIX
- if (0 <= self->fd)
- (void) close(self->fd);
- self->fd = -1;
- if (self->data != NULL) {
- munmap(self->data, self->size);
- self->data = NULL;
- }
+ if (0 <= self->fd)
+ (void) close(self->fd);
+ self->fd = -1;
+ if (self->data != NULL) {
+ munmap(self->data, self->size);
+ self->data = NULL;
+ }
#endif
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef MS_WINDOWS
-#define CHECK_VALID(err) \
-do { \
- if (self->map_handle == NULL) { \
- PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
- return err; \
- } \
+#define CHECK_VALID(err) \
+do { \
+ if (self->map_handle == NULL) { \
+ PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
+ return err; \
+ } \
} while (0)
#endif /* MS_WINDOWS */
#ifdef UNIX
-#define CHECK_VALID(err) \
-do { \
- if (self->data == NULL) { \
- PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
- return err; \
- } \
+#define CHECK_VALID(err) \
+do { \
+ if (self->data == NULL) { \
+ PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
+ return err; \
+ } \
} while (0)
#endif /* UNIX */
static PyObject *
mmap_read_byte_method(mmap_object *self,
- PyObject *unused)
+ PyObject *unused)
{
- CHECK_VALID(NULL);
- if (self->pos < self->size) {
- char value = self->data[self->pos];
- self->pos += 1;
- return Py_BuildValue("b", value);
- } else {
- PyErr_SetString(PyExc_ValueError, "read byte out of range");
- return NULL;
- }
+ CHECK_VALID(NULL);
+ if (self->pos < self->size) {
+ char value = self->data[self->pos];
+ self->pos += 1;
+ return Py_BuildValue("b", value);
+ } else {
+ PyErr_SetString(PyExc_ValueError, "read byte out of range");
+ return NULL;
+ }
}
static PyObject *
mmap_read_line_method(mmap_object *self,
- PyObject *unused)
+ PyObject *unused)
{
- char *start = self->data+self->pos;
- char *eof = self->data+self->size;
- char *eol;
- PyObject *result;
-
- CHECK_VALID(NULL);
-
- eol = memchr(start, '\n', self->size - self->pos);
- if (!eol)
- eol = eof;
- else
- ++eol; /* we're interested in the position after the
- newline. */
- result = PyBytes_FromStringAndSize(start, (eol - start));
- self->pos += (eol - start);
- return result;
+ char *start = self->data+self->pos;
+ char *eof = self->data+self->size;
+ char *eol;
+ PyObject *result;
+
+ CHECK_VALID(NULL);
+
+ eol = memchr(start, '\n', self->size - self->pos);
+ if (!eol)
+ eol = eof;
+ else
+ ++eol; /* we're interested in the position after the
+ newline. */
+ result = PyBytes_FromStringAndSize(start, (eol - start));
+ self->pos += (eol - start);
+ return result;
}
static PyObject *
mmap_read_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- Py_ssize_t num_bytes, n;
- PyObject *result;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "n:read", &num_bytes))
- return(NULL);
-
- /* silently 'adjust' out-of-range requests */
- assert(self->size >= self->pos);
- n = self->size - self->pos;
- /* The difference can overflow, only if self->size is greater than
- * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed,
- * because the mapped area and the returned string each need more
- * than half of the addressable memory. So we clip the size, and let
- * the code below raise MemoryError.
- */
- if (n < 0)
- n = PY_SSIZE_T_MAX;
- if (num_bytes < 0 || num_bytes > n) {
- num_bytes = n;
- }
- result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes);
- self->pos += num_bytes;
- return result;
+ Py_ssize_t num_bytes, n;
+ PyObject *result;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "n:read", &num_bytes))
+ return(NULL);
+
+ /* silently 'adjust' out-of-range requests */
+ assert(self->size >= self->pos);
+ n = self->size - self->pos;
+ /* The difference can overflow, only if self->size is greater than
+ * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed,
+ * because the mapped area and the returned string each need more
+ * than half of the addressable memory. So we clip the size, and let
+ * the code below raise MemoryError.
+ */
+ if (n < 0)
+ n = PY_SSIZE_T_MAX;
+ if (num_bytes < 0 || num_bytes > n) {
+ num_bytes = n;
+ }
+ result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes);
+ self->pos += num_bytes;
+ return result;
}
static PyObject *
mmap_gfind(mmap_object *self,
- PyObject *args,
- int reverse)
+ PyObject *args,
+ int reverse)
{
- Py_ssize_t start = self->pos;
- Py_ssize_t end = self->size;
- const char *needle;
- Py_ssize_t len;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find",
- &needle, &len, &start, &end)) {
- return NULL;
- } else {
- const char *p, *start_p, *end_p;
- int sign = reverse ? -1 : 1;
-
- if (start < 0)
- start += self->size;
- if (start < 0)
- start = 0;
- else if ((size_t)start > self->size)
- start = self->size;
-
- if (end < 0)
- end += self->size;
- if (end < 0)
- end = 0;
- else if ((size_t)end > self->size)
- end = self->size;
-
- start_p = self->data + start;
- end_p = self->data + end;
-
- for (p = (reverse ? end_p - len : start_p);
- (p >= start_p) && (p + len <= end_p); p += sign) {
- Py_ssize_t i;
- for (i = 0; i < len && needle[i] == p[i]; ++i)
- /* nothing */;
- if (i == len) {
- return PyLong_FromSsize_t(p - self->data);
- }
- }
- return PyLong_FromLong(-1);
- }
+ Py_ssize_t start = self->pos;
+ Py_ssize_t end = self->size;
+ const char *needle;
+ Py_ssize_t len;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find",
+ &needle, &len, &start, &end)) {
+ return NULL;
+ } else {
+ const char *p, *start_p, *end_p;
+ int sign = reverse ? -1 : 1;
+
+ if (start < 0)
+ start += self->size;
+ if (start < 0)
+ start = 0;
+ else if ((size_t)start > self->size)
+ start = self->size;
+
+ if (end < 0)
+ end += self->size;
+ if (end < 0)
+ end = 0;
+ else if ((size_t)end > self->size)
+ end = self->size;
+
+ start_p = self->data + start;
+ end_p = self->data + end;
+
+ for (p = (reverse ? end_p - len : start_p);
+ (p >= start_p) && (p + len <= end_p); p += sign) {
+ Py_ssize_t i;
+ for (i = 0; i < len && needle[i] == p[i]; ++i)
+ /* nothing */;
+ if (i == len) {
+ return PyLong_FromSsize_t(p - self->data);
+ }
+ }
+ return PyLong_FromLong(-1);
+ }
}
static PyObject *
mmap_find_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- return mmap_gfind(self, args, 0);
+ return mmap_gfind(self, args, 0);
}
static PyObject *
mmap_rfind_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- return mmap_gfind(self, args, 1);
+ return mmap_gfind(self, args, 1);
}
static int
is_writable(mmap_object *self)
{
- if (self->access != ACCESS_READ)
- return 1;
- PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
- return 0;
+ if (self->access != ACCESS_READ)
+ return 1;
+ PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
+ return 0;
}
static int
is_resizeable(mmap_object *self)
{
- if (self->exports > 0) {
- PyErr_SetString(PyExc_BufferError,
- "mmap can't resize with extant buffers exported.");
- return 0;
- }
- if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
- return 1;
- PyErr_Format(PyExc_TypeError,
- "mmap can't resize a readonly or copy-on-write memory map.");
- return 0;
+ if (self->exports > 0) {
+ PyErr_SetString(PyExc_BufferError,
+ "mmap can't resize with extant buffers exported.");
+ return 0;
+ }
+ if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
+ return 1;
+ PyErr_Format(PyExc_TypeError,
+ "mmap can't resize a readonly or copy-on-write memory map.");
+ return 0;
}
static PyObject *
mmap_write_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- Py_ssize_t length;
- char *data;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "y#:write", &data, &length))
- return(NULL);
-
- if (!is_writable(self))
- return NULL;
-
- if ((self->pos + length) > self->size) {
- PyErr_SetString(PyExc_ValueError, "data out of range");
- return NULL;
- }
- memcpy(self->data+self->pos, data, length);
- self->pos = self->pos+length;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t length;
+ char *data;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "y#:write", &data, &length))
+ return(NULL);
+
+ if (!is_writable(self))
+ return NULL;
+
+ if ((self->pos + length) > self->size) {
+ PyErr_SetString(PyExc_ValueError, "data out of range");
+ return NULL;
+ }
+ memcpy(self->data+self->pos, data, length);
+ self->pos = self->pos+length;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
mmap_write_byte_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- char value;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "b:write_byte", &value))
- return(NULL);
-
- if (!is_writable(self))
- return NULL;
-
- if (self->pos < self->size) {
- *(self->data+self->pos) = value;
- self->pos += 1;
- Py_INCREF(Py_None);
- return Py_None;
- }
- else {
- PyErr_SetString(PyExc_ValueError, "write byte out of range");
- return NULL;
- }
+ char value;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "b:write_byte", &value))
+ return(NULL);
+
+ if (!is_writable(self))
+ return NULL;
+
+ if (self->pos < self->size) {
+ *(self->data+self->pos) = value;
+ self->pos += 1;
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "write byte out of range");
+ return NULL;
+ }
}
static PyObject *
mmap_size_method(mmap_object *self,
- PyObject *unused)
+ PyObject *unused)
{
- CHECK_VALID(NULL);
+ CHECK_VALID(NULL);
#ifdef MS_WINDOWS
- if (self->file_handle != INVALID_HANDLE_VALUE) {
- DWORD low,high;
- PY_LONG_LONG size;
- low = GetFileSize(self->file_handle, &high);
- if (low == INVALID_FILE_SIZE) {
- /* It might be that the function appears to have failed,
- when indeed its size equals INVALID_FILE_SIZE */
- DWORD error = GetLastError();
- if (error != NO_ERROR)
- return PyErr_SetFromWindowsErr(error);
- }
- if (!high && low < LONG_MAX)
- return PyLong_FromLong((long)low);
- size = (((PY_LONG_LONG)high)<<32) + low;
- return PyLong_FromLongLong(size);
- } else {
- return PyLong_FromSsize_t(self->size);
- }
+ if (self->file_handle != INVALID_HANDLE_VALUE) {
+ DWORD low,high;
+ PY_LONG_LONG size;
+ low = GetFileSize(self->file_handle, &high);
+ if (low == INVALID_FILE_SIZE) {
+ /* It might be that the function appears to have failed,
+ when indeed its size equals INVALID_FILE_SIZE */
+ DWORD error = GetLastError();
+ if (error != NO_ERROR)
+ return PyErr_SetFromWindowsErr(error);
+ }
+ if (!high && low < LONG_MAX)
+ return PyLong_FromLong((long)low);
+ size = (((PY_LONG_LONG)high)<<32) + low;
+ return PyLong_FromLongLong(size);
+ } else {
+ return PyLong_FromSsize_t(self->size);
+ }
#endif /* MS_WINDOWS */
#ifdef UNIX
- {
- struct stat buf;
- if (-1 == fstat(self->fd, &buf)) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- return PyLong_FromSsize_t(buf.st_size);
- }
+ {
+ struct stat buf;
+ if (-1 == fstat(self->fd, &buf)) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ return PyLong_FromSsize_t(buf.st_size);
+ }
#endif /* UNIX */
}
@@ -450,223 +450,223 @@ mmap_size_method(mmap_object *self,
static PyObject *
mmap_resize_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- Py_ssize_t new_size;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
- !is_resizeable(self)) {
- return NULL;
+ Py_ssize_t new_size;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
+ !is_resizeable(self)) {
+ return NULL;
#ifdef MS_WINDOWS
- } else {
- DWORD dwErrCode = 0;
- DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
- /* First, unmap the file view */
- UnmapViewOfFile(self->data);
- self->data = NULL;
- /* Close the mapping object */
- CloseHandle(self->map_handle);
- self->map_handle = NULL;
- /* Move to the desired EOF position */
+ } else {
+ DWORD dwErrCode = 0;
+ DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
+ /* First, unmap the file view */
+ UnmapViewOfFile(self->data);
+ self->data = NULL;
+ /* Close the mapping object */
+ CloseHandle(self->map_handle);
+ self->map_handle = NULL;
+ /* Move to the desired EOF position */
#if SIZEOF_SIZE_T > 4
- newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
- newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
- off_hi = (DWORD)(self->offset >> 32);
- off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
+ newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
+ newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
+ off_hi = (DWORD)(self->offset >> 32);
+ off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
#else
- newSizeHigh = 0;
- newSizeLow = (DWORD)(self->offset + new_size);
- off_hi = 0;
- off_lo = (DWORD)self->offset;
+ newSizeHigh = 0;
+ newSizeLow = (DWORD)(self->offset + new_size);
+ off_hi = 0;
+ off_lo = (DWORD)self->offset;
#endif
- SetFilePointer(self->file_handle,
- newSizeLow, &newSizeHigh, FILE_BEGIN);
- /* Change the size of the file */
- SetEndOfFile(self->file_handle);
- /* Create another mapping object and remap the file view */
- self->map_handle = CreateFileMapping(
- self->file_handle,
- NULL,
- PAGE_READWRITE,
- 0,
- 0,
- self->tagname);
- if (self->map_handle != NULL) {
- self->data = (char *) MapViewOfFile(self->map_handle,
- FILE_MAP_WRITE,
- off_hi,
- off_lo,
- new_size);
- if (self->data != NULL) {
- self->size = new_size;
- Py_INCREF(Py_None);
- return Py_None;
- } else {
- dwErrCode = GetLastError();
- CloseHandle(self->map_handle);
- self->map_handle = NULL;
- }
- } else {
- dwErrCode = GetLastError();
- }
- PyErr_SetFromWindowsErr(dwErrCode);
- return NULL;
+ SetFilePointer(self->file_handle,
+ newSizeLow, &newSizeHigh, FILE_BEGIN);
+ /* Change the size of the file */
+ SetEndOfFile(self->file_handle);
+ /* Create another mapping object and remap the file view */
+ self->map_handle = CreateFileMapping(
+ self->file_handle,
+ NULL,
+ PAGE_READWRITE,
+ 0,
+ 0,
+ self->tagname);
+ if (self->map_handle != NULL) {
+ self->data = (char *) MapViewOfFile(self->map_handle,
+ FILE_MAP_WRITE,
+ off_hi,
+ off_lo,
+ new_size);
+ if (self->data != NULL) {
+ self->size = new_size;
+ Py_INCREF(Py_None);
+ return Py_None;
+ } else {
+ dwErrCode = GetLastError();
+ CloseHandle(self->map_handle);
+ self->map_handle = NULL;
+ }
+ } else {
+ dwErrCode = GetLastError();
+ }
+ PyErr_SetFromWindowsErr(dwErrCode);
+ return NULL;
#endif /* MS_WINDOWS */
#ifdef UNIX
#ifndef HAVE_MREMAP
- } else {
- PyErr_SetString(PyExc_SystemError,
- "mmap: resizing not available--no mremap()");
- return NULL;
+ } else {
+ PyErr_SetString(PyExc_SystemError,
+ "mmap: resizing not available--no mremap()");
+ return NULL;
#else
- } else {
- void *newmap;
+ } else {
+ void *newmap;
- if (ftruncate(self->fd, self->offset + new_size) == -1) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
+ if (ftruncate(self->fd, self->offset + new_size) == -1) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
#ifdef MREMAP_MAYMOVE
- newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
+ newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
#else
- #if defined(__NetBSD__)
- newmap = mremap(self->data, self->size, self->data, new_size, 0);
- #else
- newmap = mremap(self->data, self->size, new_size, 0);
- #endif /* __NetBSD__ */
+ #if defined(__NetBSD__)
+ newmap = mremap(self->data, self->size, self->data, new_size, 0);
+ #else
+ newmap = mremap(self->data, self->size, new_size, 0);
+ #endif /* __NetBSD__ */
#endif
- if (newmap == (void *)-1)
- {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- self->data = newmap;
- self->size = new_size;
- Py_INCREF(Py_None);
- return Py_None;
+ if (newmap == (void *)-1)
+ {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ self->data = newmap;
+ self->size = new_size;
+ Py_INCREF(Py_None);
+ return Py_None;
#endif /* HAVE_MREMAP */
#endif /* UNIX */
- }
+ }
}
static PyObject *
mmap_tell_method(mmap_object *self, PyObject *unused)
{
- CHECK_VALID(NULL);
- return PyLong_FromSize_t(self->pos);
+ CHECK_VALID(NULL);
+ return PyLong_FromSize_t(self->pos);
}
static PyObject *
mmap_flush_method(mmap_object *self, PyObject *args)
{
- Py_ssize_t offset = 0;
- Py_ssize_t size = self->size;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
- return NULL;
- if ((size_t)(offset + size) > self->size) {
- PyErr_SetString(PyExc_ValueError, "flush values out of range");
- return NULL;
- }
+ Py_ssize_t offset = 0;
+ Py_ssize_t size = self->size;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
+ return NULL;
+ if ((size_t)(offset + size) > self->size) {
+ PyErr_SetString(PyExc_ValueError, "flush values out of range");
+ return NULL;
+ }
#ifdef MS_WINDOWS
- return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size));
+ return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size));
#elif defined(UNIX)
- /* XXX semantics of return value? */
- /* XXX flags for msync? */
- if (-1 == msync(self->data + offset, size, MS_SYNC)) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- return PyLong_FromLong(0);
+ /* XXX semantics of return value? */
+ /* XXX flags for msync? */
+ if (-1 == msync(self->data + offset, size, MS_SYNC)) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ return PyLong_FromLong(0);
#else
- PyErr_SetString(PyExc_ValueError, "flush not supported on this system");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "flush not supported on this system");
+ return NULL;
#endif
}
static PyObject *
mmap_seek_method(mmap_object *self, PyObject *args)
{
- Py_ssize_t dist;
- int how=0;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
- return NULL;
- else {
- size_t where;
- switch (how) {
- case 0: /* relative to start */
- if (dist < 0)
- goto onoutofrange;
- where = dist;
- break;
- case 1: /* relative to current position */
- if ((Py_ssize_t)self->pos + dist < 0)
- goto onoutofrange;
- where = self->pos + dist;
- break;
- case 2: /* relative to end */
- if ((Py_ssize_t)self->size + dist < 0)
- goto onoutofrange;
- where = self->size + dist;
- break;
- default:
- PyErr_SetString(PyExc_ValueError, "unknown seek type");
- return NULL;
- }
- if (where > self->size)
- goto onoutofrange;
- self->pos = where;
- Py_INCREF(Py_None);
- return Py_None;
- }
+ Py_ssize_t dist;
+ int how=0;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
+ return NULL;
+ else {
+ size_t where;
+ switch (how) {
+ case 0: /* relative to start */
+ if (dist < 0)
+ goto onoutofrange;
+ where = dist;
+ break;
+ case 1: /* relative to current position */
+ if ((Py_ssize_t)self->pos + dist < 0)
+ goto onoutofrange;
+ where = self->pos + dist;
+ break;
+ case 2: /* relative to end */
+ if ((Py_ssize_t)self->size + dist < 0)
+ goto onoutofrange;
+ where = self->size + dist;
+ break;
+ default:
+ PyErr_SetString(PyExc_ValueError, "unknown seek type");
+ return NULL;
+ }
+ if (where > self->size)
+ goto onoutofrange;
+ self->pos = where;
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
onoutofrange:
- PyErr_SetString(PyExc_ValueError, "seek out of range");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "seek out of range");
+ return NULL;
}
static PyObject *
mmap_move_method(mmap_object *self, PyObject *args)
{
- unsigned long dest, src, cnt;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) ||
- !is_writable(self)) {
- return NULL;
- } else {
- /* bounds check the values */
- if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt ||
- src < 0 || src > self->size || (src + cnt) > self->size ||
- dest < 0 || dest > self->size || (dest + cnt) > self->size) {
- PyErr_SetString(PyExc_ValueError,
- "source, destination, or count out of range");
- return NULL;
- }
- memmove(self->data+dest, self->data+src, cnt);
- Py_INCREF(Py_None);
- return Py_None;
- }
+ unsigned long dest, src, cnt;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) ||
+ !is_writable(self)) {
+ return NULL;
+ } else {
+ /* bounds check the values */
+ if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt ||
+ src < 0 || src > self->size || (src + cnt) > self->size ||
+ dest < 0 || dest > self->size || (dest + cnt) > self->size) {
+ PyErr_SetString(PyExc_ValueError,
+ "source, destination, or count out of range");
+ return NULL;
+ }
+ memmove(self->data+dest, self->data+src, cnt);
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static struct PyMethodDef mmap_object_methods[] = {
- {"close", (PyCFunction) mmap_close_method, METH_NOARGS},
- {"find", (PyCFunction) mmap_find_method, METH_VARARGS},
- {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS},
- {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS},
- {"move", (PyCFunction) mmap_move_method, METH_VARARGS},
- {"read", (PyCFunction) mmap_read_method, METH_VARARGS},
- {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS},
- {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS},
- {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS},
- {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS},
- {"size", (PyCFunction) mmap_size_method, METH_NOARGS},
- {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS},
- {"write", (PyCFunction) mmap_write_method, METH_VARARGS},
- {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"close", (PyCFunction) mmap_close_method, METH_NOARGS},
+ {"find", (PyCFunction) mmap_find_method, METH_VARARGS},
+ {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS},
+ {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS},
+ {"move", (PyCFunction) mmap_move_method, METH_VARARGS},
+ {"read", (PyCFunction) mmap_read_method, METH_VARARGS},
+ {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS},
+ {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS},
+ {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS},
+ {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS},
+ {"size", (PyCFunction) mmap_size_method, METH_NOARGS},
+ {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS},
+ {"write", (PyCFunction) mmap_write_method, METH_VARARGS},
+ {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
/* Functions for treating an mmap'ed file as a buffer */
@@ -674,247 +674,247 @@ static struct PyMethodDef mmap_object_methods[] = {
static int
mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags)
{
- CHECK_VALID(-1);
- if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size,
- (self->access == ACCESS_READ), flags) < 0)
- return -1;
- self->exports++;
- return 0;
+ CHECK_VALID(-1);
+ if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size,
+ (self->access == ACCESS_READ), flags) < 0)
+ return -1;
+ self->exports++;
+ return 0;
}
static void
mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view)
{
- self->exports--;
+ self->exports--;
}
static Py_ssize_t
mmap_length(mmap_object *self)
{
- CHECK_VALID(-1);
- return self->size;
+ CHECK_VALID(-1);
+ return self->size;
}
static PyObject *
mmap_item(mmap_object *self, Py_ssize_t i)
{
- CHECK_VALID(NULL);
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError, "mmap index out of range");
- return NULL;
- }
- return PyBytes_FromStringAndSize(self->data + i, 1);
+ CHECK_VALID(NULL);
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError, "mmap index out of range");
+ return NULL;
+ }
+ return PyBytes_FromStringAndSize(self->data + i, 1);
}
static PyObject *
mmap_subscript(mmap_object *self, PyObject *item)
{
- CHECK_VALID(NULL);
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += self->size;
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError,
- "mmap index out of range");
- return NULL;
- }
- return PyLong_FromLong(Py_CHARMASK(self->data[i]));
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item, self->size,
- &start, &stop, &step, &slicelen) < 0) {
- return NULL;
- }
-
- if (slicelen <= 0)
- return PyBytes_FromStringAndSize("", 0);
- else if (step == 1)
- return PyBytes_FromStringAndSize(self->data + start,
- slicelen);
- else {
- char *result_buf = (char *)PyMem_Malloc(slicelen);
- Py_ssize_t cur, i;
- PyObject *result;
-
- if (result_buf == NULL)
- return PyErr_NoMemory();
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- result_buf[i] = self->data[cur];
- }
- result = PyBytes_FromStringAndSize(result_buf,
- slicelen);
- PyMem_Free(result_buf);
- return result;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "mmap indices must be integers");
- return NULL;
- }
+ CHECK_VALID(NULL);
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += self->size;
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap index out of range");
+ return NULL;
+ }
+ return PyLong_FromLong(Py_CHARMASK(self->data[i]));
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item, self->size,
+ &start, &stop, &step, &slicelen) < 0) {
+ return NULL;
+ }
+
+ if (slicelen <= 0)
+ return PyBytes_FromStringAndSize("", 0);
+ else if (step == 1)
+ return PyBytes_FromStringAndSize(self->data + start,
+ slicelen);
+ else {
+ char *result_buf = (char *)PyMem_Malloc(slicelen);
+ Py_ssize_t cur, i;
+ PyObject *result;
+
+ if (result_buf == NULL)
+ return PyErr_NoMemory();
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ result_buf[i] = self->data[cur];
+ }
+ result = PyBytes_FromStringAndSize(result_buf,
+ slicelen);
+ PyMem_Free(result_buf);
+ return result;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap indices must be integers");
+ return NULL;
+ }
}
static PyObject *
mmap_concat(mmap_object *self, PyObject *bb)
{
- CHECK_VALID(NULL);
- PyErr_SetString(PyExc_SystemError,
- "mmaps don't support concatenation");
- return NULL;
+ CHECK_VALID(NULL);
+ PyErr_SetString(PyExc_SystemError,
+ "mmaps don't support concatenation");
+ return NULL;
}
static PyObject *
mmap_repeat(mmap_object *self, Py_ssize_t n)
{
- CHECK_VALID(NULL);
- PyErr_SetString(PyExc_SystemError,
- "mmaps don't support repeat operation");
- return NULL;
+ CHECK_VALID(NULL);
+ PyErr_SetString(PyExc_SystemError,
+ "mmaps don't support repeat operation");
+ return NULL;
}
static int
mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v)
{
- const char *buf;
-
- CHECK_VALID(-1);
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError, "mmap index out of range");
- return -1;
- }
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support item deletion");
- return -1;
- }
- if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) {
- PyErr_SetString(PyExc_IndexError,
- "mmap assignment must be length-1 bytes()");
- return -1;
- }
- if (!is_writable(self))
- return -1;
- buf = PyBytes_AsString(v);
- self->data[i] = buf[0];
- return 0;
+ const char *buf;
+
+ CHECK_VALID(-1);
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError, "mmap index out of range");
+ return -1;
+ }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support item deletion");
+ return -1;
+ }
+ if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap assignment must be length-1 bytes()");
+ return -1;
+ }
+ if (!is_writable(self))
+ return -1;
+ buf = PyBytes_AsString(v);
+ self->data[i] = buf[0];
+ return 0;
}
static int
mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value)
{
- CHECK_VALID(-1);
-
- if (!is_writable(self))
- return -1;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- Py_ssize_t v;
-
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += self->size;
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError,
- "mmap index out of range");
- return -1;
- }
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap doesn't support item deletion");
- return -1;
- }
- if (!PyIndex_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "mmap item value must be an int");
- return -1;
- }
- v = PyNumber_AsSsize_t(value, PyExc_TypeError);
- if (v == -1 && PyErr_Occurred())
- return -1;
- if (v < 0 || v > 255) {
- PyErr_SetString(PyExc_ValueError,
- "mmap item value must be "
- "in range(0, 256)");
- return -1;
- }
- self->data[i] = v;
- return 0;
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen;
- Py_buffer vbuf;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- self->size, &start, &stop,
- &step, &slicelen) < 0) {
- return -1;
- }
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support slice deletion");
- return -1;
- }
- if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0)
- return -1;
- if (vbuf.len != slicelen) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment is wrong size");
- PyBuffer_Release(&vbuf);
- return -1;
- }
-
- if (slicelen == 0) {
- }
- else if (step == 1) {
- memcpy(self->data + start, vbuf.buf, slicelen);
- }
- else {
- Py_ssize_t cur, i;
-
- for (cur = start, i = 0;
- i < slicelen;
- cur += step, i++)
- {
- self->data[cur] = ((char *)vbuf.buf)[i];
- }
- }
- PyBuffer_Release(&vbuf);
- return 0;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "mmap indices must be integer");
- return -1;
- }
+ CHECK_VALID(-1);
+
+ if (!is_writable(self))
+ return -1;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ Py_ssize_t v;
+
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += self->size;
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap index out of range");
+ return -1;
+ }
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap doesn't support item deletion");
+ return -1;
+ }
+ if (!PyIndex_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap item value must be an int");
+ return -1;
+ }
+ v = PyNumber_AsSsize_t(value, PyExc_TypeError);
+ if (v == -1 && PyErr_Occurred())
+ return -1;
+ if (v < 0 || v > 255) {
+ PyErr_SetString(PyExc_ValueError,
+ "mmap item value must be "
+ "in range(0, 256)");
+ return -1;
+ }
+ self->data[i] = v;
+ return 0;
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen;
+ Py_buffer vbuf;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ self->size, &start, &stop,
+ &step, &slicelen) < 0) {
+ return -1;
+ }
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support slice deletion");
+ return -1;
+ }
+ if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0)
+ return -1;
+ if (vbuf.len != slicelen) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment is wrong size");
+ PyBuffer_Release(&vbuf);
+ return -1;
+ }
+
+ if (slicelen == 0) {
+ }
+ else if (step == 1) {
+ memcpy(self->data + start, vbuf.buf, slicelen);
+ }
+ else {
+ Py_ssize_t cur, i;
+
+ for (cur = start, i = 0;
+ i < slicelen;
+ cur += step, i++)
+ {
+ self->data[cur] = ((char *)vbuf.buf)[i];
+ }
+ }
+ PyBuffer_Release(&vbuf);
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap indices must be integer");
+ return -1;
+ }
}
static PySequenceMethods mmap_as_sequence = {
- (lenfunc)mmap_length, /*sq_length*/
- (binaryfunc)mmap_concat, /*sq_concat*/
- (ssizeargfunc)mmap_repeat, /*sq_repeat*/
- (ssizeargfunc)mmap_item, /*sq_item*/
- 0, /*sq_slice*/
- (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
+ (lenfunc)mmap_length, /*sq_length*/
+ (binaryfunc)mmap_concat, /*sq_concat*/
+ (ssizeargfunc)mmap_repeat, /*sq_repeat*/
+ (ssizeargfunc)mmap_item, /*sq_item*/
+ 0, /*sq_slice*/
+ (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
+ 0, /*sq_ass_slice*/
};
static PyMappingMethods mmap_as_mapping = {
- (lenfunc)mmap_length,
- (binaryfunc)mmap_subscript,
- (objobjargproc)mmap_ass_subscript,
+ (lenfunc)mmap_length,
+ (binaryfunc)mmap_subscript,
+ (objobjargproc)mmap_ass_subscript,
};
static PyBufferProcs mmap_as_buffer = {
- (getbufferproc)mmap_buffer_getbuf,
- (releasebufferproc)mmap_buffer_releasebuf,
+ (getbufferproc)mmap_buffer_getbuf,
+ (releasebufferproc)mmap_buffer_releasebuf,
};
static PyObject *
@@ -945,46 +945,46 @@ To map anonymous memory, pass -1 as the fileno (both versions).");
static PyTypeObject mmap_object_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "mmap.mmap", /* tp_name */
- sizeof(mmap_object), /* tp_size */
- 0, /* tp_itemsize */
- /* methods */
- (destructor) mmap_object_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &mmap_as_sequence, /*tp_as_sequence*/
- &mmap_as_mapping, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- 0, /*tp_setattro*/
- &mmap_as_buffer, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
- mmap_doc, /*tp_doc*/
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- mmap_object_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- new_mmap_object, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "mmap.mmap", /* tp_name */
+ sizeof(mmap_object), /* tp_size */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor) mmap_object_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &mmap_as_sequence, /*tp_as_sequence*/
+ &mmap_as_mapping, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ &mmap_as_buffer, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ mmap_doc, /*tp_doc*/
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ mmap_object_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ new_mmap_object, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -995,23 +995,23 @@ static PyTypeObject mmap_object_type = {
static Py_ssize_t
_GetMapSize(PyObject *o, const char* param)
{
- if (o == NULL)
- return 0;
- if (PyIndex_Check(o)) {
- Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
- if (i==-1 && PyErr_Occurred())
- return -1;
- if (i < 0) {
- PyErr_Format(PyExc_OverflowError,
- "memory mapped %s must be positive",
- param);
- return -1;
- }
- return i;
- }
-
- PyErr_SetString(PyExc_TypeError, "map size must be an integral value");
- return -1;
+ if (o == NULL)
+ return 0;
+ if (PyIndex_Check(o)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
+ if (i==-1 && PyErr_Occurred())
+ return -1;
+ if (i < 0) {
+ PyErr_Format(PyExc_OverflowError,
+ "memory mapped %s must be positive",
+ param);
+ return -1;
+ }
+ return i;
+ }
+
+ PyErr_SetString(PyExc_TypeError, "map size must be an integral value");
+ return -1;
}
#ifdef UNIX
@@ -1019,125 +1019,125 @@ static PyObject *
new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
{
#ifdef HAVE_FSTAT
- struct stat st;
+ struct stat st;
#endif
- mmap_object *m_obj;
- PyObject *map_size_obj = NULL, *offset_obj = NULL;
- Py_ssize_t map_size, offset;
- int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
- int devzero = -1;
- int access = (int)ACCESS_DEFAULT;
- static char *keywords[] = {"fileno", "length",
- "flags", "prot",
- "access", "offset", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords,
- &fd, &map_size_obj, &flags, &prot,
- &access, &offset_obj))
- return NULL;
- map_size = _GetMapSize(map_size_obj, "size");
- if (map_size < 0)
- return NULL;
- offset = _GetMapSize(offset_obj, "offset");
- if (offset < 0)
- return NULL;
-
- if ((access != (int)ACCESS_DEFAULT) &&
- ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
- return PyErr_Format(PyExc_ValueError,
- "mmap can't specify both access and flags, prot.");
- switch ((access_mode)access) {
- case ACCESS_READ:
- flags = MAP_SHARED;
- prot = PROT_READ;
- break;
- case ACCESS_WRITE:
- flags = MAP_SHARED;
- prot = PROT_READ | PROT_WRITE;
- break;
- case ACCESS_COPY:
- flags = MAP_PRIVATE;
- prot = PROT_READ | PROT_WRITE;
- break;
- case ACCESS_DEFAULT:
- /* use the specified or default values of flags and prot */
- break;
- default:
- return PyErr_Format(PyExc_ValueError,
- "mmap invalid access parameter.");
- }
+ mmap_object *m_obj;
+ PyObject *map_size_obj = NULL, *offset_obj = NULL;
+ Py_ssize_t map_size, offset;
+ int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
+ int devzero = -1;
+ int access = (int)ACCESS_DEFAULT;
+ static char *keywords[] = {"fileno", "length",
+ "flags", "prot",
+ "access", "offset", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords,
+ &fd, &map_size_obj, &flags, &prot,
+ &access, &offset_obj))
+ return NULL;
+ map_size = _GetMapSize(map_size_obj, "size");
+ if (map_size < 0)
+ return NULL;
+ offset = _GetMapSize(offset_obj, "offset");
+ if (offset < 0)
+ return NULL;
+
+ if ((access != (int)ACCESS_DEFAULT) &&
+ ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
+ return PyErr_Format(PyExc_ValueError,
+ "mmap can't specify both access and flags, prot.");
+ switch ((access_mode)access) {
+ case ACCESS_READ:
+ flags = MAP_SHARED;
+ prot = PROT_READ;
+ break;
+ case ACCESS_WRITE:
+ flags = MAP_SHARED;
+ prot = PROT_READ | PROT_WRITE;
+ break;
+ case ACCESS_COPY:
+ flags = MAP_PRIVATE;
+ prot = PROT_READ | PROT_WRITE;
+ break;
+ case ACCESS_DEFAULT:
+ /* use the specified or default values of flags and prot */
+ break;
+ default:
+ return PyErr_Format(PyExc_ValueError,
+ "mmap invalid access parameter.");
+ }
if (prot == PROT_READ) {
- access = ACCESS_READ;
+ access = ACCESS_READ;
}
#ifdef HAVE_FSTAT
# ifdef __VMS
- /* on OpenVMS we must ensure that all bytes are written to the file */
- if (fd != -1) {
- fsync(fd);
- }
+ /* on OpenVMS we must ensure that all bytes are written to the file */
+ if (fd != -1) {
+ fsync(fd);
+ }
# endif
- if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
- if (map_size == 0) {
- map_size = st.st_size;
- } else if ((size_t)offset + (size_t)map_size > st.st_size) {
- PyErr_SetString(PyExc_ValueError,
- "mmap length is greater than file size");
- return NULL;
- }
- }
+ if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
+ if (map_size == 0) {
+ map_size = st.st_size;
+ } else if ((size_t)offset + (size_t)map_size > st.st_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "mmap length is greater than file size");
+ return NULL;
+ }
+ }
#endif
- m_obj = (mmap_object *)type->tp_alloc(type, 0);
- if (m_obj == NULL) {return NULL;}
- m_obj->data = NULL;
- m_obj->size = (size_t) map_size;
- m_obj->pos = (size_t) 0;
- m_obj->exports = 0;
- m_obj->offset = offset;
- if (fd == -1) {
- m_obj->fd = -1;
- /* Assume the caller wants to map anonymous memory.
- This is the same behaviour as Windows. mmap.mmap(-1, size)
- on both Windows and Unix map anonymous memory.
- */
+ m_obj = (mmap_object *)type->tp_alloc(type, 0);
+ if (m_obj == NULL) {return NULL;}
+ m_obj->data = NULL;
+ m_obj->size = (size_t) map_size;
+ m_obj->pos = (size_t) 0;
+ m_obj->exports = 0;
+ m_obj->offset = offset;
+ if (fd == -1) {
+ m_obj->fd = -1;
+ /* Assume the caller wants to map anonymous memory.
+ This is the same behaviour as Windows. mmap.mmap(-1, size)
+ on both Windows and Unix map anonymous memory.
+ */
#ifdef MAP_ANONYMOUS
- /* BSD way to map anonymous memory */
- flags |= MAP_ANONYMOUS;
+ /* BSD way to map anonymous memory */
+ flags |= MAP_ANONYMOUS;
#else
- /* SVR4 method to map anonymous memory is to open /dev/zero */
- fd = devzero = open("/dev/zero", O_RDWR);
- if (devzero == -1) {
- Py_DECREF(m_obj);
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
+ /* SVR4 method to map anonymous memory is to open /dev/zero */
+ fd = devzero = open("/dev/zero", O_RDWR);
+ if (devzero == -1) {
+ Py_DECREF(m_obj);
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
#endif
- } else {
- m_obj->fd = dup(fd);
- if (m_obj->fd == -1) {
- Py_DECREF(m_obj);
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- }
-
- m_obj->data = mmap(NULL, map_size,
- prot, flags,
- fd, offset);
-
- if (devzero != -1) {
- close(devzero);
- }
-
- if (m_obj->data == (char *)-1) {
- m_obj->data = NULL;
- Py_DECREF(m_obj);
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- m_obj->access = (access_mode)access;
- return (PyObject *)m_obj;
+ } else {
+ m_obj->fd = dup(fd);
+ if (m_obj->fd == -1) {
+ Py_DECREF(m_obj);
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ }
+
+ m_obj->data = mmap(NULL, map_size,
+ prot, flags,
+ fd, offset);
+
+ if (devzero != -1) {
+ close(devzero);
+ }
+
+ if (m_obj->data == (char *)-1) {
+ m_obj->data = NULL;
+ Py_DECREF(m_obj);
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ m_obj->access = (access_mode)access;
+ return (PyObject *)m_obj;
}
#endif /* UNIX */
@@ -1145,266 +1145,266 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
static PyObject *
new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
{
- mmap_object *m_obj;
- PyObject *map_size_obj = NULL, *offset_obj = NULL;
- Py_ssize_t map_size, offset;
- DWORD off_hi; /* upper 32 bits of offset */
- DWORD off_lo; /* lower 32 bits of offset */
- DWORD size_hi; /* upper 32 bits of size */
- DWORD size_lo; /* lower 32 bits of size */
- char *tagname = "";
- DWORD dwErr = 0;
- int fileno;
- HANDLE fh = 0;
- int access = (access_mode)ACCESS_DEFAULT;
- DWORD flProtect, dwDesiredAccess;
- static char *keywords[] = { "fileno", "length",
- "tagname",
- "access", "offset", NULL };
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords,
- &fileno, &map_size_obj,
- &tagname, &access, &offset_obj)) {
- return NULL;
- }
-
- switch((access_mode)access) {
- case ACCESS_READ:
- flProtect = PAGE_READONLY;
- dwDesiredAccess = FILE_MAP_READ;
- break;
- case ACCESS_DEFAULT: case ACCESS_WRITE:
- flProtect = PAGE_READWRITE;
- dwDesiredAccess = FILE_MAP_WRITE;
- break;
- case ACCESS_COPY:
- flProtect = PAGE_WRITECOPY;
- dwDesiredAccess = FILE_MAP_COPY;
- break;
- default:
- return PyErr_Format(PyExc_ValueError,
- "mmap invalid access parameter.");
- }
-
- map_size = _GetMapSize(map_size_obj, "size");
- if (map_size < 0)
- return NULL;
- offset = _GetMapSize(offset_obj, "offset");
- if (offset < 0)
- return NULL;
-
- /* assume -1 and 0 both mean invalid filedescriptor
- to 'anonymously' map memory.
- XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5.
- XXX: Should this code be added?
- if (fileno == 0)
- PyErr_WarnEx(PyExc_DeprecationWarning,
- "don't use 0 for anonymous memory",
- 1);
- */
- if (fileno != -1 && fileno != 0) {
- fh = (HANDLE)_get_osfhandle(fileno);
- if (fh==(HANDLE)-1) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- /* Win9x appears to need us seeked to zero */
- lseek(fileno, 0, SEEK_SET);
- }
-
- m_obj = (mmap_object *)type->tp_alloc(type, 0);
- if (m_obj == NULL)
- return NULL;
- /* Set every field to an invalid marker, so we can safely
- destruct the object in the face of failure */
- m_obj->data = NULL;
- m_obj->file_handle = INVALID_HANDLE_VALUE;
- m_obj->map_handle = NULL;
- m_obj->tagname = NULL;
- m_obj->offset = offset;
-
- if (fh) {
- /* It is necessary to duplicate the handle, so the
- Python code can close it on us */
- if (!DuplicateHandle(
- GetCurrentProcess(), /* source process handle */
- fh, /* handle to be duplicated */
- GetCurrentProcess(), /* target proc handle */
- (LPHANDLE)&m_obj->file_handle, /* result */
- 0, /* access - ignored due to options value */
- FALSE, /* inherited by child processes? */
- DUPLICATE_SAME_ACCESS)) { /* options */
- dwErr = GetLastError();
- Py_DECREF(m_obj);
- PyErr_SetFromWindowsErr(dwErr);
- return NULL;
- }
- if (!map_size) {
- DWORD low,high;
- low = GetFileSize(fh, &high);
- /* low might just happen to have the value INVALID_FILE_SIZE;
- so we need to check the last error also. */
- if (low == INVALID_FILE_SIZE &&
- (dwErr = GetLastError()) != NO_ERROR) {
- Py_DECREF(m_obj);
- return PyErr_SetFromWindowsErr(dwErr);
- }
+ mmap_object *m_obj;
+ PyObject *map_size_obj = NULL, *offset_obj = NULL;
+ Py_ssize_t map_size, offset;
+ DWORD off_hi; /* upper 32 bits of offset */
+ DWORD off_lo; /* lower 32 bits of offset */
+ DWORD size_hi; /* upper 32 bits of size */
+ DWORD size_lo; /* lower 32 bits of size */
+ char *tagname = "";
+ DWORD dwErr = 0;
+ int fileno;
+ HANDLE fh = 0;
+ int access = (access_mode)ACCESS_DEFAULT;
+ DWORD flProtect, dwDesiredAccess;
+ static char *keywords[] = { "fileno", "length",
+ "tagname",
+ "access", "offset", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords,
+ &fileno, &map_size_obj,
+ &tagname, &access, &offset_obj)) {
+ return NULL;
+ }
+
+ switch((access_mode)access) {
+ case ACCESS_READ:
+ flProtect = PAGE_READONLY;
+ dwDesiredAccess = FILE_MAP_READ;
+ break;
+ case ACCESS_DEFAULT: case ACCESS_WRITE:
+ flProtect = PAGE_READWRITE;
+ dwDesiredAccess = FILE_MAP_WRITE;
+ break;
+ case ACCESS_COPY:
+ flProtect = PAGE_WRITECOPY;
+ dwDesiredAccess = FILE_MAP_COPY;
+ break;
+ default:
+ return PyErr_Format(PyExc_ValueError,
+ "mmap invalid access parameter.");
+ }
+
+ map_size = _GetMapSize(map_size_obj, "size");
+ if (map_size < 0)
+ return NULL;
+ offset = _GetMapSize(offset_obj, "offset");
+ if (offset < 0)
+ return NULL;
+
+ /* assume -1 and 0 both mean invalid filedescriptor
+ to 'anonymously' map memory.
+ XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5.
+ XXX: Should this code be added?
+ if (fileno == 0)
+ PyErr_WarnEx(PyExc_DeprecationWarning,
+ "don't use 0 for anonymous memory",
+ 1);
+ */
+ if (fileno != -1 && fileno != 0) {
+ fh = (HANDLE)_get_osfhandle(fileno);
+ if (fh==(HANDLE)-1) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ /* Win9x appears to need us seeked to zero */
+ lseek(fileno, 0, SEEK_SET);
+ }
+
+ m_obj = (mmap_object *)type->tp_alloc(type, 0);
+ if (m_obj == NULL)
+ return NULL;
+ /* Set every field to an invalid marker, so we can safely
+ destruct the object in the face of failure */
+ m_obj->data = NULL;
+ m_obj->file_handle = INVALID_HANDLE_VALUE;
+ m_obj->map_handle = NULL;
+ m_obj->tagname = NULL;
+ m_obj->offset = offset;
+
+ if (fh) {
+ /* It is necessary to duplicate the handle, so the
+ Python code can close it on us */
+ if (!DuplicateHandle(
+ GetCurrentProcess(), /* source process handle */
+ fh, /* handle to be duplicated */
+ GetCurrentProcess(), /* target proc handle */
+ (LPHANDLE)&m_obj->file_handle, /* result */
+ 0, /* access - ignored due to options value */
+ FALSE, /* inherited by child processes? */
+ DUPLICATE_SAME_ACCESS)) { /* options */
+ dwErr = GetLastError();
+ Py_DECREF(m_obj);
+ PyErr_SetFromWindowsErr(dwErr);
+ return NULL;
+ }
+ if (!map_size) {
+ DWORD low,high;
+ low = GetFileSize(fh, &high);
+ /* low might just happen to have the value INVALID_FILE_SIZE;
+ so we need to check the last error also. */
+ if (low == INVALID_FILE_SIZE &&
+ (dwErr = GetLastError()) != NO_ERROR) {
+ Py_DECREF(m_obj);
+ return PyErr_SetFromWindowsErr(dwErr);
+ }
#if SIZEOF_SIZE_T > 4
- m_obj->size = (((size_t)high)<<32) + low;
+ m_obj->size = (((size_t)high)<<32) + low;
#else
- if (high)
- /* File is too large to map completely */
- m_obj->size = (size_t)-1;
- else
- m_obj->size = low;
+ if (high)
+ /* File is too large to map completely */
+ m_obj->size = (size_t)-1;
+ else
+ m_obj->size = low;
#endif
- } else {
- m_obj->size = map_size;
- }
- }
- else {
- m_obj->size = map_size;
- }
-
- /* set the initial position */
- m_obj->pos = (size_t) 0;
-
- m_obj->exports = 0;
- /* set the tag name */
- if (tagname != NULL && *tagname != '\0') {
- m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
- if (m_obj->tagname == NULL) {
- PyErr_NoMemory();
- Py_DECREF(m_obj);
- return NULL;
- }
- strcpy(m_obj->tagname, tagname);
- }
- else
- m_obj->tagname = NULL;
-
- m_obj->access = (access_mode)access;
- /* DWORD is a 4-byte int. If we're on a box where size_t consumes
- * more than 4 bytes, we need to break it apart. Else (size_t
- * consumes 4 bytes), C doesn't define what happens if we shift
- * right by 32, so we need different code.
- */
+ } else {
+ m_obj->size = map_size;
+ }
+ }
+ else {
+ m_obj->size = map_size;
+ }
+
+ /* set the initial position */
+ m_obj->pos = (size_t) 0;
+
+ m_obj->exports = 0;
+ /* set the tag name */
+ if (tagname != NULL && *tagname != '\0') {
+ m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
+ if (m_obj->tagname == NULL) {
+ PyErr_NoMemory();
+ Py_DECREF(m_obj);
+ return NULL;
+ }
+ strcpy(m_obj->tagname, tagname);
+ }
+ else
+ m_obj->tagname = NULL;
+
+ m_obj->access = (access_mode)access;
+ /* DWORD is a 4-byte int. If we're on a box where size_t consumes
+ * more than 4 bytes, we need to break it apart. Else (size_t
+ * consumes 4 bytes), C doesn't define what happens if we shift
+ * right by 32, so we need different code.
+ */
#if SIZEOF_SIZE_T > 4
- size_hi = (DWORD)((offset + m_obj->size) >> 32);
- size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF);
- off_hi = (DWORD)(offset >> 32);
- off_lo = (DWORD)(offset & 0xFFFFFFFF);
+ size_hi = (DWORD)((offset + m_obj->size) >> 32);
+ size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF);
+ off_hi = (DWORD)(offset >> 32);
+ off_lo = (DWORD)(offset & 0xFFFFFFFF);
#else
- size_hi = 0;
- size_lo = (DWORD)(offset + m_obj->size);
- off_hi = 0;
- off_lo = (DWORD)offset;
+ size_hi = 0;
+ size_lo = (DWORD)(offset + m_obj->size);
+ off_hi = 0;
+ off_lo = (DWORD)offset;
#endif
- /* For files, it would be sufficient to pass 0 as size.
- For anonymous maps, we have to pass the size explicitly. */
- m_obj->map_handle = CreateFileMapping(m_obj->file_handle,
- NULL,
- flProtect,
- size_hi,
- size_lo,
- m_obj->tagname);
- if (m_obj->map_handle != NULL) {
- m_obj->data = (char *) MapViewOfFile(m_obj->map_handle,
- dwDesiredAccess,
- off_hi,
- off_lo,
- m_obj->size);
- if (m_obj->data != NULL)
- return (PyObject *)m_obj;
- else {
- dwErr = GetLastError();
- CloseHandle(m_obj->map_handle);
- m_obj->map_handle = NULL;
- }
- } else
- dwErr = GetLastError();
- Py_DECREF(m_obj);
- PyErr_SetFromWindowsErr(dwErr);
- return NULL;
+ /* For files, it would be sufficient to pass 0 as size.
+ For anonymous maps, we have to pass the size explicitly. */
+ m_obj->map_handle = CreateFileMapping(m_obj->file_handle,
+ NULL,
+ flProtect,
+ size_hi,
+ size_lo,
+ m_obj->tagname);
+ if (m_obj->map_handle != NULL) {
+ m_obj->data = (char *) MapViewOfFile(m_obj->map_handle,
+ dwDesiredAccess,
+ off_hi,
+ off_lo,
+ m_obj->size);
+ if (m_obj->data != NULL)
+ return (PyObject *)m_obj;
+ else {
+ dwErr = GetLastError();
+ CloseHandle(m_obj->map_handle);
+ m_obj->map_handle = NULL;
+ }
+ } else
+ dwErr = GetLastError();
+ Py_DECREF(m_obj);
+ PyErr_SetFromWindowsErr(dwErr);
+ return NULL;
}
#endif /* MS_WINDOWS */
static void
setint(PyObject *d, const char *name, long value)
{
- PyObject *o = PyLong_FromLong(value);
- if (o && PyDict_SetItemString(d, name, o) == 0) {
- Py_DECREF(o);
- }
+ PyObject *o = PyLong_FromLong(value);
+ if (o && PyDict_SetItemString(d, name, o) == 0) {
+ Py_DECREF(o);
+ }
}
static struct PyModuleDef mmapmodule = {
- PyModuleDef_HEAD_INIT,
- "mmap",
- NULL,
- -1,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "mmap",
+ NULL,
+ -1,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_mmap(void)
{
- PyObject *dict, *module;
-
- if (PyType_Ready(&mmap_object_type) < 0)
- return NULL;
-
- module = PyModule_Create(&mmapmodule);
- if (module == NULL)
- return NULL;
- dict = PyModule_GetDict(module);
- if (!dict)
- return NULL;
- mmap_module_error = PyErr_NewException("mmap.error",
- PyExc_EnvironmentError , NULL);
- if (mmap_module_error == NULL)
- return NULL;
- PyDict_SetItemString(dict, "error", mmap_module_error);
- PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type);
+ PyObject *dict, *module;
+
+ if (PyType_Ready(&mmap_object_type) < 0)
+ return NULL;
+
+ module = PyModule_Create(&mmapmodule);
+ if (module == NULL)
+ return NULL;
+ dict = PyModule_GetDict(module);
+ if (!dict)
+ return NULL;
+ mmap_module_error = PyErr_NewException("mmap.error",
+ PyExc_EnvironmentError , NULL);
+ if (mmap_module_error == NULL)
+ return NULL;
+ PyDict_SetItemString(dict, "error", mmap_module_error);
+ PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type);
#ifdef PROT_EXEC
- setint(dict, "PROT_EXEC", PROT_EXEC);
+ setint(dict, "PROT_EXEC", PROT_EXEC);
#endif
#ifdef PROT_READ
- setint(dict, "PROT_READ", PROT_READ);
+ setint(dict, "PROT_READ", PROT_READ);
#endif
#ifdef PROT_WRITE
- setint(dict, "PROT_WRITE", PROT_WRITE);
+ setint(dict, "PROT_WRITE", PROT_WRITE);
#endif
#ifdef MAP_SHARED
- setint(dict, "MAP_SHARED", MAP_SHARED);
+ setint(dict, "MAP_SHARED", MAP_SHARED);
#endif
#ifdef MAP_PRIVATE
- setint(dict, "MAP_PRIVATE", MAP_PRIVATE);
+ setint(dict, "MAP_PRIVATE", MAP_PRIVATE);
#endif
#ifdef MAP_DENYWRITE
- setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE);
+ setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE);
#endif
#ifdef MAP_EXECUTABLE
- setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE);
+ setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE);
#endif
#ifdef MAP_ANONYMOUS
- setint(dict, "MAP_ANON", MAP_ANONYMOUS);
- setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS);
+ setint(dict, "MAP_ANON", MAP_ANONYMOUS);
+ setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS);
#endif
- setint(dict, "PAGESIZE", (long)my_getpagesize());
+ setint(dict, "PAGESIZE", (long)my_getpagesize());
- setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity());
+ setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity());
- setint(dict, "ACCESS_READ", ACCESS_READ);
- setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
- setint(dict, "ACCESS_COPY", ACCESS_COPY);
- return module;
+ setint(dict, "ACCESS_READ", ACCESS_READ);
+ setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
+ setint(dict, "ACCESS_COPY", ACCESS_COPY);
+ return module;
}
diff --git a/Modules/nismodule.c b/Modules/nismodule.c
index 4be4657..16c7b81 100644
--- a/Modules/nismodule.c
+++ b/Modules/nismodule.c
@@ -1,11 +1,11 @@
/***********************************************************
Written by:
- Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
- B&O group,
- Faculteit der Informatica,
- Universiteit Twente,
- Enschede,
- the Netherlands.
+ Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
+ B&O group,
+ Faculteit der Informatica,
+ Universiteit Twente,
+ Enschede,
+ the Netherlands.
******************************************************************/
/* NIS module implementation */
@@ -23,7 +23,7 @@
extern int yp_get_default_domain(char **);
#endif
-PyDoc_STRVAR(get_default_domain__doc__,
+PyDoc_STRVAR(get_default_domain__doc__,
"get_default_domain() -> str\n\
Corresponds to the C library yp_get_default_domain() call, returning\n\
the default NIS domain.\n");
@@ -49,44 +49,44 @@ static PyObject *NisError;
static PyObject *
nis_error (int err)
{
- PyErr_SetString(NisError, yperr_string(err));
- return NULL;
+ PyErr_SetString(NisError, yperr_string(err));
+ return NULL;
}
static struct nis_map {
- char *alias;
- char *map;
- int fix;
+ char *alias;
+ char *map;
+ int fix;
} aliases [] = {
- {"passwd", "passwd.byname", 0},
- {"group", "group.byname", 0},
- {"networks", "networks.byaddr", 0},
- {"hosts", "hosts.byname", 0},
- {"protocols", "protocols.bynumber", 0},
- {"services", "services.byname", 0},
- {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */
- {"ethers", "ethers.byname", 0},
- {0L, 0L, 0}
+ {"passwd", "passwd.byname", 0},
+ {"group", "group.byname", 0},
+ {"networks", "networks.byaddr", 0},
+ {"hosts", "hosts.byname", 0},
+ {"protocols", "protocols.bynumber", 0},
+ {"services", "services.byname", 0},
+ {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */
+ {"ethers", "ethers.byname", 0},
+ {0L, 0L, 0}
};
static char *
nis_mapname (char *map, int *pfix)
{
- int i;
-
- *pfix = 0;
- for (i=0; aliases[i].alias != 0L; i++) {
- if (!strcmp (aliases[i].alias, map)) {
- *pfix = aliases[i].fix;
- return aliases[i].map;
- }
- if (!strcmp (aliases[i].map, map)) {
- *pfix = aliases[i].fix;
- return aliases[i].map;
- }
- }
-
- return map;
+ int i;
+
+ *pfix = 0;
+ for (i=0; aliases[i].alias != 0L; i++) {
+ if (!strcmp (aliases[i].alias, map)) {
+ *pfix = aliases[i].fix;
+ return aliases[i].map;
+ }
+ if (!strcmp (aliases[i].map, map)) {
+ *pfix = aliases[i].fix;
+ return aliases[i].map;
+ }
+ }
+
+ return map;
}
#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__)
@@ -96,168 +96,168 @@ typedef int (*foreachfunc)(int, char *, int, char *, int, char *);
#endif
struct ypcallback_data {
- PyObject *dict;
- int fix;
- PyThreadState *state;
+ PyObject *dict;
+ int fix;
+ PyThreadState *state;
};
static int
nis_foreach (int instatus, char *inkey, int inkeylen, char *inval,
int invallen, struct ypcallback_data *indata)
{
- if (instatus == YP_TRUE) {
- PyObject *key;
- PyObject *val;
- int err;
-
- PyEval_RestoreThread(indata->state);
- if (indata->fix) {
- if (inkeylen > 0 && inkey[inkeylen-1] == '\0')
- inkeylen--;
- if (invallen > 0 && inval[invallen-1] == '\0')
- invallen--;
- }
- key = PyUnicode_FromStringAndSize(inkey, inkeylen);
- val = PyUnicode_FromStringAndSize(inval, invallen);
- if (key == NULL || val == NULL) {
- /* XXX error -- don't know how to handle */
- PyErr_Clear();
- Py_XDECREF(key);
- Py_XDECREF(val);
- return 1;
- }
- err = PyDict_SetItem(indata->dict, key, val);
- Py_DECREF(key);
- Py_DECREF(val);
- if (err != 0)
- PyErr_Clear();
- indata->state = PyEval_SaveThread();
- if (err != 0)
- return 1;
- return 0;
- }
- return 1;
+ if (instatus == YP_TRUE) {
+ PyObject *key;
+ PyObject *val;
+ int err;
+
+ PyEval_RestoreThread(indata->state);
+ if (indata->fix) {
+ if (inkeylen > 0 && inkey[inkeylen-1] == '\0')
+ inkeylen--;
+ if (invallen > 0 && inval[invallen-1] == '\0')
+ invallen--;
+ }
+ key = PyUnicode_FromStringAndSize(inkey, inkeylen);
+ val = PyUnicode_FromStringAndSize(inval, invallen);
+ if (key == NULL || val == NULL) {
+ /* XXX error -- don't know how to handle */
+ PyErr_Clear();
+ Py_XDECREF(key);
+ Py_XDECREF(val);
+ return 1;
+ }
+ err = PyDict_SetItem(indata->dict, key, val);
+ Py_DECREF(key);
+ Py_DECREF(val);
+ if (err != 0)
+ PyErr_Clear();
+ indata->state = PyEval_SaveThread();
+ if (err != 0)
+ return 1;
+ return 0;
+ }
+ return 1;
}
static PyObject *
nis_get_default_domain (PyObject *self)
{
- char *domain;
- int err;
- PyObject *res;
+ char *domain;
+ int err;
+ PyObject *res;
- if ((err = yp_get_default_domain(&domain)) != 0)
- return nis_error(err);
+ if ((err = yp_get_default_domain(&domain)) != 0)
+ return nis_error(err);
- res = PyUnicode_FromStringAndSize (domain, strlen(domain));
- return res;
+ res = PyUnicode_FromStringAndSize (domain, strlen(domain));
+ return res;
}
static PyObject *
nis_match (PyObject *self, PyObject *args, PyObject *kwdict)
{
- char *match;
- char *domain = NULL;
- int keylen, len;
- char *key, *map;
- int err;
- PyObject *res;
- int fix;
- static char *kwlist[] = {"key", "map", "domain", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict,
- "s#s|s:match", kwlist,
- &key, &keylen, &map, &domain))
- return NULL;
- if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
- return nis_error(err);
- map = nis_mapname (map, &fix);
- if (fix)
- keylen++;
- Py_BEGIN_ALLOW_THREADS
- err = yp_match (domain, map, key, keylen, &match, &len);
- Py_END_ALLOW_THREADS
- if (fix)
- len--;
- if (err != 0)
- return nis_error(err);
- res = PyUnicode_FromStringAndSize (match, len);
- free (match);
- return res;
+ char *match;
+ char *domain = NULL;
+ int keylen, len;
+ char *key, *map;
+ int err;
+ PyObject *res;
+ int fix;
+ static char *kwlist[] = {"key", "map", "domain", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict,
+ "s#s|s:match", kwlist,
+ &key, &keylen, &map, &domain))
+ return NULL;
+ if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
+ return nis_error(err);
+ map = nis_mapname (map, &fix);
+ if (fix)
+ keylen++;
+ Py_BEGIN_ALLOW_THREADS
+ err = yp_match (domain, map, key, keylen, &match, &len);
+ Py_END_ALLOW_THREADS
+ if (fix)
+ len--;
+ if (err != 0)
+ return nis_error(err);
+ res = PyUnicode_FromStringAndSize (match, len);
+ free (match);
+ return res;
}
static PyObject *
nis_cat (PyObject *self, PyObject *args, PyObject *kwdict)
{
- char *domain = NULL;
- char *map;
- struct ypall_callback cb;
- struct ypcallback_data data;
- PyObject *dict;
- int err;
- static char *kwlist[] = {"map", "domain", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
- kwlist, &map, &domain))
- return NULL;
- if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
- return nis_error(err);
- dict = PyDict_New ();
- if (dict == NULL)
- return NULL;
- cb.foreach = (foreachfunc)nis_foreach;
- data.dict = dict;
- map = nis_mapname (map, &data.fix);
- cb.data = (char *)&data;
- data.state = PyEval_SaveThread();
- err = yp_all (domain, map, &cb);
- PyEval_RestoreThread(data.state);
- if (err != 0) {
- Py_DECREF(dict);
- return nis_error(err);
- }
- return dict;
+ char *domain = NULL;
+ char *map;
+ struct ypall_callback cb;
+ struct ypcallback_data data;
+ PyObject *dict;
+ int err;
+ static char *kwlist[] = {"map", "domain", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
+ kwlist, &map, &domain))
+ return NULL;
+ if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
+ return nis_error(err);
+ dict = PyDict_New ();
+ if (dict == NULL)
+ return NULL;
+ cb.foreach = (foreachfunc)nis_foreach;
+ data.dict = dict;
+ map = nis_mapname (map, &data.fix);
+ cb.data = (char *)&data;
+ data.state = PyEval_SaveThread();
+ err = yp_all (domain, map, &cb);
+ PyEval_RestoreThread(data.state);
+ if (err != 0) {
+ Py_DECREF(dict);
+ return nis_error(err);
+ }
+ return dict;
}
/* These should be u_long on Sun h/w but not on 64-bit h/w.
This is not portable to machines with 16-bit ints and no prototypes */
#ifndef YPPROC_MAPLIST
-#define YPPROC_MAPLIST 11
+#define YPPROC_MAPLIST 11
#endif
#ifndef YPPROG
-#define YPPROG 100004
+#define YPPROG 100004
#endif
#ifndef YPVERS
-#define YPVERS 2
+#define YPVERS 2
#endif
typedef char *domainname;
typedef char *mapname;
enum nisstat {
- NIS_TRUE = 1,
- NIS_NOMORE = 2,
- NIS_FALSE = 0,
- NIS_NOMAP = -1,
- NIS_NODOM = -2,
- NIS_NOKEY = -3,
- NIS_BADOP = -4,
- NIS_BADDB = -5,
- NIS_YPERR = -6,
- NIS_BADARGS = -7,
- NIS_VERS = -8
+ NIS_TRUE = 1,
+ NIS_NOMORE = 2,
+ NIS_FALSE = 0,
+ NIS_NOMAP = -1,
+ NIS_NODOM = -2,
+ NIS_NOKEY = -3,
+ NIS_BADOP = -4,
+ NIS_BADDB = -5,
+ NIS_YPERR = -6,
+ NIS_BADARGS = -7,
+ NIS_VERS = -8
};
typedef enum nisstat nisstat;
struct nismaplist {
- mapname map;
- struct nismaplist *next;
+ mapname map;
+ struct nismaplist *next;
};
typedef struct nismaplist nismaplist;
struct nisresp_maplist {
- nisstat stat;
- nismaplist *maps;
+ nisstat stat;
+ nismaplist *maps;
};
typedef struct nisresp_maplist nisresp_maplist;
@@ -267,45 +267,45 @@ static
bool_t
nis_xdr_domainname(XDR *xdrs, domainname *objp)
{
- if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) {
- return (FALSE);
- }
- return (TRUE);
+ if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) {
+ return (FALSE);
+ }
+ return (TRUE);
}
static
bool_t
nis_xdr_mapname(XDR *xdrs, mapname *objp)
{
- if (!xdr_string(xdrs, objp, YPMAXMAP)) {
- return (FALSE);
- }
- return (TRUE);
+ if (!xdr_string(xdrs, objp, YPMAXMAP)) {
+ return (FALSE);
+ }
+ return (TRUE);
}
static
bool_t
nis_xdr_ypmaplist(XDR *xdrs, nismaplist *objp)
{
- if (!nis_xdr_mapname(xdrs, &objp->map)) {
- return (FALSE);
- }
- if (!xdr_pointer(xdrs, (char **)&objp->next,
- sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
- {
- return (FALSE);
- }
- return (TRUE);
+ if (!nis_xdr_mapname(xdrs, &objp->map)) {
+ return (FALSE);
+ }
+ if (!xdr_pointer(xdrs, (char **)&objp->next,
+ sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
+ {
+ return (FALSE);
+ }
+ return (TRUE);
}
static
bool_t
nis_xdr_ypstat(XDR *xdrs, nisstat *objp)
{
- if (!xdr_enum(xdrs, (enum_t *)objp)) {
- return (FALSE);
- }
- return (TRUE);
+ if (!xdr_enum(xdrs, (enum_t *)objp)) {
+ return (FALSE);
+ }
+ return (TRUE);
}
@@ -313,15 +313,15 @@ static
bool_t
nis_xdr_ypresp_maplist(XDR *xdrs, nisresp_maplist *objp)
{
- if (!nis_xdr_ypstat(xdrs, &objp->stat)) {
- return (FALSE);
- }
- if (!xdr_pointer(xdrs, (char **)&objp->maps,
- sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
- {
- return (FALSE);
- }
- return (TRUE);
+ if (!nis_xdr_ypstat(xdrs, &objp->stat)) {
+ return (FALSE);
+ }
+ if (!xdr_pointer(xdrs, (char **)&objp->maps,
+ sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
+ {
+ return (FALSE);
+ }
+ return (TRUE);
}
@@ -329,132 +329,132 @@ static
nisresp_maplist *
nisproc_maplist_2(domainname *argp, CLIENT *clnt)
{
- static nisresp_maplist res;
-
- memset(&res, 0, sizeof(res));
- if (clnt_call(clnt, YPPROC_MAPLIST,
- (xdrproc_t)nis_xdr_domainname, (caddr_t)argp,
- (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res,
- TIMEOUT) != RPC_SUCCESS)
- {
- return (NULL);
- }
- return (&res);
+ static nisresp_maplist res;
+
+ memset(&res, 0, sizeof(res));
+ if (clnt_call(clnt, YPPROC_MAPLIST,
+ (xdrproc_t)nis_xdr_domainname, (caddr_t)argp,
+ (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res,
+ TIMEOUT) != RPC_SUCCESS)
+ {
+ return (NULL);
+ }
+ return (&res);
}
static
nismaplist *
nis_maplist (char *dom)
{
- nisresp_maplist *list;
- CLIENT *cl;
- char *server = NULL;
- int mapi = 0;
-
- while (!server && aliases[mapi].map != 0L) {
- yp_master (dom, aliases[mapi].map, &server);
- mapi++;
- }
- if (!server) {
- PyErr_SetString(NisError, "No NIS master found for any map");
- return NULL;
- }
- cl = clnt_create(server, YPPROG, YPVERS, "tcp");
- if (cl == NULL) {
- PyErr_SetString(NisError, clnt_spcreateerror(server));
- goto finally;
- }
- list = nisproc_maplist_2 (&dom, cl);
- clnt_destroy(cl);
- if (list == NULL)
- goto finally;
- if (list->stat != NIS_TRUE)
- goto finally;
-
- free(server);
- return list->maps;
+ nisresp_maplist *list;
+ CLIENT *cl;
+ char *server = NULL;
+ int mapi = 0;
+
+ while (!server && aliases[mapi].map != 0L) {
+ yp_master (dom, aliases[mapi].map, &server);
+ mapi++;
+ }
+ if (!server) {
+ PyErr_SetString(NisError, "No NIS master found for any map");
+ return NULL;
+ }
+ cl = clnt_create(server, YPPROG, YPVERS, "tcp");
+ if (cl == NULL) {
+ PyErr_SetString(NisError, clnt_spcreateerror(server));
+ goto finally;
+ }
+ list = nisproc_maplist_2 (&dom, cl);
+ clnt_destroy(cl);
+ if (list == NULL)
+ goto finally;
+ if (list->stat != NIS_TRUE)
+ goto finally;
+
+ free(server);
+ return list->maps;
finally:
- free(server);
- return NULL;
+ free(server);
+ return NULL;
}
static PyObject *
nis_maps (PyObject *self, PyObject *args, PyObject *kwdict)
{
- char *domain = NULL;
- nismaplist *maps;
- PyObject *list;
- int err;
- static char *kwlist[] = {"domain", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict,
- "|s:maps", kwlist, &domain))
- return NULL;
- if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) {
- nis_error(err);
- return NULL;
- }
-
- if ((maps = nis_maplist (domain)) == NULL)
- return NULL;
- if ((list = PyList_New(0)) == NULL)
- return NULL;
- for (maps = maps; maps; maps = maps->next) {
- PyObject *str = PyUnicode_FromString(maps->map);
- if (!str || PyList_Append(list, str) < 0)
- {
- Py_DECREF(list);
- list = NULL;
- break;
- }
- Py_DECREF(str);
- }
- /* XXX Shouldn't we free the list of maps now? */
- return list;
+ char *domain = NULL;
+ nismaplist *maps;
+ PyObject *list;
+ int err;
+ static char *kwlist[] = {"domain", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict,
+ "|s:maps", kwlist, &domain))
+ return NULL;
+ if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) {
+ nis_error(err);
+ return NULL;
+ }
+
+ if ((maps = nis_maplist (domain)) == NULL)
+ return NULL;
+ if ((list = PyList_New(0)) == NULL)
+ return NULL;
+ for (maps = maps; maps; maps = maps->next) {
+ PyObject *str = PyUnicode_FromString(maps->map);
+ if (!str || PyList_Append(list, str) < 0)
+ {
+ Py_DECREF(list);
+ list = NULL;
+ break;
+ }
+ Py_DECREF(str);
+ }
+ /* XXX Shouldn't we free the list of maps now? */
+ return list;
}
static PyMethodDef nis_methods[] = {
- {"match", (PyCFunction)nis_match,
- METH_VARARGS | METH_KEYWORDS,
- match__doc__},
- {"cat", (PyCFunction)nis_cat,
- METH_VARARGS | METH_KEYWORDS,
- cat__doc__},
- {"maps", (PyCFunction)nis_maps,
- METH_VARARGS | METH_KEYWORDS,
- maps__doc__},
- {"get_default_domain", (PyCFunction)nis_get_default_domain,
- METH_NOARGS,
- get_default_domain__doc__},
- {NULL, NULL} /* Sentinel */
+ {"match", (PyCFunction)nis_match,
+ METH_VARARGS | METH_KEYWORDS,
+ match__doc__},
+ {"cat", (PyCFunction)nis_cat,
+ METH_VARARGS | METH_KEYWORDS,
+ cat__doc__},
+ {"maps", (PyCFunction)nis_maps,
+ METH_VARARGS | METH_KEYWORDS,
+ maps__doc__},
+ {"get_default_domain", (PyCFunction)nis_get_default_domain,
+ METH_NOARGS,
+ get_default_domain__doc__},
+ {NULL, NULL} /* Sentinel */
};
PyDoc_STRVAR(nis__doc__,
"This module contains functions for accessing NIS maps.\n");
static struct PyModuleDef nismodule = {
- PyModuleDef_HEAD_INIT,
- "nis",
- nis__doc__,
- -1,
- nis_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "nis",
+ nis__doc__,
+ -1,
+ nis_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyObject*
PyInit_nis (void)
{
- PyObject *m, *d;
- m = PyModule_Create(&nismodule);
- if (m == NULL)
- return NULL;
- d = PyModule_GetDict(m);
- NisError = PyErr_NewException("nis.error", NULL, NULL);
- if (NisError != NULL)
- PyDict_SetItemString(d, "error", NisError);
- return m;
+ PyObject *m, *d;
+ m = PyModule_Create(&nismodule);
+ if (m == NULL)
+ return NULL;
+ d = PyModule_GetDict(m);
+ NisError = PyErr_NewException("nis.error", NULL, NULL);
+ if (NisError != NULL)
+ PyDict_SetItemString(d, "error", NisError);
+ return m;
}
diff --git a/Modules/operator.c b/Modules/operator.c
index 85d662d..8ca4d2d 100644
--- a/Modules/operator.c
+++ b/Modules/operator.c
@@ -112,47 +112,47 @@ spamrc(op_ge , Py_GE)
static PyObject*
op_pow(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2;
- if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2))
- return PyNumber_Power(a1, a2, Py_None);
- return NULL;
+ PyObject *a1, *a2;
+ if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2))
+ return PyNumber_Power(a1, a2, Py_None);
+ return NULL;
}
static PyObject*
op_ipow(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2;
- if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2))
- return PyNumber_InPlacePower(a1, a2, Py_None);
- return NULL;
+ PyObject *a1, *a2;
+ if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2))
+ return PyNumber_InPlacePower(a1, a2, Py_None);
+ return NULL;
}
static PyObject *
op_index(PyObject *s, PyObject *a)
{
- return PyNumber_Index(a);
+ return PyNumber_Index(a);
}
static PyObject*
is_(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2, *result = NULL;
- if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) {
- result = (a1 == a2) ? Py_True : Py_False;
- Py_INCREF(result);
- }
- return result;
+ PyObject *a1, *a2, *result = NULL;
+ if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) {
+ result = (a1 == a2) ? Py_True : Py_False;
+ Py_INCREF(result);
+ }
+ return result;
}
static PyObject*
is_not(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2, *result = NULL;
- if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) {
- result = (a1 != a2) ? Py_True : Py_False;
- Py_INCREF(result);
- }
- return result;
+ PyObject *a1, *a2, *result = NULL;
+ if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) {
+ result = (a1 != a2) ? Py_True : Py_False;
+ Py_INCREF(result);
+ }
+ return result;
}
#undef spam1
@@ -161,10 +161,10 @@ is_not(PyObject *s, PyObject *a)
#undef spam1o
#define spam1(OP,DOC) {#OP, OP, METH_VARARGS, PyDoc_STR(DOC)},
#define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \
- {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
+ {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
#define spam1o(OP,DOC) {#OP, OP, METH_O, PyDoc_STR(DOC)},
#define spam2o(OP,ALTOP,DOC) {#OP, op_##OP, METH_O, PyDoc_STR(DOC)}, \
- {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)},
+ {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)},
static struct PyMethodDef operator_methods[] = {
@@ -227,16 +227,16 @@ spam2(ne,__ne__, "ne(a, b) -- Same as a!=b.")
spam2(gt,__gt__, "gt(a, b) -- Same as a>b.")
spam2(ge,__ge__, "ge(a, b) -- Same as a>=b.")
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* itemgetter object **********************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t nitems;
- PyObject *item;
+ PyObject_HEAD
+ Py_ssize_t nitems;
+ PyObject *item;
} itemgetterobject;
static PyTypeObject itemgetter_type;
@@ -244,77 +244,77 @@ static PyTypeObject itemgetter_type;
static PyObject *
itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- itemgetterobject *ig;
- PyObject *item;
- Py_ssize_t nitems;
-
- if (!_PyArg_NoKeywords("itemgetter()", kwds))
- return NULL;
-
- nitems = PyTuple_GET_SIZE(args);
- if (nitems <= 1) {
- if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
- return NULL;
- } else
- item = args;
-
- /* create itemgetterobject structure */
- ig = PyObject_GC_New(itemgetterobject, &itemgetter_type);
- if (ig == NULL)
- return NULL;
-
- Py_INCREF(item);
- ig->item = item;
- ig->nitems = nitems;
-
- PyObject_GC_Track(ig);
- return (PyObject *)ig;
+ itemgetterobject *ig;
+ PyObject *item;
+ Py_ssize_t nitems;
+
+ if (!_PyArg_NoKeywords("itemgetter()", kwds))
+ return NULL;
+
+ nitems = PyTuple_GET_SIZE(args);
+ if (nitems <= 1) {
+ if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
+ return NULL;
+ } else
+ item = args;
+
+ /* create itemgetterobject structure */
+ ig = PyObject_GC_New(itemgetterobject, &itemgetter_type);
+ if (ig == NULL)
+ return NULL;
+
+ Py_INCREF(item);
+ ig->item = item;
+ ig->nitems = nitems;
+
+ PyObject_GC_Track(ig);
+ return (PyObject *)ig;
}
static void
itemgetter_dealloc(itemgetterobject *ig)
{
- PyObject_GC_UnTrack(ig);
- Py_XDECREF(ig->item);
- PyObject_GC_Del(ig);
+ PyObject_GC_UnTrack(ig);
+ Py_XDECREF(ig->item);
+ PyObject_GC_Del(ig);
}
static int
itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg)
{
- Py_VISIT(ig->item);
- return 0;
+ Py_VISIT(ig->item);
+ return 0;
}
static PyObject *
itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw)
{
- PyObject *obj, *result;
- Py_ssize_t i, nitems=ig->nitems;
-
- if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
- return NULL;
- if (nitems == 1)
- return PyObject_GetItem(obj, ig->item);
-
- assert(PyTuple_Check(ig->item));
- assert(PyTuple_GET_SIZE(ig->item) == nitems);
-
- result = PyTuple_New(nitems);
- if (result == NULL)
- return NULL;
-
- for (i=0 ; i < nitems ; i++) {
- PyObject *item, *val;
- item = PyTuple_GET_ITEM(ig->item, i);
- val = PyObject_GetItem(obj, item);
- if (val == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, val);
- }
- return result;
+ PyObject *obj, *result;
+ Py_ssize_t i, nitems=ig->nitems;
+
+ if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
+ return NULL;
+ if (nitems == 1)
+ return PyObject_GetItem(obj, ig->item);
+
+ assert(PyTuple_Check(ig->item));
+ assert(PyTuple_GET_SIZE(ig->item) == nitems);
+
+ result = PyTuple_New(nitems);
+ if (result == NULL)
+ return NULL;
+
+ for (i=0 ; i < nitems ; i++) {
+ PyObject *item, *val;
+ item = PyTuple_GET_ITEM(ig->item, i);
+ val = PyObject_GetItem(obj, item);
+ if (val == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, val);
+ }
+ return result;
}
PyDoc_STRVAR(itemgetter_doc,
@@ -325,55 +325,55 @@ After, f=itemgetter(2), the call f(r) returns r[2].\n\
After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])");
static PyTypeObject itemgetter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "operator.itemgetter", /* tp_name */
- sizeof(itemgetterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)itemgetter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)itemgetter_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- itemgetter_doc, /* tp_doc */
- (traverseproc)itemgetter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- itemgetter_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "operator.itemgetter", /* tp_name */
+ sizeof(itemgetterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)itemgetter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)itemgetter_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ itemgetter_doc, /* tp_doc */
+ (traverseproc)itemgetter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ itemgetter_new, /* tp_new */
+ 0, /* tp_free */
};
/* attrgetter object **********************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t nattrs;
- PyObject *attr;
+ PyObject_HEAD
+ Py_ssize_t nattrs;
+ PyObject *attr;
} attrgetterobject;
static PyTypeObject attrgetter_type;
@@ -381,112 +381,112 @@ static PyTypeObject attrgetter_type;
static PyObject *
attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- attrgetterobject *ag;
- PyObject *attr;
- Py_ssize_t nattrs;
-
- if (!_PyArg_NoKeywords("attrgetter()", kwds))
- return NULL;
-
- nattrs = PyTuple_GET_SIZE(args);
- if (nattrs <= 1) {
- if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
- return NULL;
- } else
- attr = args;
-
- /* create attrgetterobject structure */
- ag = PyObject_GC_New(attrgetterobject, &attrgetter_type);
- if (ag == NULL)
- return NULL;
-
- Py_INCREF(attr);
- ag->attr = attr;
- ag->nattrs = nattrs;
-
- PyObject_GC_Track(ag);
- return (PyObject *)ag;
+ attrgetterobject *ag;
+ PyObject *attr;
+ Py_ssize_t nattrs;
+
+ if (!_PyArg_NoKeywords("attrgetter()", kwds))
+ return NULL;
+
+ nattrs = PyTuple_GET_SIZE(args);
+ if (nattrs <= 1) {
+ if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
+ return NULL;
+ } else
+ attr = args;
+
+ /* create attrgetterobject structure */
+ ag = PyObject_GC_New(attrgetterobject, &attrgetter_type);
+ if (ag == NULL)
+ return NULL;
+
+ Py_INCREF(attr);
+ ag->attr = attr;
+ ag->nattrs = nattrs;
+
+ PyObject_GC_Track(ag);
+ return (PyObject *)ag;
}
static void
attrgetter_dealloc(attrgetterobject *ag)
{
- PyObject_GC_UnTrack(ag);
- Py_XDECREF(ag->attr);
- PyObject_GC_Del(ag);
+ PyObject_GC_UnTrack(ag);
+ Py_XDECREF(ag->attr);
+ PyObject_GC_Del(ag);
}
static int
attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg)
{
- Py_VISIT(ag->attr);
- return 0;
+ Py_VISIT(ag->attr);
+ return 0;
}
static PyObject *
dotted_getattr(PyObject *obj, PyObject *attr)
{
- char *s, *p;
-
- if (!PyUnicode_Check(attr)) {
- PyErr_SetString(PyExc_TypeError,
- "attribute name must be a string");
- return NULL;
- }
-
- s = _PyUnicode_AsString(attr);
- Py_INCREF(obj);
- for (;;) {
- PyObject *newobj, *str;
- p = strchr(s, '.');
- str = p ? PyUnicode_FromStringAndSize(s, (p-s)) :
- PyUnicode_FromString(s);
- if (str == NULL) {
- Py_DECREF(obj);
- return NULL;
- }
- newobj = PyObject_GetAttr(obj, str);
- Py_DECREF(str);
- Py_DECREF(obj);
- if (newobj == NULL)
- return NULL;
- obj = newobj;
- if (p == NULL) break;
- s = p+1;
- }
-
- return obj;
+ char *s, *p;
+
+ if (!PyUnicode_Check(attr)) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute name must be a string");
+ return NULL;
+ }
+
+ s = _PyUnicode_AsString(attr);
+ Py_INCREF(obj);
+ for (;;) {
+ PyObject *newobj, *str;
+ p = strchr(s, '.');
+ str = p ? PyUnicode_FromStringAndSize(s, (p-s)) :
+ PyUnicode_FromString(s);
+ if (str == NULL) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ newobj = PyObject_GetAttr(obj, str);
+ Py_DECREF(str);
+ Py_DECREF(obj);
+ if (newobj == NULL)
+ return NULL;
+ obj = newobj;
+ if (p == NULL) break;
+ s = p+1;
+ }
+
+ return obj;
}
static PyObject *
attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw)
{
- PyObject *obj, *result;
- Py_ssize_t i, nattrs=ag->nattrs;
-
- if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
- return NULL;
- if (ag->nattrs == 1)
- return dotted_getattr(obj, ag->attr);
-
- assert(PyTuple_Check(ag->attr));
- assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
-
- result = PyTuple_New(nattrs);
- if (result == NULL)
- return NULL;
-
- for (i=0 ; i < nattrs ; i++) {
- PyObject *attr, *val;
- attr = PyTuple_GET_ITEM(ag->attr, i);
- val = dotted_getattr(obj, attr);
- if (val == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, val);
- }
- return result;
+ PyObject *obj, *result;
+ Py_ssize_t i, nattrs=ag->nattrs;
+
+ if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
+ return NULL;
+ if (ag->nattrs == 1)
+ return dotted_getattr(obj, ag->attr);
+
+ assert(PyTuple_Check(ag->attr));
+ assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
+
+ result = PyTuple_New(nattrs);
+ if (result == NULL)
+ return NULL;
+
+ for (i=0 ; i < nattrs ; i++) {
+ PyObject *attr, *val;
+ attr = PyTuple_GET_ITEM(ag->attr, i);
+ val = dotted_getattr(obj, attr);
+ if (val == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, val);
+ }
+ return result;
}
PyDoc_STRVAR(attrgetter_doc,
@@ -499,56 +499,56 @@ After, h=attrgetter('name.first', 'name.last'), the call h(r) returns\n\
(r.name.first, r.name.last).");
static PyTypeObject attrgetter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "operator.attrgetter", /* tp_name */
- sizeof(attrgetterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)attrgetter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)attrgetter_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- attrgetter_doc, /* tp_doc */
- (traverseproc)attrgetter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- attrgetter_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "operator.attrgetter", /* tp_name */
+ sizeof(attrgetterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)attrgetter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)attrgetter_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ attrgetter_doc, /* tp_doc */
+ (traverseproc)attrgetter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ attrgetter_new, /* tp_new */
+ 0, /* tp_free */
};
/* methodcaller object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *name;
- PyObject *args;
- PyObject *kwds;
+ PyObject_HEAD
+ PyObject *name;
+ PyObject *args;
+ PyObject *kwds;
} methodcallerobject;
static PyTypeObject methodcaller_type;
@@ -556,69 +556,69 @@ static PyTypeObject methodcaller_type;
static PyObject *
methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- methodcallerobject *mc;
- PyObject *name, *newargs;
-
- if (PyTuple_GET_SIZE(args) < 1) {
- PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
- "one argument, the method name");
- return NULL;
- }
-
- /* create methodcallerobject structure */
- mc = PyObject_GC_New(methodcallerobject, &methodcaller_type);
- if (mc == NULL)
- return NULL;
-
- newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
- if (newargs == NULL) {
- Py_DECREF(mc);
- return NULL;
- }
- mc->args = newargs;
-
- name = PyTuple_GET_ITEM(args, 0);
- Py_INCREF(name);
- mc->name = name;
-
- Py_XINCREF(kwds);
- mc->kwds = kwds;
-
- PyObject_GC_Track(mc);
- return (PyObject *)mc;
+ methodcallerobject *mc;
+ PyObject *name, *newargs;
+
+ if (PyTuple_GET_SIZE(args) < 1) {
+ PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
+ "one argument, the method name");
+ return NULL;
+ }
+
+ /* create methodcallerobject structure */
+ mc = PyObject_GC_New(methodcallerobject, &methodcaller_type);
+ if (mc == NULL)
+ return NULL;
+
+ newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
+ if (newargs == NULL) {
+ Py_DECREF(mc);
+ return NULL;
+ }
+ mc->args = newargs;
+
+ name = PyTuple_GET_ITEM(args, 0);
+ Py_INCREF(name);
+ mc->name = name;
+
+ Py_XINCREF(kwds);
+ mc->kwds = kwds;
+
+ PyObject_GC_Track(mc);
+ return (PyObject *)mc;
}
static void
methodcaller_dealloc(methodcallerobject *mc)
{
- PyObject_GC_UnTrack(mc);
- Py_XDECREF(mc->name);
- Py_XDECREF(mc->args);
- Py_XDECREF(mc->kwds);
- PyObject_GC_Del(mc);
+ PyObject_GC_UnTrack(mc);
+ Py_XDECREF(mc->name);
+ Py_XDECREF(mc->args);
+ Py_XDECREF(mc->kwds);
+ PyObject_GC_Del(mc);
}
static int
methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg)
{
- Py_VISIT(mc->args);
- Py_VISIT(mc->kwds);
- return 0;
+ Py_VISIT(mc->args);
+ Py_VISIT(mc->kwds);
+ return 0;
}
static PyObject *
methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw)
{
- PyObject *method, *obj, *result;
-
- if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
- return NULL;
- method = PyObject_GetAttr(obj, mc->name);
- if (method == NULL)
- return NULL;
- result = PyObject_Call(method, mc->args, mc->kwds);
- Py_DECREF(method);
- return result;
+ PyObject *method, *obj, *result;
+
+ if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
+ return NULL;
+ method = PyObject_GetAttr(obj, mc->name);
+ if (method == NULL)
+ return NULL;
+ result = PyObject_Call(method, mc->args, mc->kwds);
+ Py_DECREF(method);
+ return result;
}
PyDoc_STRVAR(methodcaller_doc,
@@ -630,46 +630,46 @@ After, g = methodcaller('name', 'date', foo=1), the call g(r) returns\n\
r.name('date', foo=1).");
static PyTypeObject methodcaller_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "operator.methodcaller", /* tp_name */
- sizeof(methodcallerobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)methodcaller_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)methodcaller_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- methodcaller_doc, /* tp_doc */
- (traverseproc)methodcaller_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- methodcaller_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "operator.methodcaller", /* tp_name */
+ sizeof(methodcallerobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)methodcaller_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)methodcaller_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ methodcaller_doc, /* tp_doc */
+ (traverseproc)methodcaller_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ methodcaller_new, /* tp_new */
+ 0, /* tp_free */
};
@@ -677,40 +677,40 @@ static PyTypeObject methodcaller_type = {
static struct PyModuleDef operatormodule = {
- PyModuleDef_HEAD_INIT,
- "operator",
- operator_doc,
- -1,
- operator_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "operator",
+ operator_doc,
+ -1,
+ operator_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_operator(void)
{
- PyObject *m;
-
- /* Create the module and add the functions */
- m = PyModule_Create(&operatormodule);
- if (m == NULL)
- return NULL;
-
- if (PyType_Ready(&itemgetter_type) < 0)
- return NULL;
- Py_INCREF(&itemgetter_type);
- PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
-
- if (PyType_Ready(&attrgetter_type) < 0)
- return NULL;
- Py_INCREF(&attrgetter_type);
- PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
-
- if (PyType_Ready(&methodcaller_type) < 0)
- return NULL;
- Py_INCREF(&methodcaller_type);
- PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
- return m;
+ PyObject *m;
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&operatormodule);
+ if (m == NULL)
+ return NULL;
+
+ if (PyType_Ready(&itemgetter_type) < 0)
+ return NULL;
+ Py_INCREF(&itemgetter_type);
+ PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
+
+ if (PyType_Ready(&attrgetter_type) < 0)
+ return NULL;
+ Py_INCREF(&attrgetter_type);
+ PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
+
+ if (PyType_Ready(&methodcaller_type) < 0)
+ return NULL;
+ Py_INCREF(&methodcaller_type);
+ PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
+ return m;
}
diff --git a/Modules/ossaudiodev.c b/Modules/ossaudiodev.c
index 6654d71..5c990ef 100644
--- a/Modules/ossaudiodev.c
+++ b/Modules/ossaudiodev.c
@@ -809,8 +809,8 @@ oss_getattro(oss_audio_t *self, PyObject *nameobj)
PyObject * rval = NULL;
if (PyUnicode_Check(nameobj))
- name = _PyUnicode_AsString(nameobj);
-
+ name = _PyUnicode_AsString(nameobj);
+
if (strcmp(name, "closed") == 0) {
rval = (self->fd == -1) ? Py_True : Py_False;
Py_INCREF(rval);
@@ -975,15 +975,15 @@ error1:
static struct PyModuleDef ossaudiodevmodule = {
- PyModuleDef_HEAD_INIT,
- "ossaudiodev",
- NULL,
- -1,
- ossaudiodev_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "ossaudiodev",
+ NULL,
+ -1,
+ ossaudiodev_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -999,10 +999,10 @@ PyInit_ossaudiodev(void)
m = PyModule_Create(&ossaudiodevmodule);
if (m == NULL)
- return NULL;
+ return NULL;
OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError",
- NULL, NULL);
+ NULL, NULL);
if (OSSAudioError) {
/* Each call to PyModule_AddObject decrefs it; compensate: */
Py_INCREF(OSSAudioError);
diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c
index 2fa8529..3e0f530 100644
--- a/Modules/parsermodule.c
+++ b/Modules/parsermodule.c
@@ -578,8 +578,8 @@ parser_do_parse(PyObject *args, PyObject *kw, char *argspec, int type)
? eval_input : file_input,
&err, &flags);
- if (n) {
- res = parser_newstobject(n, type);
+ if (n) {
+ res = parser_newstobject(n, type);
if (res)
((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK;
}
@@ -784,7 +784,7 @@ build_node_children(PyObject *tuple, node *root, int *line_num)
PyErr_Format(parser_error,
"third item in terminal node must be an"
" integer, found %s",
- Py_TYPE(temp)->tp_name);
+ Py_TYPE(temp)->tp_name);
Py_DECREF(o);
Py_DECREF(temp);
Py_DECREF(elem);
@@ -1051,7 +1051,7 @@ validate_class(node *tree)
{
int nch = NCH(tree);
int res = (validate_ntype(tree, classdef) &&
- ((nch == 4) || (nch == 6) || (nch == 7)));
+ ((nch == 4) || (nch == 6) || (nch == 7)));
if (res) {
res = (validate_name(CHILD(tree, 0), "class")
@@ -1064,15 +1064,15 @@ validate_class(node *tree)
}
if (res) {
- if (nch == 7) {
- res = ((validate_lparen(CHILD(tree, 2)) &&
- validate_arglist(CHILD(tree, 3)) &&
- validate_rparen(CHILD(tree, 4))));
- }
- else if (nch == 6) {
- res = (validate_lparen(CHILD(tree,2)) &&
- validate_rparen(CHILD(tree,3)));
- }
+ if (nch == 7) {
+ res = ((validate_lparen(CHILD(tree, 2)) &&
+ validate_arglist(CHILD(tree, 3)) &&
+ validate_rparen(CHILD(tree, 4))));
+ }
+ else if (nch == 6) {
+ res = (validate_lparen(CHILD(tree,2)) &&
+ validate_rparen(CHILD(tree,3)));
+ }
}
return (res);
}
@@ -1244,10 +1244,10 @@ validate_varargslist_trailer(node *tree, int start)
else {
/* skip over vfpdef (',' vfpdef ['=' test])* */
i = start + 1;
- if (TYPE(CHILD(tree, i)) == vfpdef ||
- TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */
- i += 1;
- }
+ if (TYPE(CHILD(tree, i)) == vfpdef ||
+ TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */
+ i += 1;
+ }
while (res && i+1 < nch) { /* validate (',' vfpdef ['=' test])* */
res = validate_comma(CHILD(tree, i));
if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR)
@@ -1718,14 +1718,14 @@ validate_dotted_as_name(node *tree)
static int
validate_dotted_as_names(node *tree)
{
- int nch = NCH(tree);
- int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
- int i;
+ int nch = NCH(tree);
+ int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
+ int i;
- for (i = 1; res && (i < nch); i += 2)
- res = (validate_comma(CHILD(tree, i))
- && validate_dotted_as_name(CHILD(tree, i + 1)));
- return (res);
+ for (i = 1; res && (i < nch); i += 2)
+ res = (validate_comma(CHILD(tree, i))
+ && validate_dotted_as_name(CHILD(tree, i + 1)));
+ return (res);
}
@@ -1738,8 +1738,8 @@ validate_import_as_names(node *tree)
int i;
for (i = 1; res && (i + 1 < nch); i += 2)
- res = (validate_comma(CHILD(tree, i))
- && validate_import_as_name(CHILD(tree, i + 1)));
+ res = (validate_comma(CHILD(tree, i))
+ && validate_import_as_name(CHILD(tree, i + 1)));
return (res);
}
@@ -1748,10 +1748,10 @@ validate_import_as_names(node *tree)
static int
validate_import_name(node *tree)
{
- return (validate_ntype(tree, import_name)
- && validate_numnodes(tree, 2, "import_name")
- && validate_name(CHILD(tree, 0), "import")
- && validate_dotted_as_names(CHILD(tree, 1)));
+ return (validate_ntype(tree, import_name)
+ && validate_numnodes(tree, 2, "import_name")
+ && validate_name(CHILD(tree, 0), "import")
+ && validate_dotted_as_names(CHILD(tree, 1)));
}
/* Helper function to count the number of leading dots in
@@ -1762,8 +1762,8 @@ count_from_dots(node *tree)
{
int i;
for (i = 1; i < NCH(tree); i++)
- if (TYPE(CHILD(tree, i)) != DOT)
- break;
+ if (TYPE(CHILD(tree, i)) != DOT)
+ break;
return i-1;
}
@@ -1773,24 +1773,24 @@ count_from_dots(node *tree)
static int
validate_import_from(node *tree)
{
- int nch = NCH(tree);
- int ndots = count_from_dots(tree);
- int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
- int offset = ndots + havename;
- int res = validate_ntype(tree, import_from)
- && (nch >= 4 + ndots)
- && validate_name(CHILD(tree, 0), "from")
- && (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
- && validate_name(CHILD(tree, offset + 1), "import");
-
- if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
- res = ((nch == offset + 5)
- && validate_lparen(CHILD(tree, offset + 2))
- && validate_import_as_names(CHILD(tree, offset + 3))
- && validate_rparen(CHILD(tree, offset + 4)));
- else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
- res = validate_import_as_names(CHILD(tree, offset + 2));
- return (res);
+ int nch = NCH(tree);
+ int ndots = count_from_dots(tree);
+ int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
+ int offset = ndots + havename;
+ int res = validate_ntype(tree, import_from)
+ && (nch >= 4 + ndots)
+ && validate_name(CHILD(tree, 0), "from")
+ && (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
+ && validate_name(CHILD(tree, offset + 1), "import");
+
+ if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
+ res = ((nch == offset + 5)
+ && validate_lparen(CHILD(tree, offset + 2))
+ && validate_import_as_names(CHILD(tree, offset + 3))
+ && validate_rparen(CHILD(tree, offset + 4)));
+ else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
+ res = validate_import_as_names(CHILD(tree, offset + 2));
+ return (res);
}
@@ -1802,9 +1802,9 @@ validate_import_stmt(node *tree)
int res = validate_numnodes(tree, 1, "import_stmt");
if (res) {
- int ntype = TYPE(CHILD(tree, 0));
+ int ntype = TYPE(CHILD(tree, 0));
- if (ntype == import_name || ntype == import_from)
+ if (ntype == import_name || ntype == import_from)
res = validate_node(CHILD(tree, 0));
else {
res = 0;
@@ -2323,11 +2323,11 @@ validate_atom(node *tree)
&& (validate_rparen(CHILD(tree, nch - 1))));
if (res && (nch == 3)) {
- if (TYPE(CHILD(tree, 1))==yield_expr)
- res = validate_yield_expr(CHILD(tree, 1));
- else
- res = validate_testlist_comp(CHILD(tree, 1));
- }
+ if (TYPE(CHILD(tree, 1))==yield_expr)
+ res = validate_yield_expr(CHILD(tree, 1));
+ else
+ res = validate_testlist_comp(CHILD(tree, 1));
+ }
break;
case LSQB:
if (nch == 2)
@@ -2355,11 +2355,11 @@ validate_atom(node *tree)
for (pos = 1; res && (pos < nch); ++pos)
res = validate_ntype(CHILD(tree, pos), STRING);
break;
- case DOT:
- res = (nch == 3 &&
- validate_ntype(CHILD(tree, 1), DOT) &&
- validate_ntype(CHILD(tree, 2), DOT));
- break;
+ case DOT:
+ res = (nch == 3 &&
+ validate_ntype(CHILD(tree, 1), DOT) &&
+ validate_ntype(CHILD(tree, 2), DOT));
+ break;
default:
res = 0;
break;
@@ -2416,17 +2416,17 @@ validate_decorator(node *tree)
int ok;
int nch = NCH(tree);
ok = (validate_ntype(tree, decorator) &&
- (nch == 3 || nch == 5 || nch == 6) &&
- validate_at(CHILD(tree, 0)) &&
- validate_dotted_name(CHILD(tree, 1)) &&
- validate_newline(RCHILD(tree, -1)));
+ (nch == 3 || nch == 5 || nch == 6) &&
+ validate_at(CHILD(tree, 0)) &&
+ validate_dotted_name(CHILD(tree, 1)) &&
+ validate_newline(RCHILD(tree, -1)));
if (ok && nch != 3) {
- ok = (validate_lparen(CHILD(tree, 2)) &&
- validate_rparen(RCHILD(tree, -2)));
+ ok = (validate_lparen(CHILD(tree, 2)) &&
+ validate_rparen(RCHILD(tree, -2)));
- if (ok && nch == 6)
- ok = validate_arglist(CHILD(tree, 3));
+ if (ok && nch == 6)
+ ok = validate_arglist(CHILD(tree, 3));
}
return ok;
@@ -2443,7 +2443,7 @@ validate_decorators(node *tree)
ok = validate_ntype(tree, decorators) && nch >= 1;
for (i = 0; ok && i < nch; ++i)
- ok = validate_decorator(CHILD(tree, i));
+ ok = validate_decorator(CHILD(tree, i));
return ok;
}
@@ -2458,7 +2458,7 @@ validate_with_item(node *tree)
int ok = (validate_ntype(tree, with_item)
&& (nch == 1 || nch == 3)
&& validate_test(CHILD(tree, 0)));
- if (ok && nch == 3)
+ if (ok && nch == 3)
ok = (validate_name(CHILD(tree, 1), "as")
&& validate_expr(CHILD(tree, 2)));
return ok;
@@ -2493,12 +2493,12 @@ validate_funcdef(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, funcdef)
- && (nch == 5)
- && validate_name(RCHILD(tree, -5), "def")
- && validate_ntype(RCHILD(tree, -4), NAME)
- && validate_colon(RCHILD(tree, -2))
- && validate_parameters(RCHILD(tree, -3))
- && validate_suite(RCHILD(tree, -1)));
+ && (nch == 5)
+ && validate_name(RCHILD(tree, -5), "def")
+ && validate_ntype(RCHILD(tree, -4), NAME)
+ && validate_colon(RCHILD(tree, -2))
+ && validate_parameters(RCHILD(tree, -3))
+ && validate_suite(RCHILD(tree, -1)));
return ok;
}
@@ -2511,11 +2511,11 @@ validate_decorated(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, decorated)
- && (nch == 2)
- && validate_decorators(RCHILD(tree, -2))
- && (validate_funcdef(RCHILD(tree, -1))
- || validate_class(RCHILD(tree, -1)))
- );
+ && (nch == 2)
+ && validate_decorators(RCHILD(tree, -2))
+ && (validate_funcdef(RCHILD(tree, -1))
+ || validate_class(RCHILD(tree, -1)))
+ );
return ok;
}
@@ -2882,9 +2882,9 @@ validate_node(node *tree)
case classdef:
res = validate_class(tree);
break;
- case decorated:
- res = validate_decorated(tree);
- break;
+ case decorated:
+ res = validate_decorated(tree);
+ break;
/*
* "Trivial" parse tree nodes.
* (Why did I call these trivial?)
@@ -2953,12 +2953,12 @@ validate_node(node *tree)
case import_stmt:
res = validate_import_stmt(tree);
break;
- case import_name:
- res = validate_import_name(tree);
- break;
- case import_from:
- res = validate_import_from(tree);
- break;
+ case import_name:
+ res = validate_import_name(tree);
+ break;
+ case import_from:
+ res = validate_import_from(tree);
+ break;
case global_stmt:
res = validate_global_stmt(tree);
break;
@@ -3170,15 +3170,15 @@ static PyMethodDef parser_functions[] = {
static struct PyModuleDef parsermodule = {
- PyModuleDef_HEAD_INIT,
- "parser",
- NULL,
- -1,
- parser_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "parser",
+ NULL,
+ -1,
+ parser_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC PyInit_parser(void); /* supply a prototype */
@@ -3192,7 +3192,7 @@ PyInit_parser(void)
return NULL;
module = PyModule_Create(&parsermodule);
if (module == NULL)
- return NULL;
+ return NULL;
if (parser_error == 0)
parser_error = PyErr_NewException("parser.ParserError", NULL, NULL);
diff --git a/Modules/pwdmodule.c b/Modules/pwdmodule.c
index 6a6f0de..35a387a 100644
--- a/Modules/pwdmodule.c
+++ b/Modules/pwdmodule.c
@@ -8,14 +8,14 @@
#include <pwd.h>
static PyStructSequence_Field struct_pwd_type_fields[] = {
- {"pw_name", "user name"},
- {"pw_passwd", "password"},
- {"pw_uid", "user id"},
- {"pw_gid", "group id"},
- {"pw_gecos", "real name"},
- {"pw_dir", "home directory"},
- {"pw_shell", "shell program"},
- {0}
+ {"pw_name", "user name"},
+ {"pw_passwd", "password"},
+ {"pw_uid", "user id"},
+ {"pw_gid", "group id"},
+ {"pw_gecos", "real name"},
+ {"pw_dir", "home directory"},
+ {"pw_shell", "shell program"},
+ {0}
};
PyDoc_STRVAR(struct_passwd__doc__,
@@ -25,10 +25,10 @@ This object may be accessed either as a tuple of\n\
or via the object attributes as named in the above tuple.");
static PyStructSequence_Desc struct_pwd_type_desc = {
- "pwd.struct_passwd",
- struct_passwd__doc__,
- struct_pwd_type_fields,
- 7,
+ "pwd.struct_passwd",
+ struct_passwd__doc__,
+ struct_pwd_type_fields,
+ 7,
};
PyDoc_STRVAR(pwd__doc__,
@@ -41,7 +41,7 @@ pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell.\n\
The uid and gid items are integers, all others are strings. An\n\
exception is raised if the entry asked for cannot be found.");
-
+
static int initialized;
static PyTypeObject StructPwdType;
@@ -49,51 +49,51 @@ static void
sets(PyObject *v, int i, const char* val)
{
if (val) {
- PyObject *o = PyUnicode_DecodeFSDefault(val);
- PyStructSequence_SET_ITEM(v, i, o);
+ PyObject *o = PyUnicode_DecodeFSDefault(val);
+ PyStructSequence_SET_ITEM(v, i, o);
}
else {
- PyStructSequence_SET_ITEM(v, i, Py_None);
- Py_INCREF(Py_None);
+ PyStructSequence_SET_ITEM(v, i, Py_None);
+ Py_INCREF(Py_None);
}
}
static PyObject *
mkpwent(struct passwd *p)
{
- int setIndex = 0;
- PyObject *v = PyStructSequence_New(&StructPwdType);
- if (v == NULL)
- return NULL;
+ int setIndex = 0;
+ PyObject *v = PyStructSequence_New(&StructPwdType);
+ if (v == NULL)
+ return NULL;
#define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
#define SETS(i,val) sets(v, i, val)
- SETS(setIndex++, p->pw_name);
+ SETS(setIndex++, p->pw_name);
#ifdef __VMS
- SETS(setIndex++, "");
+ SETS(setIndex++, "");
#else
- SETS(setIndex++, p->pw_passwd);
+ SETS(setIndex++, p->pw_passwd);
#endif
- SETI(setIndex++, p->pw_uid);
- SETI(setIndex++, p->pw_gid);
+ SETI(setIndex++, p->pw_uid);
+ SETI(setIndex++, p->pw_gid);
#ifdef __VMS
- SETS(setIndex++, "");
+ SETS(setIndex++, "");
#else
- SETS(setIndex++, p->pw_gecos);
+ SETS(setIndex++, p->pw_gecos);
#endif
- SETS(setIndex++, p->pw_dir);
- SETS(setIndex++, p->pw_shell);
+ SETS(setIndex++, p->pw_dir);
+ SETS(setIndex++, p->pw_shell);
#undef SETS
#undef SETI
- if (PyErr_Occurred()) {
- Py_XDECREF(v);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v);
+ return NULL;
+ }
- return v;
+ return v;
}
PyDoc_STRVAR(pwd_getpwuid__doc__,
@@ -105,16 +105,16 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwuid(PyObject *self, PyObject *args)
{
- unsigned int uid;
- struct passwd *p;
- if (!PyArg_ParseTuple(args, "I:getpwuid", &uid))
- return NULL;
- if ((p = getpwuid(uid)) == NULL) {
- PyErr_Format(PyExc_KeyError,
- "getpwuid(): uid not found: %d", uid);
- return NULL;
- }
- return mkpwent(p);
+ unsigned int uid;
+ struct passwd *p;
+ if (!PyArg_ParseTuple(args, "I:getpwuid", &uid))
+ return NULL;
+ if ((p = getpwuid(uid)) == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "getpwuid(): uid not found: %d", uid);
+ return NULL;
+ }
+ return mkpwent(p);
}
PyDoc_STRVAR(pwd_getpwnam__doc__,
@@ -126,27 +126,27 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwnam(PyObject *self, PyObject *args)
{
- char *name;
- struct passwd *p;
- PyObject *arg, *bytes, *retval = NULL;
-
- if (!PyArg_ParseTuple(args, "U:getpwnam", &arg))
- return NULL;
- if ((bytes = PyUnicode_AsEncodedString(arg,
- Py_FileSystemDefaultEncoding,
- "surrogateescape")) == NULL)
- return NULL;
- if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
- goto out;
- if ((p = getpwnam(name)) == NULL) {
- PyErr_Format(PyExc_KeyError,
- "getpwnam(): name not found: %s", name);
- goto out;
- }
- retval = mkpwent(p);
+ char *name;
+ struct passwd *p;
+ PyObject *arg, *bytes, *retval = NULL;
+
+ if (!PyArg_ParseTuple(args, "U:getpwnam", &arg))
+ return NULL;
+ if ((bytes = PyUnicode_AsEncodedString(arg,
+ Py_FileSystemDefaultEncoding,
+ "surrogateescape")) == NULL)
+ return NULL;
+ if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
+ goto out;
+ if ((p = getpwnam(name)) == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "getpwnam(): name not found: %s", name);
+ goto out;
+ }
+ retval = mkpwent(p);
out:
- Py_DECREF(bytes);
- return retval;
+ Py_DECREF(bytes);
+ return retval;
}
#ifdef HAVE_GETPWENT
@@ -159,67 +159,67 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwall(PyObject *self)
{
- PyObject *d;
- struct passwd *p;
- if ((d = PyList_New(0)) == NULL)
- return NULL;
+ PyObject *d;
+ struct passwd *p;
+ if ((d = PyList_New(0)) == NULL)
+ return NULL;
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- if ((p = getpwuid(0)) != NULL) {
+ if ((p = getpwuid(0)) != NULL) {
#else
- setpwent();
- while ((p = getpwent()) != NULL) {
+ setpwent();
+ while ((p = getpwent()) != NULL) {
#endif
- PyObject *v = mkpwent(p);
- if (v == NULL || PyList_Append(d, v) != 0) {
- Py_XDECREF(v);
- Py_DECREF(d);
- endpwent();
- return NULL;
- }
- Py_DECREF(v);
- }
- endpwent();
- return d;
+ PyObject *v = mkpwent(p);
+ if (v == NULL || PyList_Append(d, v) != 0) {
+ Py_XDECREF(v);
+ Py_DECREF(d);
+ endpwent();
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ endpwent();
+ return d;
}
#endif
static PyMethodDef pwd_methods[] = {
- {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__},
- {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__},
+ {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__},
+ {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__},
#ifdef HAVE_GETPWENT
- {"getpwall", (PyCFunction)pwd_getpwall,
- METH_NOARGS, pwd_getpwall__doc__},
+ {"getpwall", (PyCFunction)pwd_getpwall,
+ METH_NOARGS, pwd_getpwall__doc__},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef pwdmodule = {
- PyModuleDef_HEAD_INIT,
- "pwd",
- pwd__doc__,
- -1,
- pwd_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "pwd",
+ pwd__doc__,
+ -1,
+ pwd_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_pwd(void)
{
- PyObject *m;
- m = PyModule_Create(&pwdmodule);
- if (m == NULL)
- return NULL;
-
- if (!initialized) {
- PyStructSequence_InitType(&StructPwdType,
- &struct_pwd_type_desc);
- initialized = 1;
- }
- Py_INCREF((PyObject *) &StructPwdType);
- PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
- return m;
+ PyObject *m;
+ m = PyModule_Create(&pwdmodule);
+ if (m == NULL)
+ return NULL;
+
+ if (!initialized) {
+ PyStructSequence_InitType(&StructPwdType,
+ &struct_pwd_type_desc);
+ initialized = 1;
+ }
+ Py_INCREF((PyObject *) &StructPwdType);
+ PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
+ return m;
}
diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c
index 4b5652e..20af5ed 100644
--- a/Modules/pyexpat.c
+++ b/Modules/pyexpat.c
@@ -193,7 +193,7 @@ error_external_entity_ref_handler(XML_Parser parser,
used only from the character data handler trampoline, and must be
used right after `flag_error()` is called. */
static void
-noop_character_data_handler(void *userData, const XML_Char *data, int len)
+noop_character_data_handler(void *userData, const XML_Char *data, int len)
{
/* Do nothing. */
}
@@ -222,25 +222,25 @@ trace_frame(PyThreadState *tstate, PyFrameObject *f, int code, PyObject *val)
{
int result = 0;
if (!tstate->use_tracing || tstate->tracing)
- return 0;
+ return 0;
if (tstate->c_profilefunc != NULL) {
- tstate->tracing++;
- result = tstate->c_profilefunc(tstate->c_profileobj,
- f, code , val);
- tstate->use_tracing = ((tstate->c_tracefunc != NULL)
- || (tstate->c_profilefunc != NULL));
- tstate->tracing--;
- if (result)
- return result;
+ tstate->tracing++;
+ result = tstate->c_profilefunc(tstate->c_profileobj,
+ f, code , val);
+ tstate->use_tracing = ((tstate->c_tracefunc != NULL)
+ || (tstate->c_profilefunc != NULL));
+ tstate->tracing--;
+ if (result)
+ return result;
}
if (tstate->c_tracefunc != NULL) {
- tstate->tracing++;
- result = tstate->c_tracefunc(tstate->c_traceobj,
- f, code , val);
- tstate->use_tracing = ((tstate->c_tracefunc != NULL)
- || (tstate->c_profilefunc != NULL));
- tstate->tracing--;
- }
+ tstate->tracing++;
+ result = tstate->c_tracefunc(tstate->c_traceobj,
+ f, code , val);
+ tstate->use_tracing = ((tstate->c_tracefunc != NULL)
+ || (tstate->c_profilefunc != NULL));
+ tstate->tracing--;
+ }
return result;
}
@@ -251,12 +251,12 @@ trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
int err;
if (tstate->c_tracefunc == NULL)
- return 0;
+ return 0;
PyErr_Fetch(&type, &value, &traceback);
if (value == NULL) {
- value = Py_None;
- Py_INCREF(value);
+ value = Py_None;
+ Py_INCREF(value);
}
#if PY_VERSION_HEX < 0x02040000
arg = Py_BuildValue("(OOO)", type, value, traceback);
@@ -264,17 +264,17 @@ trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
arg = PyTuple_Pack(3, type, value, traceback);
#endif
if (arg == NULL) {
- PyErr_Restore(type, value, traceback);
- return 0;
+ PyErr_Restore(type, value, traceback);
+ return 0;
}
err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg);
Py_DECREF(arg);
if (err == 0)
- PyErr_Restore(type, value, traceback);
+ PyErr_Restore(type, value, traceback);
else {
- Py_XDECREF(type);
- Py_XDECREF(value);
- Py_XDECREF(traceback);
+ Py_XDECREF(type);
+ Py_XDECREF(value);
+ Py_XDECREF(traceback);
}
return err;
}
@@ -290,31 +290,31 @@ call_with_frame(PyCodeObject *c, PyObject* func, PyObject* args,
if (c == NULL)
return NULL;
-
+
f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL);
if (f == NULL)
return NULL;
tstate->frame = f;
#ifdef FIX_TRACE
if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) {
- return NULL;
+ return NULL;
}
#endif
res = PyEval_CallObject(func, args);
if (res == NULL) {
- if (tstate->curexc_traceback == NULL)
- PyTraceBack_Here(f);
+ if (tstate->curexc_traceback == NULL)
+ PyTraceBack_Here(f);
XML_StopParser(self->itself, XML_FALSE);
#ifdef FIX_TRACE
- if (trace_frame_exc(tstate, f) < 0) {
- return NULL;
- }
+ if (trace_frame_exc(tstate, f) < 0) {
+ return NULL;
+ }
}
else {
- if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
- Py_XDECREF(res);
- res = NULL;
- }
+ if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
+ Py_XDECREF(res);
+ res = NULL;
+ }
}
#else
}
@@ -331,12 +331,12 @@ string_intern(xmlparseobject *self, const char* str)
PyObject *value;
/* result can be NULL if the unicode conversion failed. */
if (!result)
- return result;
+ return result;
if (!self->intern)
- return result;
+ return result;
value = PyDict_GetItem(self->intern, result);
if (!value) {
- if (PyDict_SetItem(self->intern, result, result) == 0)
+ if (PyDict_SetItem(self->intern, result, result) == 0)
return result;
else
return NULL;
@@ -396,7 +396,7 @@ flush_character_buffer(xmlparseobject *self)
}
static void
-my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
+my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
{
xmlparseobject *self = (xmlparseobject *) userData;
if (self->buffer == NULL)
@@ -536,13 +536,13 @@ my_##NAME##Handler PARAMS {\
}
#define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
- RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
- (xmlparseobject *)userData)
+ RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
+ (xmlparseobject *)userData)
#define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
- RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
- rc = PyLong_AsLong(rv);, rc, \
- (xmlparseobject *)userData)
+ RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
+ rc = PyLong_AsLong(rv);, rc, \
+ (xmlparseobject *)userData)
VOID_HANDLER(EndElement,
(void *userData, const XML_Char *name),
@@ -687,25 +687,25 @@ VOID_HANDLER(SkippedEntity,
#endif
VOID_HANDLER(NotationDecl,
- (void *userData,
- const XML_Char *notationName,
- const XML_Char *base,
- const XML_Char *systemId,
- const XML_Char *publicId),
+ (void *userData,
+ const XML_Char *notationName,
+ const XML_Char *base,
+ const XML_Char *systemId,
+ const XML_Char *publicId),
("(NNNN)",
- string_intern(self, notationName), string_intern(self, base),
- string_intern(self, systemId), string_intern(self, publicId)))
+ string_intern(self, notationName), string_intern(self, base),
+ string_intern(self, systemId), string_intern(self, publicId)))
VOID_HANDLER(StartNamespaceDecl,
- (void *userData,
- const XML_Char *prefix,
- const XML_Char *uri),
+ (void *userData,
+ const XML_Char *prefix,
+ const XML_Char *uri),
("(NN)",
string_intern(self, prefix), string_intern(self, uri)))
VOID_HANDLER(EndNamespaceDecl,
- (void *userData,
- const XML_Char *prefix),
+ (void *userData,
+ const XML_Char *prefix),
("(N)", string_intern(self, prefix)))
VOID_HANDLER(Comment,
@@ -714,36 +714,36 @@ VOID_HANDLER(Comment,
VOID_HANDLER(StartCdataSection,
(void *userData),
- ("()"))
+ ("()"))
VOID_HANDLER(EndCdataSection,
(void *userData),
- ("()"))
+ ("()"))
VOID_HANDLER(Default,
- (void *userData, const XML_Char *s, int len),
- ("(N)", (conv_string_len_to_unicode(s,len))))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", (conv_string_len_to_unicode(s,len))))
VOID_HANDLER(DefaultHandlerExpand,
- (void *userData, const XML_Char *s, int len),
- ("(N)", (conv_string_len_to_unicode(s,len))))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", (conv_string_len_to_unicode(s,len))))
INT_HANDLER(NotStandalone,
- (void *userData),
- ("()"))
+ (void *userData),
+ ("()"))
RC_HANDLER(int, ExternalEntityRef,
- (XML_Parser parser,
- const XML_Char *context,
- const XML_Char *base,
- const XML_Char *systemId,
- const XML_Char *publicId),
- int rc=0;,
+ (XML_Parser parser,
+ const XML_Char *context,
+ const XML_Char *base,
+ const XML_Char *systemId,
+ const XML_Char *publicId),
+ int rc=0;,
("(O&NNN)",
- conv_string_to_unicode ,context, string_intern(self, base),
- string_intern(self, systemId), string_intern(self, publicId)),
- rc = PyLong_AsLong(rv);, rc,
- XML_GetUserData(parser))
+ conv_string_to_unicode ,context, string_intern(self, base),
+ string_intern(self, systemId), string_intern(self, publicId)),
+ rc = PyLong_AsLong(rv);, rc,
+ XML_GetUserData(parser))
/* XXX UnknownEncodingHandler */
@@ -915,7 +915,7 @@ xmlparse_SetBase(xmlparseobject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "s:SetBase", &base))
return NULL;
if (!XML_SetBase(self->itself, base)) {
- return PyErr_NoMemory();
+ return PyErr_NoMemory();
}
Py_INCREF(Py_None);
return Py_None;
@@ -1005,7 +1005,7 @@ xmlparse_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args)
new_parser->in_callback = 0;
new_parser->ns_prefixes = self->ns_prefixes;
new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
- encoding);
+ encoding);
new_parser->handlers = 0;
new_parser->intern = self->intern;
Py_XINCREF(new_parser->intern);
@@ -1096,26 +1096,26 @@ xmlparse_UseForeignDTD(xmlparseobject *self, PyObject *args)
static PyObject *xmlparse_dir(PyObject *self, PyObject* noargs);
static struct PyMethodDef xmlparse_methods[] = {
- {"Parse", (PyCFunction)xmlparse_Parse,
- METH_VARARGS, xmlparse_Parse__doc__},
+ {"Parse", (PyCFunction)xmlparse_Parse,
+ METH_VARARGS, xmlparse_Parse__doc__},
{"ParseFile", (PyCFunction)xmlparse_ParseFile,
- METH_O, xmlparse_ParseFile__doc__},
+ METH_O, xmlparse_ParseFile__doc__},
{"SetBase", (PyCFunction)xmlparse_SetBase,
- METH_VARARGS, xmlparse_SetBase__doc__},
+ METH_VARARGS, xmlparse_SetBase__doc__},
{"GetBase", (PyCFunction)xmlparse_GetBase,
- METH_NOARGS, xmlparse_GetBase__doc__},
+ METH_NOARGS, xmlparse_GetBase__doc__},
{"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate,
- METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
+ METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
{"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing,
- METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
+ METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
{"GetInputContext", (PyCFunction)xmlparse_GetInputContext,
- METH_NOARGS, xmlparse_GetInputContext__doc__},
+ METH_NOARGS, xmlparse_GetInputContext__doc__},
#if XML_COMBINED_VERSION >= 19505
{"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD,
- METH_VARARGS, xmlparse_UseForeignDTD__doc__},
+ METH_VARARGS, xmlparse_UseForeignDTD__doc__},
#endif
{"__dir__", xmlparse_dir, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -1133,7 +1133,7 @@ init_template_buffer(void)
{
int i;
for (i = 0; i < 256; i++) {
- template_buffer[i] = i;
+ template_buffer[i] = i;
}
template_buffer[256] = 0;
}
@@ -1152,15 +1152,15 @@ PyUnknownEncodingHandler(void *encodingHandlerData,
PyUnicode_Decode(template_buffer, 256, name, "replace");
if (_u_string == NULL)
- return result;
+ return result;
for (i = 0; i < 256; i++) {
- /* Stupid to access directly, but fast */
- Py_UNICODE c = _u_string->str[i];
- if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
- info->map[i] = -1;
- else
- info->map[i] = c;
+ /* Stupid to access directly, but fast */
+ Py_UNICODE c = _u_string->str[i];
+ if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
+ info->map[i] = -1;
+ else
+ info->map[i] = c;
}
info->data = NULL;
info->convert = NULL;
@@ -1295,8 +1295,8 @@ xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
int handlernum = -1;
if (PyUnicode_Check(nameobj))
- name = _PyUnicode_AsString(nameobj);
-
+ name = _PyUnicode_AsString(nameobj);
+
handlernum = handlername2int(name);
if (handlernum != -1) {
@@ -1362,18 +1362,18 @@ xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
static PyObject *
xmlparse_dir(PyObject *self, PyObject* noargs)
{
-#define APPEND(list, str) \
- do { \
- PyObject *o = PyUnicode_FromString(str); \
- if (o != NULL) \
- PyList_Append(list, o); \
- Py_XDECREF(o); \
+#define APPEND(list, str) \
+ do { \
+ PyObject *o = PyUnicode_FromString(str); \
+ if (o != NULL) \
+ PyList_Append(list, o); \
+ Py_XDECREF(o); \
} while (0)
int i;
PyObject *rc = PyList_New(0);
if (!rc)
- return NULL;
+ return NULL;
for (i = 0; handler_info[i].name != NULL; i++) {
PyObject *o = get_handler_name(&handler_info[i]);
if (o != NULL)
@@ -1494,42 +1494,42 @@ xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v)
if (strcmp(name, "buffer_size") == 0) {
long new_buffer_size;
if (!PyLong_Check(v)) {
- PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
+ return -1;
}
new_buffer_size=PyLong_AS_LONG(v);
/* trivial case -- no change */
if (new_buffer_size == self->buffer_size) {
- return 0;
+ return 0;
}
if (new_buffer_size <= 0) {
- PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
- return -1;
+ PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
+ return -1;
}
/* check maximum */
if (new_buffer_size > INT_MAX) {
- char errmsg[100];
- sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
- PyErr_SetString(PyExc_ValueError, errmsg);
- return -1;
+ char errmsg[100];
+ sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
+ PyErr_SetString(PyExc_ValueError, errmsg);
+ return -1;
}
if (self->buffer != NULL) {
- /* there is already a buffer */
- if (self->buffer_used != 0) {
- flush_character_buffer(self);
- }
- /* free existing buffer */
- free(self->buffer);
+ /* there is already a buffer */
+ if (self->buffer_used != 0) {
+ flush_character_buffer(self);
+ }
+ /* free existing buffer */
+ free(self->buffer);
}
self->buffer = malloc(new_buffer_size);
if (self->buffer == NULL) {
- PyErr_NoMemory();
- return -1;
- }
+ PyErr_NoMemory();
+ return -1;
+ }
self->buffer_size = new_buffer_size;
return 0;
}
@@ -1570,39 +1570,39 @@ xmlparse_clear(xmlparseobject *op)
PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
static PyTypeObject Xmlparsetype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "pyexpat.xmlparser", /*tp_name*/
- sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)xmlparse_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- 0, /*tp_getattr*/
- (setattrfunc)xmlparse_setattr, /*tp_setattr*/
- 0, /*tp_reserved*/
- (reprfunc)0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- (hashfunc)0, /*tp_hash*/
- (ternaryfunc)0, /*tp_call*/
- (reprfunc)0, /*tp_str*/
- (getattrofunc)xmlparse_getattro, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "pyexpat.xmlparser", /*tp_name*/
+ sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)xmlparse_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ 0, /*tp_getattr*/
+ (setattrfunc)xmlparse_setattr, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ (reprfunc)0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ (hashfunc)0, /*tp_hash*/
+ (ternaryfunc)0, /*tp_call*/
+ (reprfunc)0, /*tp_str*/
+ (getattrofunc)xmlparse_getattro, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
#ifdef Py_TPFLAGS_HAVE_GC
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
#else
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
#endif
- Xmlparsetype__doc__, /* tp_doc - Documentation string */
- (traverseproc)xmlparse_traverse, /* tp_traverse */
- (inquiry)xmlparse_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- xmlparse_methods, /* tp_methods */
+ Xmlparsetype__doc__, /* tp_doc - Documentation string */
+ (traverseproc)xmlparse_traverse, /* tp_traverse */
+ (inquiry)xmlparse_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ xmlparse_methods, /* tp_methods */
};
/* End of code for xmlparser objects */
@@ -1636,21 +1636,21 @@ pyexpat_ParserCreate(PyObject *notused, PyObject *args, PyObject *kw)
/* Explicitly passing None means no interning is desired.
Not passing anything means that a new dictionary is used. */
if (intern == Py_None)
- intern = NULL;
+ intern = NULL;
else if (intern == NULL) {
- intern = PyDict_New();
- if (!intern)
- return NULL;
- intern_decref = 1;
+ intern = PyDict_New();
+ if (!intern)
+ return NULL;
+ intern_decref = 1;
}
else if (!PyDict_Check(intern)) {
- PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
- return NULL;
+ PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
+ return NULL;
}
result = newxmlparseobject(encoding, namespace_separator, intern);
if (intern_decref) {
- Py_DECREF(intern);
+ Py_DECREF(intern);
}
return result;
}
@@ -1672,12 +1672,12 @@ pyexpat_ErrorString(PyObject *self, PyObject *args)
/* List of methods defined in the module */
static struct PyMethodDef pyexpat_methods[] = {
- {"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
+ {"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},
- {"ErrorString", (PyCFunction)pyexpat_ErrorString,
- METH_VARARGS, pyexpat_ErrorString__doc__},
+ {"ErrorString", (PyCFunction)pyexpat_ErrorString,
+ METH_VARARGS, pyexpat_ErrorString__doc__},
- {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
+ {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Module docstring */
@@ -1726,15 +1726,15 @@ get_version_string(void)
PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */
static struct PyModuleDef pyexpatmodule = {
- PyModuleDef_HEAD_INIT,
- MODULE_NAME,
- pyexpat_module_documentation,
- -1,
- pyexpat_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ MODULE_NAME,
+ pyexpat_module_documentation,
+ -1,
+ pyexpat_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -1756,12 +1756,12 @@ MODULE_INITFUNC(void)
return NULL;
if (PyType_Ready(&Xmlparsetype) < 0)
- return NULL;
+ return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&pyexpatmodule);
if (m == NULL)
- return NULL;
+ return NULL;
/* Add some symbolic constants to the module */
if (ErrorObject == NULL) {
@@ -1818,7 +1818,7 @@ MODULE_INITFUNC(void)
if (errors_module == NULL || model_module == NULL)
/* Don't core dump later! */
return NULL;
-
+
#if XML_COMBINED_VERSION > 19505
{
const XML_Feature *features = XML_GetFeatureList();
@@ -1943,7 +1943,7 @@ MODULE_INITFUNC(void)
capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
capi.SetUserData = XML_SetUserData;
-
+
/* export using capsule */
capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);
if (capi_object)
@@ -1959,12 +1959,12 @@ clear_handlers(xmlparseobject *self, int initial)
for (; handler_info[i].name != NULL; i++) {
if (initial)
- self->handlers[i] = NULL;
- else {
+ self->handlers[i] = NULL;
+ else {
temp = self->handlers[i];
self->handlers[i] = NULL;
Py_XDECREF(temp);
- handler_info[i].setter(self->itself, NULL);
+ handler_info[i].setter(self->itself, NULL);
}
}
}
diff --git a/Modules/python.c b/Modules/python.c
index 03c3e2f..22fbdb5 100644
--- a/Modules/python.c
+++ b/Modules/python.c
@@ -11,48 +11,48 @@
int
wmain(int argc, wchar_t **argv)
{
- return Py_Main(argc, argv);
+ return Py_Main(argc, argv);
}
#else
int
main(int argc, char **argv)
{
- wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
- /* We need a second copies, as Python might modify the first one. */
- wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
- int i, res;
- char *oldloc;
- /* 754 requires that FP exceptions run in "no stop" mode by default,
- * and until C vendors implement C99's ways to control FP exceptions,
- * Python requires non-stop mode. Alas, some platforms enable FP
- * exceptions by default. Here we disable them.
- */
+ wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
+ /* We need a second copies, as Python might modify the first one. */
+ wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
+ int i, res;
+ char *oldloc;
+ /* 754 requires that FP exceptions run in "no stop" mode by default,
+ * and until C vendors implement C99's ways to control FP exceptions,
+ * Python requires non-stop mode. Alas, some platforms enable FP
+ * exceptions by default. Here we disable them.
+ */
#ifdef __FreeBSD__
- fp_except_t m;
+ fp_except_t m;
- m = fpgetmask();
- fpsetmask(m & ~FP_X_OFL);
+ m = fpgetmask();
+ fpsetmask(m & ~FP_X_OFL);
#endif
- if (!argv_copy || !argv_copy2) {
- fprintf(stderr, "out of memory\n");
- return 1;
- }
- oldloc = strdup(setlocale(LC_ALL, NULL));
- setlocale(LC_ALL, "");
- for (i = 0; i < argc; i++) {
- argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]);
- if (!argv_copy[i])
- return 1;
- }
- setlocale(LC_ALL, oldloc);
- free(oldloc);
- res = Py_Main(argc, argv_copy);
- for (i = 0; i < argc; i++) {
- PyMem_Free(argv_copy2[i]);
- }
- PyMem_Free(argv_copy);
- PyMem_Free(argv_copy2);
- return res;
+ if (!argv_copy || !argv_copy2) {
+ fprintf(stderr, "out of memory\n");
+ return 1;
+ }
+ oldloc = strdup(setlocale(LC_ALL, NULL));
+ setlocale(LC_ALL, "");
+ for (i = 0; i < argc; i++) {
+ argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]);
+ if (!argv_copy[i])
+ return 1;
+ }
+ setlocale(LC_ALL, oldloc);
+ free(oldloc);
+ res = Py_Main(argc, argv_copy);
+ for (i = 0; i < argc; i++) {
+ PyMem_Free(argv_copy2[i]);
+ }
+ PyMem_Free(argv_copy);
+ PyMem_Free(argv_copy2);
+ return res;
}
#endif
diff --git a/Modules/readline.c b/Modules/readline.c
index a3dc4d9..7240d93 100644
--- a/Modules/readline.c
+++ b/Modules/readline.c
@@ -23,7 +23,7 @@
#ifdef SAVE_LOCALE
# define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
#else
-# define RESTORE_LOCALE(sl)
+# define RESTORE_LOCALE(sl)
#endif
/* GNU readline definitions */
@@ -33,7 +33,7 @@
#ifdef HAVE_RL_COMPLETION_MATCHES
#define completion_matches(x, y) \
- rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
+ rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
#else
#if defined(_RL_FUNCTION_TYPEDEF)
extern char **completion_matches(char *, rl_compentry_func_t *);
@@ -48,13 +48,13 @@ extern char **completion_matches(char *, CPFunction *);
#ifdef __APPLE__
/*
* It is possible to link the readline module to the readline
- * emulation library of editline/libedit.
- *
+ * emulation library of editline/libedit.
+ *
* On OSX this emulation library is not 100% API compatible
* with the "real" readline and cannot be detected at compile-time,
* hence we use a runtime check to detect if we're using libedit
*
- * Currently there is one know API incompatibility:
+ * Currently there is one know API incompatibility:
* - 'get_history' has a 1-based index with GNU readline, and a 0-based
* index with libedit's emulation.
* - Note that replace_history and remove_history use a 0-based index
@@ -66,7 +66,7 @@ static const char libedit_version_tag[] = "EditLine wrapper";
static void
on_completion_display_matches_hook(char **matches,
- int num_matches, int max_length);
+ int num_matches, int max_length);
/* Exported function to send one line to readline's init file parser */
@@ -74,18 +74,18 @@ on_completion_display_matches_hook(char **matches,
static PyObject *
parse_and_bind(PyObject *self, PyObject *args)
{
- char *s, *copy;
- if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
- return NULL;
- /* Make a copy -- rl_parse_and_bind() modifies its argument */
- /* Bernard Herzog */
- copy = malloc(1 + strlen(s));
- if (copy == NULL)
- return PyErr_NoMemory();
- strcpy(copy, s);
- rl_parse_and_bind(copy);
- free(copy); /* Free the copy */
- Py_RETURN_NONE;
+ char *s, *copy;
+ if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
+ return NULL;
+ /* Make a copy -- rl_parse_and_bind() modifies its argument */
+ /* Bernard Herzog */
+ copy = malloc(1 + strlen(s));
+ if (copy == NULL)
+ return PyErr_NoMemory();
+ strcpy(copy, s);
+ rl_parse_and_bind(copy);
+ free(copy); /* Free the copy */
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_parse_and_bind,
@@ -98,13 +98,13 @@ Parse and execute single line of a readline init file.");
static PyObject *
read_init_file(PyObject *self, PyObject *args)
{
- char *s = NULL;
- if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
- return NULL;
- errno = rl_read_init_file(s);
- if (errno)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_RETURN_NONE;
+ char *s = NULL;
+ if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
+ return NULL;
+ errno = rl_read_init_file(s);
+ if (errno)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_read_init_file,
@@ -118,13 +118,13 @@ The default filename is the last filename used.");
static PyObject *
read_history_file(PyObject *self, PyObject *args)
{
- char *s = NULL;
- if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
- return NULL;
- errno = read_history(s);
- if (errno)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_RETURN_NONE;
+ char *s = NULL;
+ if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
+ return NULL;
+ errno = read_history(s);
+ if (errno)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_RETURN_NONE;
}
static int _history_length = -1; /* do not truncate history by default */
@@ -139,15 +139,15 @@ The default filename is ~/.history.");
static PyObject *
write_history_file(PyObject *self, PyObject *args)
{
- char *s = NULL;
- if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
- return NULL;
- errno = write_history(s);
- if (!errno && _history_length >= 0)
- history_truncate_file(s, _history_length);
- if (errno)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_RETURN_NONE;
+ char *s = NULL;
+ if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
+ return NULL;
+ errno = write_history(s);
+ if (!errno && _history_length >= 0)
+ history_truncate_file(s, _history_length);
+ if (errno)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_write_history_file,
@@ -161,11 +161,11 @@ The default filename is ~/.history.");
static PyObject*
set_history_length(PyObject *self, PyObject *args)
{
- int length = _history_length;
- if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
- return NULL;
- _history_length = length;
- Py_RETURN_NONE;
+ int length = _history_length;
+ if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
+ return NULL;
+ _history_length = length;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(set_history_length_doc,
@@ -180,7 +180,7 @@ history truncation.");
static PyObject*
get_history_length(PyObject *self, PyObject *noarg)
{
- return PyLong_FromLong(_history_length);
+ return PyLong_FromLong(_history_length);
}
PyDoc_STRVAR(get_history_length_doc,
@@ -194,29 +194,29 @@ the history file.");
static PyObject *
set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
{
- PyObject *function = Py_None;
- char buf[80];
- PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
- if (!PyArg_ParseTuple(args, buf, &function))
- return NULL;
- if (function == Py_None) {
- Py_XDECREF(*hook_var);
- *hook_var = NULL;
- }
- else if (PyCallable_Check(function)) {
- PyObject *tmp = *hook_var;
- Py_INCREF(function);
- *hook_var = function;
- Py_XDECREF(tmp);
- }
- else {
- PyOS_snprintf(buf, sizeof(buf),
- "set_%.50s(func): argument not callable",
- funcname);
- PyErr_SetString(PyExc_TypeError, buf);
- return NULL;
- }
- Py_RETURN_NONE;
+ PyObject *function = Py_None;
+ char buf[80];
+ PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
+ if (!PyArg_ParseTuple(args, buf, &function))
+ return NULL;
+ if (function == Py_None) {
+ Py_XDECREF(*hook_var);
+ *hook_var = NULL;
+ }
+ else if (PyCallable_Check(function)) {
+ PyObject *tmp = *hook_var;
+ Py_INCREF(function);
+ *hook_var = function;
+ Py_XDECREF(tmp);
+ }
+ else {
+ PyOS_snprintf(buf, sizeof(buf),
+ "set_%.50s(func): argument not callable",
+ funcname);
+ PyErr_SetString(PyExc_TypeError, buf);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -232,20 +232,20 @@ static PyObject *pre_input_hook = NULL;
static PyObject *
set_completion_display_matches_hook(PyObject *self, PyObject *args)
{
- PyObject *result = set_hook("completion_display_matches_hook",
- &completion_display_matches_hook, args);
+ PyObject *result = set_hook("completion_display_matches_hook",
+ &completion_display_matches_hook, args);
#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
- /* We cannot set this hook globally, since it replaces the
- default completion display. */
- rl_completion_display_matches_hook =
- completion_display_matches_hook ?
+ /* We cannot set this hook globally, since it replaces the
+ default completion display. */
+ rl_completion_display_matches_hook =
+ completion_display_matches_hook ?
#if defined(_RL_FUNCTION_TYPEDEF)
- (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
+ (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
#else
- (VFunction *)on_completion_display_matches_hook : 0;
+ (VFunction *)on_completion_display_matches_hook : 0;
#endif
#endif
- return result;
+ return result;
}
@@ -259,7 +259,7 @@ once each time matches need to be displayed.");
static PyObject *
set_startup_hook(PyObject *self, PyObject *args)
{
- return set_hook("startup_hook", &startup_hook, args);
+ return set_hook("startup_hook", &startup_hook, args);
}
PyDoc_STRVAR(doc_set_startup_hook,
@@ -276,7 +276,7 @@ before readline prints the first prompt.");
static PyObject *
set_pre_input_hook(PyObject *self, PyObject *args)
{
- return set_hook("pre_input_hook", &pre_input_hook, args);
+ return set_hook("pre_input_hook", &pre_input_hook, args);
}
PyDoc_STRVAR(doc_set_pre_input_hook,
@@ -314,8 +314,8 @@ Get the type of completion being attempted.");
static PyObject *
get_begidx(PyObject *self, PyObject *noarg)
{
- Py_INCREF(begidx);
- return begidx;
+ Py_INCREF(begidx);
+ return begidx;
}
PyDoc_STRVAR(doc_get_begidx,
@@ -328,8 +328,8 @@ get the beginning index of the readline tab-completion scope");
static PyObject *
get_endidx(PyObject *self, PyObject *noarg)
{
- Py_INCREF(endidx);
- return endidx;
+ Py_INCREF(endidx);
+ return endidx;
}
PyDoc_STRVAR(doc_get_endidx,
@@ -342,14 +342,14 @@ get the ending index of the readline tab-completion scope");
static PyObject *
set_completer_delims(PyObject *self, PyObject *args)
{
- char *break_chars;
-
- if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
- return NULL;
- }
- free((void*)rl_completer_word_break_characters);
- rl_completer_word_break_characters = strdup(break_chars);
- Py_RETURN_NONE;
+ char *break_chars;
+
+ if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
+ return NULL;
+ }
+ free((void*)rl_completer_word_break_characters);
+ rl_completer_word_break_characters = strdup(break_chars);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_set_completer_delims,
@@ -359,31 +359,31 @@ set the readline word delimiters for tab-completion");
static PyObject *
py_remove_history(PyObject *self, PyObject *args)
{
- int entry_number;
- HIST_ENTRY *entry;
-
- if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
- return NULL;
- if (entry_number < 0) {
- PyErr_SetString(PyExc_ValueError,
- "History index cannot be negative");
- return NULL;
- }
- entry = remove_history(entry_number);
- if (!entry) {
- PyErr_Format(PyExc_ValueError,
- "No history item at position %d",
- entry_number);
- return NULL;
- }
- /* free memory allocated for the history entry */
- if (entry->line)
- free(entry->line);
- if (entry->data)
- free(entry->data);
- free(entry);
-
- Py_RETURN_NONE;
+ int entry_number;
+ HIST_ENTRY *entry;
+
+ if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
+ return NULL;
+ if (entry_number < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "History index cannot be negative");
+ return NULL;
+ }
+ entry = remove_history(entry_number);
+ if (!entry) {
+ PyErr_Format(PyExc_ValueError,
+ "No history item at position %d",
+ entry_number);
+ return NULL;
+ }
+ /* free memory allocated for the history entry */
+ if (entry->line)
+ free(entry->line);
+ if (entry->data)
+ free(entry->data);
+ free(entry);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_remove_history,
@@ -393,34 +393,34 @@ remove history item given by its position");
static PyObject *
py_replace_history(PyObject *self, PyObject *args)
{
- int entry_number;
- char *line;
- HIST_ENTRY *old_entry;
-
- if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
- &line)) {
- return NULL;
- }
- if (entry_number < 0) {
- PyErr_SetString(PyExc_ValueError,
- "History index cannot be negative");
- return NULL;
- }
- old_entry = replace_history_entry(entry_number, line, (void *)NULL);
- if (!old_entry) {
- PyErr_Format(PyExc_ValueError,
- "No history item at position %d",
- entry_number);
- return NULL;
- }
- /* free memory allocated for the old history entry */
- if (old_entry->line)
- free(old_entry->line);
- if (old_entry->data)
- free(old_entry->data);
- free(old_entry);
-
- Py_RETURN_NONE;
+ int entry_number;
+ char *line;
+ HIST_ENTRY *old_entry;
+
+ if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
+ &line)) {
+ return NULL;
+ }
+ if (entry_number < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "History index cannot be negative");
+ return NULL;
+ }
+ old_entry = replace_history_entry(entry_number, line, (void *)NULL);
+ if (!old_entry) {
+ PyErr_Format(PyExc_ValueError,
+ "No history item at position %d",
+ entry_number);
+ return NULL;
+ }
+ /* free memory allocated for the old history entry */
+ if (old_entry->line)
+ free(old_entry->line);
+ if (old_entry->data)
+ free(old_entry->data);
+ free(old_entry);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_replace_history,
@@ -432,13 +432,13 @@ replaces history item given by its position with contents of line");
static PyObject *
py_add_history(PyObject *self, PyObject *args)
{
- char *line;
+ char *line;
- if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
- return NULL;
- }
- add_history(line);
- Py_RETURN_NONE;
+ if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
+ return NULL;
+ }
+ add_history(line);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_add_history,
@@ -451,7 +451,7 @@ add a line to the history buffer");
static PyObject *
get_completer_delims(PyObject *self, PyObject *noarg)
{
- return PyUnicode_FromString(rl_completer_word_break_characters);
+ return PyUnicode_FromString(rl_completer_word_break_characters);
}
PyDoc_STRVAR(doc_get_completer_delims,
@@ -464,7 +464,7 @@ get the readline word delimiters for tab-completion");
static PyObject *
set_completer(PyObject *self, PyObject *args)
{
- return set_hook("completer", &completer, args);
+ return set_hook("completer", &completer, args);
}
PyDoc_STRVAR(doc_set_completer,
@@ -478,11 +478,11 @@ It should return the next possible completion starting with 'text'.");
static PyObject *
get_completer(PyObject *self, PyObject *noargs)
{
- if (completer == NULL) {
- Py_RETURN_NONE;
- }
- Py_INCREF(completer);
- return completer;
+ if (completer == NULL) {
+ Py_RETURN_NONE;
+ }
+ Py_INCREF(completer);
+ return completer;
}
PyDoc_STRVAR(doc_get_completer,
@@ -495,39 +495,39 @@ Returns current completer function.");
static PyObject *
get_history_item(PyObject *self, PyObject *args)
{
- int idx = 0;
- HIST_ENTRY *hist_ent;
+ int idx = 0;
+ HIST_ENTRY *hist_ent;
- if (!PyArg_ParseTuple(args, "i:index", &idx))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:index", &idx))
+ return NULL;
#ifdef __APPLE__
- if (using_libedit_emulation) {
- /* Libedit emulation uses 0-based indexes,
- * the real one uses 1-based indexes,
- * adjust the index to ensure that Python
- * code doesn't have to worry about the
- * difference.
- */
- HISTORY_STATE *hist_st;
- hist_st = history_get_history_state();
-
- idx --;
-
- /*
- * Apple's readline emulation crashes when
- * the index is out of range, therefore
- * test for that and fail gracefully.
- */
- if (idx < 0 || idx >= hist_st->length) {
- Py_RETURN_NONE;
- }
- }
+ if (using_libedit_emulation) {
+ /* Libedit emulation uses 0-based indexes,
+ * the real one uses 1-based indexes,
+ * adjust the index to ensure that Python
+ * code doesn't have to worry about the
+ * difference.
+ */
+ HISTORY_STATE *hist_st;
+ hist_st = history_get_history_state();
+
+ idx --;
+
+ /*
+ * Apple's readline emulation crashes when
+ * the index is out of range, therefore
+ * test for that and fail gracefully.
+ */
+ if (idx < 0 || idx >= hist_st->length) {
+ Py_RETURN_NONE;
+ }
+ }
#endif /* __APPLE__ */
- if ((hist_ent = history_get(idx)))
- return PyUnicode_FromString(hist_ent->line);
- else {
- Py_RETURN_NONE;
- }
+ if ((hist_ent = history_get(idx)))
+ return PyUnicode_FromString(hist_ent->line);
+ else {
+ Py_RETURN_NONE;
+ }
}
PyDoc_STRVAR(doc_get_history_item,
@@ -540,10 +540,10 @@ return the current contents of history item at index.");
static PyObject *
get_current_history_length(PyObject *self, PyObject *noarg)
{
- HISTORY_STATE *hist_st;
+ HISTORY_STATE *hist_st;
- hist_st = history_get_history_state();
- return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0);
+ hist_st = history_get_history_state();
+ return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0);
}
PyDoc_STRVAR(doc_get_current_history_length,
@@ -556,7 +556,7 @@ return the current (not the maximum) length of history.");
static PyObject *
get_line_buffer(PyObject *self, PyObject *noarg)
{
- return PyUnicode_FromString(rl_line_buffer);
+ return PyUnicode_FromString(rl_line_buffer);
}
PyDoc_STRVAR(doc_get_line_buffer,
@@ -571,8 +571,8 @@ return the current contents of the line buffer.");
static PyObject *
py_clear_history(PyObject *self, PyObject *noarg)
{
- clear_history();
- Py_RETURN_NONE;
+ clear_history();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_clear_history,
@@ -586,11 +586,11 @@ Clear the current readline history.");
static PyObject *
insert_text(PyObject *self, PyObject *args)
{
- char *s;
- if (!PyArg_ParseTuple(args, "s:insert_text", &s))
- return NULL;
- rl_insert_text(s);
- Py_RETURN_NONE;
+ char *s;
+ if (!PyArg_ParseTuple(args, "s:insert_text", &s))
+ return NULL;
+ rl_insert_text(s);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_insert_text,
@@ -603,8 +603,8 @@ Insert text into the command line.");
static PyObject *
redisplay(PyObject *self, PyObject *noarg)
{
- rl_redisplay();
- Py_RETURN_NONE;
+ rl_redisplay();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_redisplay,
@@ -617,50 +617,50 @@ contents of the line buffer.");
static struct PyMethodDef readline_methods[] =
{
- {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
- {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
- {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
- {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
- {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
- {"read_history_file", read_history_file,
- METH_VARARGS, doc_read_history_file},
- {"write_history_file", write_history_file,
- METH_VARARGS, doc_write_history_file},
- {"get_history_item", get_history_item,
- METH_VARARGS, doc_get_history_item},
- {"get_current_history_length", (PyCFunction)get_current_history_length,
- METH_NOARGS, doc_get_current_history_length},
- {"set_history_length", set_history_length,
- METH_VARARGS, set_history_length_doc},
- {"get_history_length", get_history_length,
- METH_NOARGS, get_history_length_doc},
- {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
- {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
- {"get_completion_type", get_completion_type,
- METH_NOARGS, doc_get_completion_type},
- {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
- {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
-
- {"set_completer_delims", set_completer_delims,
- METH_VARARGS, doc_set_completer_delims},
- {"add_history", py_add_history, METH_VARARGS, doc_add_history},
- {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
- {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
- {"get_completer_delims", get_completer_delims,
- METH_NOARGS, doc_get_completer_delims},
-
- {"set_completion_display_matches_hook", set_completion_display_matches_hook,
- METH_VARARGS, doc_set_completion_display_matches_hook},
- {"set_startup_hook", set_startup_hook,
- METH_VARARGS, doc_set_startup_hook},
+ {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
+ {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
+ {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
+ {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
+ {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
+ {"read_history_file", read_history_file,
+ METH_VARARGS, doc_read_history_file},
+ {"write_history_file", write_history_file,
+ METH_VARARGS, doc_write_history_file},
+ {"get_history_item", get_history_item,
+ METH_VARARGS, doc_get_history_item},
+ {"get_current_history_length", (PyCFunction)get_current_history_length,
+ METH_NOARGS, doc_get_current_history_length},
+ {"set_history_length", set_history_length,
+ METH_VARARGS, set_history_length_doc},
+ {"get_history_length", get_history_length,
+ METH_NOARGS, get_history_length_doc},
+ {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
+ {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
+ {"get_completion_type", get_completion_type,
+ METH_NOARGS, doc_get_completion_type},
+ {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
+ {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
+
+ {"set_completer_delims", set_completer_delims,
+ METH_VARARGS, doc_set_completer_delims},
+ {"add_history", py_add_history, METH_VARARGS, doc_add_history},
+ {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
+ {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
+ {"get_completer_delims", get_completer_delims,
+ METH_NOARGS, doc_get_completer_delims},
+
+ {"set_completion_display_matches_hook", set_completion_display_matches_hook,
+ METH_VARARGS, doc_set_completion_display_matches_hook},
+ {"set_startup_hook", set_startup_hook,
+ METH_VARARGS, doc_set_startup_hook},
#ifdef HAVE_RL_PRE_INPUT_HOOK
- {"set_pre_input_hook", set_pre_input_hook,
- METH_VARARGS, doc_set_pre_input_hook},
+ {"set_pre_input_hook", set_pre_input_hook,
+ METH_VARARGS, doc_set_pre_input_hook},
#endif
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
+ {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
#endif
- {0, 0}
+ {0, 0}
};
@@ -669,47 +669,47 @@ static struct PyMethodDef readline_methods[] =
static int
on_hook(PyObject *func)
{
- int result = 0;
- if (func != NULL) {
- PyObject *r;
+ int result = 0;
+ if (func != NULL) {
+ PyObject *r;
#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
- r = PyObject_CallFunction(func, NULL);
- if (r == NULL)
- goto error;
- if (r == Py_None)
- result = 0;
- else {
- result = PyLong_AsLong(r);
- if (result == -1 && PyErr_Occurred())
- goto error;
- }
- Py_DECREF(r);
- goto done;
- error:
- PyErr_Clear();
- Py_XDECREF(r);
- done:
+ r = PyObject_CallFunction(func, NULL);
+ if (r == NULL)
+ goto error;
+ if (r == Py_None)
+ result = 0;
+ else {
+ result = PyLong_AsLong(r);
+ if (result == -1 && PyErr_Occurred())
+ goto error;
+ }
+ Py_DECREF(r);
+ goto done;
+ error:
+ PyErr_Clear();
+ Py_XDECREF(r);
+ done:
#ifdef WITH_THREAD
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
- return result;
- }
- return result;
+ return result;
+ }
+ return result;
}
static int
on_startup_hook(void)
{
- return on_hook(startup_hook);
+ return on_hook(startup_hook);
}
#ifdef HAVE_RL_PRE_INPUT_HOOK
static int
on_pre_input_hook(void)
{
- return on_hook(pre_input_hook);
+ return on_hook(pre_input_hook);
}
#endif
@@ -718,42 +718,42 @@ on_pre_input_hook(void)
static void
on_completion_display_matches_hook(char **matches,
- int num_matches, int max_length)
+ int num_matches, int max_length)
{
- int i;
- PyObject *m=NULL, *s=NULL, *r=NULL;
+ int i;
+ PyObject *m=NULL, *s=NULL, *r=NULL;
#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
- m = PyList_New(num_matches);
- if (m == NULL)
- goto error;
- for (i = 0; i < num_matches; i++) {
- s = PyUnicode_FromString(matches[i+1]);
- if (s == NULL)
- goto error;
- if (PyList_SetItem(m, i, s) == -1)
- goto error;
- }
- r = PyObject_CallFunction(completion_display_matches_hook,
- "sOi", matches[0], m, max_length);
-
- Py_DECREF(m); m=NULL;
-
- if (r == NULL ||
- (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
- goto error;
- }
- Py_XDECREF(r); r=NULL;
-
- if (0) {
- error:
- PyErr_Clear();
- Py_XDECREF(m);
- Py_XDECREF(r);
- }
+ m = PyList_New(num_matches);
+ if (m == NULL)
+ goto error;
+ for (i = 0; i < num_matches; i++) {
+ s = PyUnicode_FromString(matches[i+1]);
+ if (s == NULL)
+ goto error;
+ if (PyList_SetItem(m, i, s) == -1)
+ goto error;
+ }
+ r = PyObject_CallFunction(completion_display_matches_hook,
+ "sOi", matches[0], m, max_length);
+
+ Py_DECREF(m); m=NULL;
+
+ if (r == NULL ||
+ (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
+ goto error;
+ }
+ Py_XDECREF(r); r=NULL;
+
+ if (0) {
+ error:
+ PyErr_Clear();
+ Py_XDECREF(m);
+ Py_XDECREF(r);
+ }
#ifdef WITH_THREAD
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
}
@@ -763,37 +763,37 @@ on_completion_display_matches_hook(char **matches,
static char *
on_completion(const char *text, int state)
{
- char *result = NULL;
- if (completer != NULL) {
- PyObject *r;
+ char *result = NULL;
+ if (completer != NULL) {
+ PyObject *r;
#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
- rl_attempted_completion_over = 1;
- r = PyObject_CallFunction(completer, "si", text, state);
- if (r == NULL)
- goto error;
- if (r == Py_None) {
- result = NULL;
- }
- else {
- char *s = _PyUnicode_AsString(r);
- if (s == NULL)
- goto error;
- result = strdup(s);
- }
- Py_DECREF(r);
- goto done;
- error:
- PyErr_Clear();
- Py_XDECREF(r);
- done:
+ rl_attempted_completion_over = 1;
+ r = PyObject_CallFunction(completer, "si", text, state);
+ if (r == NULL)
+ goto error;
+ if (r == Py_None) {
+ result = NULL;
+ }
+ else {
+ char *s = _PyUnicode_AsString(r);
+ if (s == NULL)
+ goto error;
+ result = strdup(s);
+ }
+ Py_DECREF(r);
+ goto done;
+ error:
+ PyErr_Clear();
+ Py_XDECREF(r);
+ done:
#ifdef WITH_THREAD
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
- return result;
- }
- return result;
+ return result;
+ }
+ return result;
}
@@ -804,16 +804,16 @@ static char **
flex_complete(char *text, int start, int end)
{
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- rl_completion_append_character ='\0';
+ rl_completion_append_character ='\0';
#endif
#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
- rl_completion_suppress_append = 0;
+ rl_completion_suppress_append = 0;
#endif
- Py_XDECREF(begidx);
- Py_XDECREF(endidx);
- begidx = PyLong_FromLong((long) start);
- endidx = PyLong_FromLong((long) end);
- return completion_matches(text, *on_completion);
+ Py_XDECREF(begidx);
+ Py_XDECREF(endidx);
+ begidx = PyLong_FromLong((long) start);
+ endidx = PyLong_FromLong((long) end);
+ return completion_matches(text, *on_completion);
}
@@ -823,45 +823,45 @@ static void
setup_readline(void)
{
#ifdef SAVE_LOCALE
- char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
- if (!saved_locale)
- Py_FatalError("not enough memory to save locale");
+ char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
+ if (!saved_locale)
+ Py_FatalError("not enough memory to save locale");
#endif
- using_history();
+ using_history();
- rl_readline_name = "python";
+ rl_readline_name = "python";
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- /* Allow $if term= in .inputrc to work */
- rl_terminal_name = getenv("TERM");
+ /* Allow $if term= in .inputrc to work */
+ rl_terminal_name = getenv("TERM");
#endif
- /* Force rebind of TAB to insert-tab */
- rl_bind_key('\t', rl_insert);
- /* Bind both ESC-TAB and ESC-ESC to the completion function */
- rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
- rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
- /* Set our hook functions */
- rl_startup_hook = (Function *)on_startup_hook;
+ /* Force rebind of TAB to insert-tab */
+ rl_bind_key('\t', rl_insert);
+ /* Bind both ESC-TAB and ESC-ESC to the completion function */
+ rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
+ rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
+ /* Set our hook functions */
+ rl_startup_hook = (Function *)on_startup_hook;
#ifdef HAVE_RL_PRE_INPUT_HOOK
- rl_pre_input_hook = (Function *)on_pre_input_hook;
+ rl_pre_input_hook = (Function *)on_pre_input_hook;
#endif
- /* Set our completion function */
- rl_attempted_completion_function = (CPPFunction *)flex_complete;
- /* Set Python word break characters */
- rl_completer_word_break_characters =
- strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
- /* All nonalphanums except '.' */
-
- begidx = PyLong_FromLong(0L);
- endidx = PyLong_FromLong(0L);
- /* Initialize (allows .inputrc to override)
- *
- * XXX: A bug in the readline-2.2 library causes a memory leak
- * inside this function. Nothing we can do about it.
- */
- rl_initialize();
-
- RESTORE_LOCALE(saved_locale)
+ /* Set our completion function */
+ rl_attempted_completion_function = (CPPFunction *)flex_complete;
+ /* Set Python word break characters */
+ rl_completer_word_break_characters =
+ strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
+ /* All nonalphanums except '.' */
+
+ begidx = PyLong_FromLong(0L);
+ endidx = PyLong_FromLong(0L);
+ /* Initialize (allows .inputrc to override)
+ *
+ * XXX: A bug in the readline-2.2 library causes a memory leak
+ * inside this function. Nothing we can do about it.
+ */
+ rl_initialize();
+
+ RESTORE_LOCALE(saved_locale)
}
/* Wrapper around GNU readline that handles signals differently. */
@@ -869,12 +869,12 @@ setup_readline(void)
#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
-static char *completed_input_string;
+static char *completed_input_string;
static void
rlhandler(char *text)
{
- completed_input_string = text;
- rl_callback_handler_remove();
+ completed_input_string = text;
+ rl_callback_handler_remove();
}
extern PyThreadState* _PyOS_ReadlineTState;
@@ -882,60 +882,60 @@ extern PyThreadState* _PyOS_ReadlineTState;
static char *
readline_until_enter_or_signal(char *prompt, int *signal)
{
- char * not_done_reading = "";
- fd_set selectset;
+ char * not_done_reading = "";
+ fd_set selectset;
- *signal = 0;
+ *signal = 0;
#ifdef HAVE_RL_CATCH_SIGNAL
- rl_catch_signals = 0;
+ rl_catch_signals = 0;
#endif
- rl_callback_handler_install (prompt, rlhandler);
- FD_ZERO(&selectset);
-
- completed_input_string = not_done_reading;
-
- while (completed_input_string == not_done_reading) {
- int has_input = 0;
-
- while (!has_input)
- { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
-
- /* [Bug #1552726] Only limit the pause if an input hook has been
- defined. */
- struct timeval *timeoutp = NULL;
- if (PyOS_InputHook)
- timeoutp = &timeout;
- FD_SET(fileno(rl_instream), &selectset);
- /* select resets selectset if no input was available */
- has_input = select(fileno(rl_instream) + 1, &selectset,
- NULL, NULL, timeoutp);
- if(PyOS_InputHook) PyOS_InputHook();
- }
-
- if(has_input > 0) {
- rl_callback_read_char();
- }
- else if (errno == EINTR) {
- int s;
+ rl_callback_handler_install (prompt, rlhandler);
+ FD_ZERO(&selectset);
+
+ completed_input_string = not_done_reading;
+
+ while (completed_input_string == not_done_reading) {
+ int has_input = 0;
+
+ while (!has_input)
+ { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
+
+ /* [Bug #1552726] Only limit the pause if an input hook has been
+ defined. */
+ struct timeval *timeoutp = NULL;
+ if (PyOS_InputHook)
+ timeoutp = &timeout;
+ FD_SET(fileno(rl_instream), &selectset);
+ /* select resets selectset if no input was available */
+ has_input = select(fileno(rl_instream) + 1, &selectset,
+ NULL, NULL, timeoutp);
+ if(PyOS_InputHook) PyOS_InputHook();
+ }
+
+ if(has_input > 0) {
+ rl_callback_read_char();
+ }
+ else if (errno == EINTR) {
+ int s;
#ifdef WITH_THREAD
- PyEval_RestoreThread(_PyOS_ReadlineTState);
+ PyEval_RestoreThread(_PyOS_ReadlineTState);
#endif
- s = PyErr_CheckSignals();
+ s = PyErr_CheckSignals();
#ifdef WITH_THREAD
- PyEval_SaveThread();
+ PyEval_SaveThread();
#endif
- if (s < 0) {
- rl_free_line_state();
- rl_cleanup_after_signal();
- rl_callback_handler_remove();
- *signal = 1;
- completed_input_string = NULL;
- }
- }
- }
-
- return completed_input_string;
+ if (s < 0) {
+ rl_free_line_state();
+ rl_cleanup_after_signal();
+ rl_callback_handler_remove();
+ *signal = 1;
+ completed_input_string = NULL;
+ }
+ }
+ }
+
+ return completed_input_string;
}
@@ -949,31 +949,31 @@ static jmp_buf jbuf;
static void
onintr(int sig)
{
- longjmp(jbuf, 1);
+ longjmp(jbuf, 1);
}
static char *
readline_until_enter_or_signal(char *prompt, int *signal)
{
- PyOS_sighandler_t old_inthandler;
- char *p;
-
- *signal = 0;
+ PyOS_sighandler_t old_inthandler;
+ char *p;
+
+ *signal = 0;
- old_inthandler = PyOS_setsig(SIGINT, onintr);
- if (setjmp(jbuf)) {
+ old_inthandler = PyOS_setsig(SIGINT, onintr);
+ if (setjmp(jbuf)) {
#ifdef HAVE_SIGRELSE
- /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
- sigrelse(SIGINT);
+ /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
+ sigrelse(SIGINT);
#endif
- PyOS_setsig(SIGINT, old_inthandler);
- *signal = 1;
- return NULL;
- }
- rl_event_hook = PyOS_InputHook;
- p = readline(prompt);
- PyOS_setsig(SIGINT, old_inthandler);
+ PyOS_setsig(SIGINT, old_inthandler);
+ *signal = 1;
+ return NULL;
+ }
+ rl_event_hook = PyOS_InputHook;
+ p = readline(prompt);
+ PyOS_setsig(SIGINT, old_inthandler);
return p;
}
@@ -983,82 +983,82 @@ readline_until_enter_or_signal(char *prompt, int *signal)
static char *
call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
- size_t n;
- char *p, *q;
- int signal;
+ size_t n;
+ char *p, *q;
+ int signal;
#ifdef SAVE_LOCALE
- char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
- if (!saved_locale)
- Py_FatalError("not enough memory to save locale");
- setlocale(LC_CTYPE, "");
+ char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
+ if (!saved_locale)
+ Py_FatalError("not enough memory to save locale");
+ setlocale(LC_CTYPE, "");
#endif
- if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
- rl_instream = sys_stdin;
- rl_outstream = sys_stdout;
+ if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
+ rl_instream = sys_stdin;
+ rl_outstream = sys_stdout;
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- rl_prep_terminal (1);
+ rl_prep_terminal (1);
#endif
- }
-
- p = readline_until_enter_or_signal(prompt, &signal);
-
- /* we got an interrupt signal */
- if (signal) {
- RESTORE_LOCALE(saved_locale)
- return NULL;
- }
-
- /* We got an EOF, return a empty string. */
- if (p == NULL) {
- p = PyMem_Malloc(1);
- if (p != NULL)
- *p = '\0';
- RESTORE_LOCALE(saved_locale)
- return p;
- }
-
- /* we have a valid line */
- n = strlen(p);
- if (n > 0) {
- char *line;
- HISTORY_STATE *state = history_get_history_state();
- if (state->length > 0)
+ }
+
+ p = readline_until_enter_or_signal(prompt, &signal);
+
+ /* we got an interrupt signal */
+ if (signal) {
+ RESTORE_LOCALE(saved_locale)
+ return NULL;
+ }
+
+ /* We got an EOF, return a empty string. */
+ if (p == NULL) {
+ p = PyMem_Malloc(1);
+ if (p != NULL)
+ *p = '\0';
+ RESTORE_LOCALE(saved_locale)
+ return p;
+ }
+
+ /* we have a valid line */
+ n = strlen(p);
+ if (n > 0) {
+ char *line;
+ HISTORY_STATE *state = history_get_history_state();
+ if (state->length > 0)
#ifdef __APPLE__
- if (using_libedit_emulation) {
- /*
- * Libedit's emulation uses 0-based indexes,
- * the real readline uses 1-based indexes.
- */
- line = history_get(state->length - 1)->line;
- } else
+ if (using_libedit_emulation) {
+ /*
+ * Libedit's emulation uses 0-based indexes,
+ * the real readline uses 1-based indexes.
+ */
+ line = history_get(state->length - 1)->line;
+ } else
#endif /* __APPLE__ */
- line = history_get(state->length)->line;
- else
- line = "";
- if (strcmp(p, line))
- add_history(p);
- /* the history docs don't say so, but the address of state
- changes each time history_get_history_state is called
- which makes me think it's freshly malloc'd memory...
- on the other hand, the address of the last line stays the
- same as long as history isn't extended, so it appears to
- be malloc'd but managed by the history package... */
- free(state);
- }
- /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
- release the original. */
- q = p;
- p = PyMem_Malloc(n+2);
- if (p != NULL) {
- strncpy(p, q, n);
- p[n] = '\n';
- p[n+1] = '\0';
- }
- free(q);
- RESTORE_LOCALE(saved_locale)
- return p;
+ line = history_get(state->length)->line;
+ else
+ line = "";
+ if (strcmp(p, line))
+ add_history(p);
+ /* the history docs don't say so, but the address of state
+ changes each time history_get_history_state is called
+ which makes me think it's freshly malloc'd memory...
+ on the other hand, the address of the last line stays the
+ same as long as history isn't extended, so it appears to
+ be malloc'd but managed by the history package... */
+ free(state);
+ }
+ /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
+ release the original. */
+ q = p;
+ p = PyMem_Malloc(n+2);
+ if (p != NULL) {
+ strncpy(p, q, n);
+ p[n] = '\n';
+ p[n+1] = '\0';
+ }
+ free(q);
+ RESTORE_LOCALE(saved_locale)
+ return p;
}
@@ -1073,41 +1073,41 @@ PyDoc_STRVAR(doc_module_le,
#endif /* __APPLE__ */
static struct PyModuleDef readlinemodule = {
- PyModuleDef_HEAD_INIT,
- "readline",
- doc_module,
- -1,
- readline_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "readline",
+ doc_module,
+ -1,
+ readline_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_readline(void)
{
- PyObject *m;
+ PyObject *m;
#ifdef __APPLE__
- if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
- using_libedit_emulation = 1;
- }
+ if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
+ using_libedit_emulation = 1;
+ }
- if (using_libedit_emulation)
- readlinemodule.m_doc = doc_module_le;
+ if (using_libedit_emulation)
+ readlinemodule.m_doc = doc_module_le;
#endif /* __APPLE__ */
- m = PyModule_Create(&readlinemodule);
+ m = PyModule_Create(&readlinemodule);
- if (m == NULL)
- return NULL;
+ if (m == NULL)
+ return NULL;
- PyOS_ReadlineFunctionPointer = call_readline;
- setup_readline();
- return m;
+ PyOS_ReadlineFunctionPointer = call_readline;
+ setup_readline();
+ return m;
}
diff --git a/Modules/resource.c b/Modules/resource.c
index 22e177f..6d8bd57 100644
--- a/Modules/resource.c
+++ b/Modules/resource.c
@@ -29,30 +29,30 @@ PyDoc_STRVAR(struct_rusage__doc__,
"or via the attributes ru_utime, ru_stime, ru_maxrss, and so on.");
static PyStructSequence_Field struct_rusage_fields[] = {
- {"ru_utime", "user time used"},
- {"ru_stime", "system time used"},
- {"ru_maxrss", "max. resident set size"},
- {"ru_ixrss", "shared memory size"},
- {"ru_idrss", "unshared data size"},
- {"ru_isrss", "unshared stack size"},
- {"ru_minflt", "page faults not requiring I/O"},
- {"ru_majflt", "page faults requiring I/O"},
- {"ru_nswap", "number of swap outs"},
- {"ru_inblock", "block input operations"},
- {"ru_oublock", "block output operations"},
- {"ru_msgsnd", "IPC messages sent"},
- {"ru_msgrcv", "IPC messages received"},
- {"ru_nsignals", "signals received"},
- {"ru_nvcsw", "voluntary context switches"},
- {"ru_nivcsw", "involuntary context switches"},
- {0}
+ {"ru_utime", "user time used"},
+ {"ru_stime", "system time used"},
+ {"ru_maxrss", "max. resident set size"},
+ {"ru_ixrss", "shared memory size"},
+ {"ru_idrss", "unshared data size"},
+ {"ru_isrss", "unshared stack size"},
+ {"ru_minflt", "page faults not requiring I/O"},
+ {"ru_majflt", "page faults requiring I/O"},
+ {"ru_nswap", "number of swap outs"},
+ {"ru_inblock", "block input operations"},
+ {"ru_oublock", "block output operations"},
+ {"ru_msgsnd", "IPC messages sent"},
+ {"ru_msgrcv", "IPC messages received"},
+ {"ru_nsignals", "signals received"},
+ {"ru_nvcsw", "voluntary context switches"},
+ {"ru_nivcsw", "involuntary context switches"},
+ {0}
};
static PyStructSequence_Desc struct_rusage_desc = {
- "resource.struct_rusage", /* name */
- struct_rusage__doc__, /* doc */
- struct_rusage_fields, /* fields */
- 16 /* n_in_sequence */
+ "resource.struct_rusage", /* name */
+ struct_rusage__doc__, /* doc */
+ struct_rusage_fields, /* fields */
+ 16 /* n_in_sequence */
};
static int initialized;
@@ -61,151 +61,151 @@ static PyTypeObject StructRUsageType;
static PyObject *
resource_getrusage(PyObject *self, PyObject *args)
{
- int who;
- struct rusage ru;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "i:getrusage", &who))
- return NULL;
-
- if (getrusage(who, &ru) == -1) {
- if (errno == EINVAL) {
- PyErr_SetString(PyExc_ValueError,
- "invalid who parameter");
- return NULL;
- }
- PyErr_SetFromErrno(ResourceError);
- return NULL;
- }
-
- result = PyStructSequence_New(&StructRUsageType);
- if (!result)
- return NULL;
-
- PyStructSequence_SET_ITEM(result, 0,
- PyFloat_FromDouble(doubletime(ru.ru_utime)));
- PyStructSequence_SET_ITEM(result, 1,
- PyFloat_FromDouble(doubletime(ru.ru_stime)));
- PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss));
- PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss));
- PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss));
- PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss));
- PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt));
- PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt));
- PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap));
- PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock));
- PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock));
- PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd));
- PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv));
- PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals));
- PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw));
- PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw));
-
- if (PyErr_Occurred()) {
- Py_DECREF(result);
- return NULL;
- }
-
- return result;
+ int who;
+ struct rusage ru;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "i:getrusage", &who))
+ return NULL;
+
+ if (getrusage(who, &ru) == -1) {
+ if (errno == EINVAL) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid who parameter");
+ return NULL;
+ }
+ PyErr_SetFromErrno(ResourceError);
+ return NULL;
+ }
+
+ result = PyStructSequence_New(&StructRUsageType);
+ if (!result)
+ return NULL;
+
+ PyStructSequence_SET_ITEM(result, 0,
+ PyFloat_FromDouble(doubletime(ru.ru_utime)));
+ PyStructSequence_SET_ITEM(result, 1,
+ PyFloat_FromDouble(doubletime(ru.ru_stime)));
+ PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss));
+ PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss));
+ PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss));
+ PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss));
+ PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt));
+ PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt));
+ PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap));
+ PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock));
+ PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock));
+ PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd));
+ PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv));
+ PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals));
+ PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw));
+ PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw));
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return result;
}
static PyObject *
resource_getrlimit(PyObject *self, PyObject *args)
{
- struct rlimit rl;
- int resource;
+ struct rlimit rl;
+ int resource;
- if (!PyArg_ParseTuple(args, "i:getrlimit", &resource))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:getrlimit", &resource))
+ return NULL;
- if (resource < 0 || resource >= RLIM_NLIMITS) {
- PyErr_SetString(PyExc_ValueError,
- "invalid resource specified");
- return NULL;
- }
+ if (resource < 0 || resource >= RLIM_NLIMITS) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid resource specified");
+ return NULL;
+ }
- if (getrlimit(resource, &rl) == -1) {
- PyErr_SetFromErrno(ResourceError);
- return NULL;
- }
+ if (getrlimit(resource, &rl) == -1) {
+ PyErr_SetFromErrno(ResourceError);
+ return NULL;
+ }
#if defined(HAVE_LONG_LONG)
- if (sizeof(rl.rlim_cur) > sizeof(long)) {
- return Py_BuildValue("LL",
- (PY_LONG_LONG) rl.rlim_cur,
- (PY_LONG_LONG) rl.rlim_max);
- }
+ if (sizeof(rl.rlim_cur) > sizeof(long)) {
+ return Py_BuildValue("LL",
+ (PY_LONG_LONG) rl.rlim_cur,
+ (PY_LONG_LONG) rl.rlim_max);
+ }
#endif
- return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
+ return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
}
static PyObject *
resource_setrlimit(PyObject *self, PyObject *args)
{
- struct rlimit rl;
- int resource;
- PyObject *curobj, *maxobj;
+ struct rlimit rl;
+ int resource;
+ PyObject *curobj, *maxobj;
- if (!PyArg_ParseTuple(args, "i(OO):setrlimit",
- &resource, &curobj, &maxobj))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i(OO):setrlimit",
+ &resource, &curobj, &maxobj))
+ return NULL;
- if (resource < 0 || resource >= RLIM_NLIMITS) {
- PyErr_SetString(PyExc_ValueError,
- "invalid resource specified");
- return NULL;
- }
+ if (resource < 0 || resource >= RLIM_NLIMITS) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid resource specified");
+ return NULL;
+ }
#if !defined(HAVE_LARGEFILE_SUPPORT)
- rl.rlim_cur = PyLong_AsLong(curobj);
- if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
- rl.rlim_max = PyLong_AsLong(maxobj);
- if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
+ rl.rlim_cur = PyLong_AsLong(curobj);
+ if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
+ rl.rlim_max = PyLong_AsLong(maxobj);
+ if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
#else
- /* The limits are probably bigger than a long */
- rl.rlim_cur = PyLong_AsLongLong(curobj);
- if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
- rl.rlim_max = PyLong_AsLongLong(maxobj);
- if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
+ /* The limits are probably bigger than a long */
+ rl.rlim_cur = PyLong_AsLongLong(curobj);
+ if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
+ rl.rlim_max = PyLong_AsLongLong(maxobj);
+ if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
#endif
- rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY;
- rl.rlim_max = rl.rlim_max & RLIM_INFINITY;
- if (setrlimit(resource, &rl) == -1) {
- if (errno == EINVAL)
- PyErr_SetString(PyExc_ValueError,
- "current limit exceeds maximum limit");
- else if (errno == EPERM)
- PyErr_SetString(PyExc_ValueError,
- "not allowed to raise maximum limit");
- else
- PyErr_SetFromErrno(ResourceError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY;
+ rl.rlim_max = rl.rlim_max & RLIM_INFINITY;
+ if (setrlimit(resource, &rl) == -1) {
+ if (errno == EINVAL)
+ PyErr_SetString(PyExc_ValueError,
+ "current limit exceeds maximum limit");
+ else if (errno == EPERM)
+ PyErr_SetString(PyExc_ValueError,
+ "not allowed to raise maximum limit");
+ else
+ PyErr_SetFromErrno(ResourceError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
resource_getpagesize(PyObject *self, PyObject *unused)
{
- long pagesize = 0;
+ long pagesize = 0;
#if defined(HAVE_GETPAGESIZE)
- pagesize = getpagesize();
+ pagesize = getpagesize();
#elif defined(HAVE_SYSCONF)
#if defined(_SC_PAGE_SIZE)
- pagesize = sysconf(_SC_PAGE_SIZE);
+ pagesize = sysconf(_SC_PAGE_SIZE);
#else
- /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
- pagesize = sysconf(_SC_PAGESIZE);
+ /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
+ pagesize = sysconf(_SC_PAGESIZE);
#endif
#endif
- return Py_BuildValue("i", pagesize);
+ return Py_BuildValue("i", pagesize);
}
@@ -213,11 +213,11 @@ resource_getpagesize(PyObject *self, PyObject *unused)
static struct PyMethodDef
resource_methods[] = {
- {"getrusage", resource_getrusage, METH_VARARGS},
- {"getrlimit", resource_getrlimit, METH_VARARGS},
- {"setrlimit", resource_setrlimit, METH_VARARGS},
- {"getpagesize", resource_getpagesize, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"getrusage", resource_getrusage, METH_VARARGS},
+ {"getrlimit", resource_getrlimit, METH_VARARGS},
+ {"setrlimit", resource_setrlimit, METH_VARARGS},
+ {"getpagesize", resource_getpagesize, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -225,117 +225,117 @@ resource_methods[] = {
static struct PyModuleDef resourcemodule = {
- PyModuleDef_HEAD_INIT,
- "resource",
- NULL,
- -1,
- resource_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "resource",
+ NULL,
+ -1,
+ resource_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_resource(void)
{
- PyObject *m, *v;
-
- /* Create the module and add the functions */
- m = PyModule_Create(&resourcemodule);
- if (m == NULL)
- return NULL;
-
- /* Add some symbolic constants to the module */
- if (ResourceError == NULL) {
- ResourceError = PyErr_NewException("resource.error",
- NULL, NULL);
- }
- Py_INCREF(ResourceError);
- PyModule_AddObject(m, "error", ResourceError);
- if (!initialized)
- PyStructSequence_InitType(&StructRUsageType,
- &struct_rusage_desc);
- Py_INCREF(&StructRUsageType);
- PyModule_AddObject(m, "struct_rusage",
- (PyObject*) &StructRUsageType);
-
- /* insert constants */
+ PyObject *m, *v;
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&resourcemodule);
+ if (m == NULL)
+ return NULL;
+
+ /* Add some symbolic constants to the module */
+ if (ResourceError == NULL) {
+ ResourceError = PyErr_NewException("resource.error",
+ NULL, NULL);
+ }
+ Py_INCREF(ResourceError);
+ PyModule_AddObject(m, "error", ResourceError);
+ if (!initialized)
+ PyStructSequence_InitType(&StructRUsageType,
+ &struct_rusage_desc);
+ Py_INCREF(&StructRUsageType);
+ PyModule_AddObject(m, "struct_rusage",
+ (PyObject*) &StructRUsageType);
+
+ /* insert constants */
#ifdef RLIMIT_CPU
- PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU);
+ PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU);
#endif
#ifdef RLIMIT_FSIZE
- PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE);
+ PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE);
#endif
#ifdef RLIMIT_DATA
- PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA);
+ PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA);
#endif
#ifdef RLIMIT_STACK
- PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK);
+ PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK);
#endif
#ifdef RLIMIT_CORE
- PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE);
+ PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE);
#endif
#ifdef RLIMIT_NOFILE
- PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE);
+ PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE);
#endif
#ifdef RLIMIT_OFILE
- PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE);
+ PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE);
#endif
#ifdef RLIMIT_VMEM
- PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM);
+ PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM);
#endif
#ifdef RLIMIT_AS
- PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS);
+ PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS);
#endif
#ifdef RLIMIT_RSS
- PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS);
+ PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS);
#endif
#ifdef RLIMIT_NPROC
- PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC);
+ PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC);
#endif
#ifdef RLIMIT_MEMLOCK
- PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK);
+ PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK);
#endif
#ifdef RLIMIT_SBSIZE
- PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE);
+ PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE);
#endif
#ifdef RUSAGE_SELF
- PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF);
+ PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF);
#endif
#ifdef RUSAGE_CHILDREN
- PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN);
+ PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN);
#endif
#ifdef RUSAGE_BOTH
- PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
+ PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
#endif
#if defined(HAVE_LONG_LONG)
- if (sizeof(RLIM_INFINITY) > sizeof(long)) {
- v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
- } else
+ if (sizeof(RLIM_INFINITY) > sizeof(long)) {
+ v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
+ } else
#endif
- {
- v = PyLong_FromLong((long) RLIM_INFINITY);
- }
- if (v) {
- PyModule_AddObject(m, "RLIM_INFINITY", v);
- }
- initialized = 1;
- return m;
+ {
+ v = PyLong_FromLong((long) RLIM_INFINITY);
+ }
+ if (v) {
+ PyModule_AddObject(m, "RLIM_INFINITY", v);
+ }
+ initialized = 1;
+ return m;
}
diff --git a/Modules/rotatingtree.c b/Modules/rotatingtree.c
index 39c6dd5..07e08bc 100644
--- a/Modules/rotatingtree.c
+++ b/Modules/rotatingtree.c
@@ -14,14 +14,14 @@ static unsigned int random_stream = 0;
static int
randombits(int bits)
{
- int result;
- if (random_stream < (1U << bits)) {
- random_value *= 1082527;
- random_stream = random_value;
- }
- result = random_stream & ((1<<bits)-1);
- random_stream >>= bits;
- return result;
+ int result;
+ if (random_stream < (1U << bits)) {
+ random_value *= 1082527;
+ random_stream = random_value;
+ }
+ result = random_stream & ((1<<bits)-1);
+ random_stream >>= bits;
+ return result;
}
@@ -30,15 +30,15 @@ randombits(int bits)
void
RotatingTree_Add(rotating_node_t **root, rotating_node_t *node)
{
- while (*root != NULL) {
- if (KEY_LOWER_THAN(node->key, (*root)->key))
- root = &((*root)->left);
- else
- root = &((*root)->right);
- }
- node->left = NULL;
- node->right = NULL;
- *root = node;
+ while (*root != NULL) {
+ if (KEY_LOWER_THAN(node->key, (*root)->key))
+ root = &((*root)->left);
+ else
+ root = &((*root)->right);
+ }
+ node->left = NULL;
+ node->right = NULL;
+ *root = node;
}
/* Locate the node with the given key. This is the most complicated
@@ -47,57 +47,57 @@ RotatingTree_Add(rotating_node_t **root, rotating_node_t *node)
rotating_node_t *
RotatingTree_Get(rotating_node_t **root, void *key)
{
- if (randombits(3) != 4) {
- /* Fast path, no rebalancing */
- rotating_node_t *node = *root;
- while (node != NULL) {
- if (node->key == key)
- return node;
- if (KEY_LOWER_THAN(key, node->key))
- node = node->left;
- else
- node = node->right;
- }
- return NULL;
- }
- else {
- rotating_node_t **pnode = root;
- rotating_node_t *node = *pnode;
- rotating_node_t *next;
- int rotate;
- if (node == NULL)
- return NULL;
- while (1) {
- if (node->key == key)
- return node;
- rotate = !randombits(1);
- if (KEY_LOWER_THAN(key, node->key)) {
- next = node->left;
- if (next == NULL)
- return NULL;
- if (rotate) {
- node->left = next->right;
- next->right = node;
- *pnode = next;
- }
- else
- pnode = &(node->left);
- }
- else {
- next = node->right;
- if (next == NULL)
- return NULL;
- if (rotate) {
- node->right = next->left;
- next->left = node;
- *pnode = next;
- }
- else
- pnode = &(node->right);
- }
- node = next;
- }
- }
+ if (randombits(3) != 4) {
+ /* Fast path, no rebalancing */
+ rotating_node_t *node = *root;
+ while (node != NULL) {
+ if (node->key == key)
+ return node;
+ if (KEY_LOWER_THAN(key, node->key))
+ node = node->left;
+ else
+ node = node->right;
+ }
+ return NULL;
+ }
+ else {
+ rotating_node_t **pnode = root;
+ rotating_node_t *node = *pnode;
+ rotating_node_t *next;
+ int rotate;
+ if (node == NULL)
+ return NULL;
+ while (1) {
+ if (node->key == key)
+ return node;
+ rotate = !randombits(1);
+ if (KEY_LOWER_THAN(key, node->key)) {
+ next = node->left;
+ if (next == NULL)
+ return NULL;
+ if (rotate) {
+ node->left = next->right;
+ next->right = node;
+ *pnode = next;
+ }
+ else
+ pnode = &(node->left);
+ }
+ else {
+ next = node->right;
+ if (next == NULL)
+ return NULL;
+ if (rotate) {
+ node->right = next->left;
+ next->left = node;
+ *pnode = next;
+ }
+ else
+ pnode = &(node->right);
+ }
+ node = next;
+ }
+ }
}
/* Enumerate all nodes in the tree. The callback enumfn() should return
@@ -105,17 +105,17 @@ RotatingTree_Get(rotating_node_t **root, void *key)
A non-zero value is directly returned by RotatingTree_Enum(). */
int
RotatingTree_Enum(rotating_node_t *root, rotating_tree_enum_fn enumfn,
- void *arg)
+ void *arg)
{
- int result;
- rotating_node_t *node;
- while (root != NULL) {
- result = RotatingTree_Enum(root->left, enumfn, arg);
- if (result != 0) return result;
- node = root->right;
- result = enumfn(root, arg);
- if (result != 0) return result;
- root = node;
- }
- return 0;
+ int result;
+ rotating_node_t *node;
+ while (root != NULL) {
+ result = RotatingTree_Enum(root->left, enumfn, arg);
+ if (result != 0) return result;
+ node = root->right;
+ result = enumfn(root, arg);
+ if (result != 0) return result;
+ root = node;
+ }
+ return 0;
}
diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c
index 1c021ba..f334153 100644
--- a/Modules/selectmodule.c
+++ b/Modules/selectmodule.c
@@ -22,7 +22,7 @@
*/
#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
#define FD_SETSIZE 512
-#endif
+#endif
#if defined(HAVE_POLL_H)
#include <poll.h>
@@ -58,20 +58,20 @@ static PyObject *SelectError;
/* list of Python objects and their file descriptor */
typedef struct {
- PyObject *obj; /* owned reference */
- SOCKET fd;
- int sentinel; /* -1 == sentinel */
+ PyObject *obj; /* owned reference */
+ SOCKET fd;
+ int sentinel; /* -1 == sentinel */
} pylist;
static void
reap_obj(pylist fd2obj[FD_SETSIZE + 1])
{
- int i;
- for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
- Py_XDECREF(fd2obj[i].obj);
- fd2obj[i].obj = NULL;
- }
- fd2obj[0].sentinel = -1;
+ int i;
+ for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
+ Py_XDECREF(fd2obj[i].obj);
+ fd2obj[i].obj = NULL;
+ }
+ fd2obj[0].sentinel = -1;
}
@@ -81,106 +81,106 @@ reap_obj(pylist fd2obj[FD_SETSIZE + 1])
static int
seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
- int i;
- int max = -1;
- int index = 0;
- int len = -1;
- PyObject* fast_seq = NULL;
- PyObject* o = NULL;
-
- fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
- FD_ZERO(set);
-
- fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences");
- if (!fast_seq)
- return -1;
+ int i;
+ int max = -1;
+ int index = 0;
+ int len = -1;
+ PyObject* fast_seq = NULL;
+ PyObject* o = NULL;
+
+ fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
+ FD_ZERO(set);
+
+ fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences");
+ if (!fast_seq)
+ return -1;
- len = PySequence_Fast_GET_SIZE(fast_seq);
+ len = PySequence_Fast_GET_SIZE(fast_seq);
- for (i = 0; i < len; i++) {
- SOCKET v;
+ for (i = 0; i < len; i++) {
+ SOCKET v;
- /* any intervening fileno() calls could decr this refcnt */
- if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
- return -1;
+ /* any intervening fileno() calls could decr this refcnt */
+ if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
+ return -1;
- Py_INCREF(o);
- v = PyObject_AsFileDescriptor( o );
- if (v == -1) goto finally;
+ Py_INCREF(o);
+ v = PyObject_AsFileDescriptor( o );
+ if (v == -1) goto finally;
#if defined(_MSC_VER)
- max = 0; /* not used for Win32 */
+ max = 0; /* not used for Win32 */
#else /* !_MSC_VER */
- if (v < 0 || v >= FD_SETSIZE) {
- PyErr_SetString(PyExc_ValueError,
- "filedescriptor out of range in select()");
- goto finally;
- }
- if (v > max)
- max = v;
+ if (v < 0 || v >= FD_SETSIZE) {
+ PyErr_SetString(PyExc_ValueError,
+ "filedescriptor out of range in select()");
+ goto finally;
+ }
+ if (v > max)
+ max = v;
#endif /* _MSC_VER */
- FD_SET(v, set);
-
- /* add object and its file descriptor to the list */
- if (index >= FD_SETSIZE) {
- PyErr_SetString(PyExc_ValueError,
- "too many file descriptors in select()");
- goto finally;
- }
- fd2obj[index].obj = o;
- fd2obj[index].fd = v;
- fd2obj[index].sentinel = 0;
- fd2obj[++index].sentinel = -1;
- }
- Py_DECREF(fast_seq);
- return max+1;
+ FD_SET(v, set);
+
+ /* add object and its file descriptor to the list */
+ if (index >= FD_SETSIZE) {
+ PyErr_SetString(PyExc_ValueError,
+ "too many file descriptors in select()");
+ goto finally;
+ }
+ fd2obj[index].obj = o;
+ fd2obj[index].fd = v;
+ fd2obj[index].sentinel = 0;
+ fd2obj[++index].sentinel = -1;
+ }
+ Py_DECREF(fast_seq);
+ return max+1;
finally:
- Py_XDECREF(o);
- Py_DECREF(fast_seq);
- return -1;
+ Py_XDECREF(o);
+ Py_DECREF(fast_seq);
+ return -1;
}
/* returns NULL and sets the Python exception if an error occurred */
static PyObject *
set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
- int i, j, count=0;
- PyObject *list, *o;
- SOCKET fd;
-
- for (j = 0; fd2obj[j].sentinel >= 0; j++) {
- if (FD_ISSET(fd2obj[j].fd, set))
- count++;
- }
- list = PyList_New(count);
- if (!list)
- return NULL;
-
- i = 0;
- for (j = 0; fd2obj[j].sentinel >= 0; j++) {
- fd = fd2obj[j].fd;
- if (FD_ISSET(fd, set)) {
+ int i, j, count=0;
+ PyObject *list, *o;
+ SOCKET fd;
+
+ for (j = 0; fd2obj[j].sentinel >= 0; j++) {
+ if (FD_ISSET(fd2obj[j].fd, set))
+ count++;
+ }
+ list = PyList_New(count);
+ if (!list)
+ return NULL;
+
+ i = 0;
+ for (j = 0; fd2obj[j].sentinel >= 0; j++) {
+ fd = fd2obj[j].fd;
+ if (FD_ISSET(fd, set)) {
#ifndef _MSC_VER
- if (fd > FD_SETSIZE) {
- PyErr_SetString(PyExc_SystemError,
- "filedescriptor out of range returned in select()");
- goto finally;
- }
+ if (fd > FD_SETSIZE) {
+ PyErr_SetString(PyExc_SystemError,
+ "filedescriptor out of range returned in select()");
+ goto finally;
+ }
#endif
- o = fd2obj[j].obj;
- fd2obj[j].obj = NULL;
- /* transfer ownership */
- if (PyList_SetItem(list, i, o) < 0)
- goto finally;
-
- i++;
- }
- }
- return list;
+ o = fd2obj[j].obj;
+ fd2obj[j].obj = NULL;
+ /* transfer ownership */
+ if (PyList_SetItem(list, i, o) < 0)
+ goto finally;
+
+ i++;
+ }
+ }
+ return list;
finally:
- Py_DECREF(list);
- return NULL;
+ Py_DECREF(list);
+ return NULL;
}
#undef SELECT_USES_HEAP
@@ -192,170 +192,170 @@ static PyObject *
select_select(PyObject *self, PyObject *args)
{
#ifdef SELECT_USES_HEAP
- pylist *rfd2obj, *wfd2obj, *efd2obj;
+ pylist *rfd2obj, *wfd2obj, *efd2obj;
#else /* !SELECT_USES_HEAP */
- /* XXX: All this should probably be implemented as follows:
- * - find the highest descriptor we're interested in
- * - add one
- * - that's the size
- * See: Stevens, APitUE, $12.5.1
- */
- pylist rfd2obj[FD_SETSIZE + 1];
- pylist wfd2obj[FD_SETSIZE + 1];
- pylist efd2obj[FD_SETSIZE + 1];
+ /* XXX: All this should probably be implemented as follows:
+ * - find the highest descriptor we're interested in
+ * - add one
+ * - that's the size
+ * See: Stevens, APitUE, $12.5.1
+ */
+ pylist rfd2obj[FD_SETSIZE + 1];
+ pylist wfd2obj[FD_SETSIZE + 1];
+ pylist efd2obj[FD_SETSIZE + 1];
#endif /* SELECT_USES_HEAP */
- PyObject *ifdlist, *ofdlist, *efdlist;
- PyObject *ret = NULL;
- PyObject *tout = Py_None;
- fd_set ifdset, ofdset, efdset;
- double timeout;
- struct timeval tv, *tvp;
- long seconds;
- int imax, omax, emax, max;
- int n;
-
- /* convert arguments */
- if (!PyArg_UnpackTuple(args, "select", 3, 4,
- &ifdlist, &ofdlist, &efdlist, &tout))
- return NULL;
-
- if (tout == Py_None)
- tvp = (struct timeval *)0;
- else if (!PyNumber_Check(tout)) {
- PyErr_SetString(PyExc_TypeError,
- "timeout must be a float or None");
- return NULL;
- }
- else {
- timeout = PyFloat_AsDouble(tout);
- if (timeout == -1 && PyErr_Occurred())
- return NULL;
- if (timeout > (double)LONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout period too long");
- return NULL;
- }
- seconds = (long)timeout;
- timeout = timeout - (double)seconds;
- tv.tv_sec = seconds;
- tv.tv_usec = (long)(timeout * 1E6);
- tvp = &tv;
- }
+ PyObject *ifdlist, *ofdlist, *efdlist;
+ PyObject *ret = NULL;
+ PyObject *tout = Py_None;
+ fd_set ifdset, ofdset, efdset;
+ double timeout;
+ struct timeval tv, *tvp;
+ long seconds;
+ int imax, omax, emax, max;
+ int n;
+
+ /* convert arguments */
+ if (!PyArg_UnpackTuple(args, "select", 3, 4,
+ &ifdlist, &ofdlist, &efdlist, &tout))
+ return NULL;
+
+ if (tout == Py_None)
+ tvp = (struct timeval *)0;
+ else if (!PyNumber_Check(tout)) {
+ PyErr_SetString(PyExc_TypeError,
+ "timeout must be a float or None");
+ return NULL;
+ }
+ else {
+ timeout = PyFloat_AsDouble(tout);
+ if (timeout == -1 && PyErr_Occurred())
+ return NULL;
+ if (timeout > (double)LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout period too long");
+ return NULL;
+ }
+ seconds = (long)timeout;
+ timeout = timeout - (double)seconds;
+ tv.tv_sec = seconds;
+ tv.tv_usec = (long)(timeout * 1E6);
+ tvp = &tv;
+ }
#ifdef SELECT_USES_HEAP
- /* Allocate memory for the lists */
- rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
- wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
- efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
- if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
- if (rfd2obj) PyMem_DEL(rfd2obj);
- if (wfd2obj) PyMem_DEL(wfd2obj);
- if (efd2obj) PyMem_DEL(efd2obj);
- return PyErr_NoMemory();
- }
+ /* Allocate memory for the lists */
+ rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
+ wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
+ efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
+ if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
+ if (rfd2obj) PyMem_DEL(rfd2obj);
+ if (wfd2obj) PyMem_DEL(wfd2obj);
+ if (efd2obj) PyMem_DEL(efd2obj);
+ return PyErr_NoMemory();
+ }
#endif /* SELECT_USES_HEAP */
- /* Convert sequences to fd_sets, and get maximum fd number
- * propagates the Python exception set in seq2set()
- */
- rfd2obj[0].sentinel = -1;
- wfd2obj[0].sentinel = -1;
- efd2obj[0].sentinel = -1;
- if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
- goto finally;
- if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
- goto finally;
- if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
- goto finally;
- max = imax;
- if (omax > max) max = omax;
- if (emax > max) max = emax;
-
- Py_BEGIN_ALLOW_THREADS
- n = select(max, &ifdset, &ofdset, &efdset, tvp);
- Py_END_ALLOW_THREADS
+ /* Convert sequences to fd_sets, and get maximum fd number
+ * propagates the Python exception set in seq2set()
+ */
+ rfd2obj[0].sentinel = -1;
+ wfd2obj[0].sentinel = -1;
+ efd2obj[0].sentinel = -1;
+ if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
+ goto finally;
+ if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
+ goto finally;
+ if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
+ goto finally;
+ max = imax;
+ if (omax > max) max = omax;
+ if (emax > max) max = emax;
+
+ Py_BEGIN_ALLOW_THREADS
+ n = select(max, &ifdset, &ofdset, &efdset, tvp);
+ Py_END_ALLOW_THREADS
#ifdef MS_WINDOWS
- if (n == SOCKET_ERROR) {
- PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
- }
+ if (n == SOCKET_ERROR) {
+ PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
+ }
#else
- if (n < 0) {
- PyErr_SetFromErrno(SelectError);
- }
+ if (n < 0) {
+ PyErr_SetFromErrno(SelectError);
+ }
#endif
- else {
- /* any of these three calls can raise an exception. it's more
- convenient to test for this after all three calls... but
- is that acceptable?
- */
- ifdlist = set2list(&ifdset, rfd2obj);
- ofdlist = set2list(&ofdset, wfd2obj);
- efdlist = set2list(&efdset, efd2obj);
- if (PyErr_Occurred())
- ret = NULL;
- else
- ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
-
- Py_DECREF(ifdlist);
- Py_DECREF(ofdlist);
- Py_DECREF(efdlist);
- }
-
+ else {
+ /* any of these three calls can raise an exception. it's more
+ convenient to test for this after all three calls... but
+ is that acceptable?
+ */
+ ifdlist = set2list(&ifdset, rfd2obj);
+ ofdlist = set2list(&ofdset, wfd2obj);
+ efdlist = set2list(&efdset, efd2obj);
+ if (PyErr_Occurred())
+ ret = NULL;
+ else
+ ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
+
+ Py_DECREF(ifdlist);
+ Py_DECREF(ofdlist);
+ Py_DECREF(efdlist);
+ }
+
finally:
- reap_obj(rfd2obj);
- reap_obj(wfd2obj);
- reap_obj(efd2obj);
+ reap_obj(rfd2obj);
+ reap_obj(wfd2obj);
+ reap_obj(efd2obj);
#ifdef SELECT_USES_HEAP
- PyMem_DEL(rfd2obj);
- PyMem_DEL(wfd2obj);
- PyMem_DEL(efd2obj);
+ PyMem_DEL(rfd2obj);
+ PyMem_DEL(wfd2obj);
+ PyMem_DEL(efd2obj);
#endif /* SELECT_USES_HEAP */
- return ret;
+ return ret;
}
#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
-/*
+/*
* poll() support
*/
typedef struct {
- PyObject_HEAD
- PyObject *dict;
- int ufd_uptodate;
- int ufd_len;
- struct pollfd *ufds;
+ PyObject_HEAD
+ PyObject *dict;
+ int ufd_uptodate;
+ int ufd_len;
+ struct pollfd *ufds;
} pollObject;
static PyTypeObject poll_Type;
-/* Update the malloc'ed array of pollfds to match the dictionary
+/* Update the malloc'ed array of pollfds to match the dictionary
contained within a pollObject. Return 1 on success, 0 on an error.
*/
static int
update_ufd_array(pollObject *self)
{
- Py_ssize_t i, pos;
- PyObject *key, *value;
- struct pollfd *old_ufds = self->ufds;
-
- self->ufd_len = PyDict_Size(self->dict);
- PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
- if (self->ufds == NULL) {
- self->ufds = old_ufds;
- PyErr_NoMemory();
- return 0;
- }
-
- i = pos = 0;
- while (PyDict_Next(self->dict, &pos, &key, &value)) {
- self->ufds[i].fd = PyLong_AsLong(key);
- self->ufds[i].events = (short)PyLong_AsLong(value);
- i++;
- }
- self->ufd_uptodate = 1;
- return 1;
+ Py_ssize_t i, pos;
+ PyObject *key, *value;
+ struct pollfd *old_ufds = self->ufds;
+
+ self->ufd_len = PyDict_Size(self->dict);
+ PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
+ if (self->ufds == NULL) {
+ self->ufds = old_ufds;
+ PyErr_NoMemory();
+ return 0;
+ }
+
+ i = pos = 0;
+ while (PyDict_Next(self->dict, &pos, &key, &value)) {
+ self->ufds[i].fd = PyLong_AsLong(key);
+ self->ufds[i].events = (short)PyLong_AsLong(value);
+ i++;
+ }
+ self->ufd_uptodate = 1;
+ return 1;
}
PyDoc_STRVAR(poll_register_doc,
@@ -366,39 +366,39 @@ fd -- either an integer, or an object with a fileno() method returning an\n\
events -- an optional bitmask describing the type of events to check for");
static PyObject *
-poll_register(pollObject *self, PyObject *args)
+poll_register(pollObject *self, PyObject *args)
{
- PyObject *o, *key, *value;
- int fd, events = POLLIN | POLLPRI | POLLOUT;
- int err;
-
- if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
- return NULL;
- }
-
- fd = PyObject_AsFileDescriptor(o);
- if (fd == -1) return NULL;
-
- /* Add entry to the internal dictionary: the key is the
- file descriptor, and the value is the event mask. */
- key = PyLong_FromLong(fd);
- if (key == NULL)
- return NULL;
- value = PyLong_FromLong(events);
- if (value == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- err = PyDict_SetItem(self->dict, key, value);
- Py_DECREF(key);
- Py_DECREF(value);
- if (err < 0)
- return NULL;
-
- self->ufd_uptodate = 0;
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *o, *key, *value;
+ int fd, events = POLLIN | POLLPRI | POLLOUT;
+ int err;
+
+ if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
+ return NULL;
+ }
+
+ fd = PyObject_AsFileDescriptor(o);
+ if (fd == -1) return NULL;
+
+ /* Add entry to the internal dictionary: the key is the
+ file descriptor, and the value is the event mask. */
+ key = PyLong_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+ value = PyLong_FromLong(events);
+ if (value == NULL) {
+ Py_DECREF(key);
+ return NULL;
+ }
+ err = PyDict_SetItem(self->dict, key, value);
+ Py_DECREF(key);
+ Py_DECREF(value);
+ if (err < 0)
+ return NULL;
+
+ self->ufd_uptodate = 0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(poll_modify_doc,
@@ -411,41 +411,41 @@ events -- an optional bitmask describing the type of events to check for");
static PyObject *
poll_modify(pollObject *self, PyObject *args)
{
- PyObject *o, *key, *value;
- int fd, events;
- int err;
-
- if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {
- return NULL;
- }
-
- fd = PyObject_AsFileDescriptor(o);
- if (fd == -1) return NULL;
-
- /* Modify registered fd */
- key = PyLong_FromLong(fd);
- if (key == NULL)
- return NULL;
- if (PyDict_GetItem(self->dict, key) == NULL) {
- errno = ENOENT;
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- value = PyLong_FromLong(events);
- if (value == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- err = PyDict_SetItem(self->dict, key, value);
- Py_DECREF(key);
- Py_DECREF(value);
- if (err < 0)
- return NULL;
-
- self->ufd_uptodate = 0;
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *o, *key, *value;
+ int fd, events;
+ int err;
+
+ if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {
+ return NULL;
+ }
+
+ fd = PyObject_AsFileDescriptor(o);
+ if (fd == -1) return NULL;
+
+ /* Modify registered fd */
+ key = PyLong_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+ if (PyDict_GetItem(self->dict, key) == NULL) {
+ errno = ENOENT;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ value = PyLong_FromLong(events);
+ if (value == NULL) {
+ Py_DECREF(key);
+ return NULL;
+ }
+ err = PyDict_SetItem(self->dict, key, value);
+ Py_DECREF(key);
+ Py_DECREF(value);
+ if (err < 0)
+ return NULL;
+
+ self->ufd_uptodate = 0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -454,32 +454,32 @@ PyDoc_STRVAR(poll_unregister_doc,
Remove a file descriptor being tracked by the polling object.");
static PyObject *
-poll_unregister(pollObject *self, PyObject *o)
+poll_unregister(pollObject *self, PyObject *o)
{
- PyObject *key;
- int fd;
-
- fd = PyObject_AsFileDescriptor( o );
- if (fd == -1)
- return NULL;
-
- /* Check whether the fd is already in the array */
- key = PyLong_FromLong(fd);
- if (key == NULL)
- return NULL;
-
- if (PyDict_DelItem(self->dict, key) == -1) {
- Py_DECREF(key);
- /* This will simply raise the KeyError set by PyDict_DelItem
- if the file descriptor isn't registered. */
- return NULL;
- }
-
- Py_DECREF(key);
- self->ufd_uptodate = 0;
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *key;
+ int fd;
+
+ fd = PyObject_AsFileDescriptor( o );
+ if (fd == -1)
+ return NULL;
+
+ /* Check whether the fd is already in the array */
+ key = PyLong_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+
+ if (PyDict_DelItem(self->dict, key) == -1) {
+ Py_DECREF(key);
+ /* This will simply raise the KeyError set by PyDict_DelItem
+ if the file descriptor isn't registered. */
+ return NULL;
+ }
+
+ Py_DECREF(key);
+ self->ufd_uptodate = 0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(poll_poll_doc,
@@ -488,169 +488,169 @@ Polls the set of registered file descriptors, returning a list containing \n\
any descriptors that have events or errors to report.");
static PyObject *
-poll_poll(pollObject *self, PyObject *args)
+poll_poll(pollObject *self, PyObject *args)
{
- PyObject *result_list = NULL, *tout = NULL;
- int timeout = 0, poll_result, i, j;
- PyObject *value = NULL, *num = NULL;
-
- if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
- return NULL;
- }
-
- /* Check values for timeout */
- if (tout == NULL || tout == Py_None)
- timeout = -1;
- else if (!PyNumber_Check(tout)) {
- PyErr_SetString(PyExc_TypeError,
- "timeout must be an integer or None");
- return NULL;
- }
- else {
- tout = PyNumber_Long(tout);
- if (!tout)
- return NULL;
- timeout = PyLong_AsLong(tout);
- Py_DECREF(tout);
- if (timeout == -1 && PyErr_Occurred())
- return NULL;
- }
-
- /* Ensure the ufd array is up to date */
- if (!self->ufd_uptodate)
- if (update_ufd_array(self) == 0)
- return NULL;
-
- /* call poll() */
- Py_BEGIN_ALLOW_THREADS
- poll_result = poll(self->ufds, self->ufd_len, timeout);
- Py_END_ALLOW_THREADS
-
- if (poll_result < 0) {
- PyErr_SetFromErrno(SelectError);
- return NULL;
- }
-
- /* build the result list */
-
- result_list = PyList_New(poll_result);
- if (!result_list)
- return NULL;
- else {
- for (i = 0, j = 0; j < poll_result; j++) {
- /* skip to the next fired descriptor */
- while (!self->ufds[i].revents) {
- i++;
- }
- /* if we hit a NULL return, set value to NULL
- and break out of loop; code at end will
- clean up result_list */
- value = PyTuple_New(2);
- if (value == NULL)
- goto error;
- num = PyLong_FromLong(self->ufds[i].fd);
- if (num == NULL) {
- Py_DECREF(value);
- goto error;
- }
- PyTuple_SET_ITEM(value, 0, num);
-
- /* The &0xffff is a workaround for AIX. 'revents'
- is a 16-bit short, and IBM assigned POLLNVAL
- to be 0x8000, so the conversion to int results
- in a negative number. See SF bug #923315. */
- num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
- if (num == NULL) {
- Py_DECREF(value);
- goto error;
- }
- PyTuple_SET_ITEM(value, 1, num);
- if ((PyList_SetItem(result_list, j, value)) == -1) {
- Py_DECREF(value);
- goto error;
- }
- i++;
- }
- }
- return result_list;
+ PyObject *result_list = NULL, *tout = NULL;
+ int timeout = 0, poll_result, i, j;
+ PyObject *value = NULL, *num = NULL;
+
+ if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
+ return NULL;
+ }
+
+ /* Check values for timeout */
+ if (tout == NULL || tout == Py_None)
+ timeout = -1;
+ else if (!PyNumber_Check(tout)) {
+ PyErr_SetString(PyExc_TypeError,
+ "timeout must be an integer or None");
+ return NULL;
+ }
+ else {
+ tout = PyNumber_Long(tout);
+ if (!tout)
+ return NULL;
+ timeout = PyLong_AsLong(tout);
+ Py_DECREF(tout);
+ if (timeout == -1 && PyErr_Occurred())
+ return NULL;
+ }
+
+ /* Ensure the ufd array is up to date */
+ if (!self->ufd_uptodate)
+ if (update_ufd_array(self) == 0)
+ return NULL;
+
+ /* call poll() */
+ Py_BEGIN_ALLOW_THREADS
+ poll_result = poll(self->ufds, self->ufd_len, timeout);
+ Py_END_ALLOW_THREADS
+
+ if (poll_result < 0) {
+ PyErr_SetFromErrno(SelectError);
+ return NULL;
+ }
+
+ /* build the result list */
+
+ result_list = PyList_New(poll_result);
+ if (!result_list)
+ return NULL;
+ else {
+ for (i = 0, j = 0; j < poll_result; j++) {
+ /* skip to the next fired descriptor */
+ while (!self->ufds[i].revents) {
+ i++;
+ }
+ /* if we hit a NULL return, set value to NULL
+ and break out of loop; code at end will
+ clean up result_list */
+ value = PyTuple_New(2);
+ if (value == NULL)
+ goto error;
+ num = PyLong_FromLong(self->ufds[i].fd);
+ if (num == NULL) {
+ Py_DECREF(value);
+ goto error;
+ }
+ PyTuple_SET_ITEM(value, 0, num);
+
+ /* The &0xffff is a workaround for AIX. 'revents'
+ is a 16-bit short, and IBM assigned POLLNVAL
+ to be 0x8000, so the conversion to int results
+ in a negative number. See SF bug #923315. */
+ num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
+ if (num == NULL) {
+ Py_DECREF(value);
+ goto error;
+ }
+ PyTuple_SET_ITEM(value, 1, num);
+ if ((PyList_SetItem(result_list, j, value)) == -1) {
+ Py_DECREF(value);
+ goto error;
+ }
+ i++;
+ }
+ }
+ return result_list;
error:
- Py_DECREF(result_list);
- return NULL;
+ Py_DECREF(result_list);
+ return NULL;
}
static PyMethodDef poll_methods[] = {
- {"register", (PyCFunction)poll_register,
- METH_VARARGS, poll_register_doc},
- {"modify", (PyCFunction)poll_modify,
- METH_VARARGS, poll_modify_doc},
- {"unregister", (PyCFunction)poll_unregister,
- METH_O, poll_unregister_doc},
- {"poll", (PyCFunction)poll_poll,
- METH_VARARGS, poll_poll_doc},
- {NULL, NULL} /* sentinel */
+ {"register", (PyCFunction)poll_register,
+ METH_VARARGS, poll_register_doc},
+ {"modify", (PyCFunction)poll_modify,
+ METH_VARARGS, poll_modify_doc},
+ {"unregister", (PyCFunction)poll_unregister,
+ METH_O, poll_unregister_doc},
+ {"poll", (PyCFunction)poll_poll,
+ METH_VARARGS, poll_poll_doc},
+ {NULL, NULL} /* sentinel */
};
static pollObject *
newPollObject(void)
{
- pollObject *self;
- self = PyObject_New(pollObject, &poll_Type);
- if (self == NULL)
- return NULL;
- /* ufd_uptodate is a Boolean, denoting whether the
- array pointed to by ufds matches the contents of the dictionary. */
- self->ufd_uptodate = 0;
- self->ufds = NULL;
- self->dict = PyDict_New();
- if (self->dict == NULL) {
- Py_DECREF(self);
- return NULL;
- }
- return self;
+ pollObject *self;
+ self = PyObject_New(pollObject, &poll_Type);
+ if (self == NULL)
+ return NULL;
+ /* ufd_uptodate is a Boolean, denoting whether the
+ array pointed to by ufds matches the contents of the dictionary. */
+ self->ufd_uptodate = 0;
+ self->ufds = NULL;
+ self->dict = PyDict_New();
+ if (self->dict == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ return self;
}
static void
poll_dealloc(pollObject *self)
{
- if (self->ufds != NULL)
- PyMem_DEL(self->ufds);
- Py_XDECREF(self->dict);
- PyObject_Del(self);
+ if (self->ufds != NULL)
+ PyMem_DEL(self->ufds);
+ Py_XDECREF(self->dict);
+ PyObject_Del(self);
}
static PyTypeObject poll_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.poll", /*tp_name*/
- sizeof(pollObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)poll_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 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, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- poll_methods, /*tp_methods*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.poll", /*tp_name*/
+ sizeof(pollObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)poll_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 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, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ poll_methods, /*tp_methods*/
};
PyDoc_STRVAR(poll_doc,
@@ -660,36 +660,36 @@ unregistering file descriptors, and then polling them for I/O events.");
static PyObject *
select_poll(PyObject *self, PyObject *unused)
{
- return (PyObject *)newPollObject();
+ return (PyObject *)newPollObject();
}
#ifdef __APPLE__
-/*
+/*
* On some systems poll() sets errno on invalid file descriptors. We test
* for this at runtime because this bug may be fixed or introduced between
* OS releases.
*/
static int select_have_broken_poll(void)
{
- int poll_test;
- int filedes[2];
-
- struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
-
- /* Create a file descriptor to make invalid */
- if (pipe(filedes) < 0) {
- return 1;
- }
- poll_struct.fd = filedes[0];
- close(filedes[0]);
- close(filedes[1]);
- poll_test = poll(&poll_struct, 1, 0);
- if (poll_test < 0) {
- return 1;
- } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
- return 1;
- }
- return 0;
+ int poll_test;
+ int filedes[2];
+
+ struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
+
+ /* Create a file descriptor to make invalid */
+ if (pipe(filedes) < 0) {
+ return 1;
+ }
+ poll_struct.fd = filedes[0];
+ close(filedes[0]);
+ close(filedes[1]);
+ poll_test = poll(&poll_struct, 1, 0);
+ if (poll_test < 0) {
+ return 1;
+ } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
+ return 1;
+ }
+ return 0;
}
#endif /* __APPLE__ */
@@ -708,8 +708,8 @@ static int select_have_broken_poll(void)
#endif
typedef struct {
- PyObject_HEAD
- SOCKET epfd; /* epoll control file descriptor */
+ PyObject_HEAD
+ SOCKET epfd; /* epoll control file descriptor */
} pyEpoll_Object;
static PyTypeObject pyEpoll_Type;
@@ -718,92 +718,92 @@ static PyTypeObject pyEpoll_Type;
static PyObject *
pyepoll_err_closed(void)
{
- PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
+ return NULL;
}
static int
pyepoll_internal_close(pyEpoll_Object *self)
{
- int save_errno = 0;
- if (self->epfd >= 0) {
- int epfd = self->epfd;
- self->epfd = -1;
- Py_BEGIN_ALLOW_THREADS
- if (close(epfd) < 0)
- save_errno = errno;
- Py_END_ALLOW_THREADS
- }
- return save_errno;
+ int save_errno = 0;
+ if (self->epfd >= 0) {
+ int epfd = self->epfd;
+ self->epfd = -1;
+ Py_BEGIN_ALLOW_THREADS
+ if (close(epfd) < 0)
+ save_errno = errno;
+ Py_END_ALLOW_THREADS
+ }
+ return save_errno;
}
static PyObject *
newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd)
{
- pyEpoll_Object *self;
-
- if (sizehint == -1) {
- sizehint = FD_SETSIZE-1;
- }
- else if (sizehint < 1) {
- PyErr_Format(PyExc_ValueError,
- "sizehint must be greater zero, got %d",
- sizehint);
- return NULL;
- }
-
- assert(type != NULL && type->tp_alloc != NULL);
- self = (pyEpoll_Object *) type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- if (fd == -1) {
- Py_BEGIN_ALLOW_THREADS
- self->epfd = epoll_create(sizehint);
- Py_END_ALLOW_THREADS
- }
- else {
- self->epfd = fd;
- }
- if (self->epfd < 0) {
- Py_DECREF(self);
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return (PyObject *)self;
+ pyEpoll_Object *self;
+
+ if (sizehint == -1) {
+ sizehint = FD_SETSIZE-1;
+ }
+ else if (sizehint < 1) {
+ PyErr_Format(PyExc_ValueError,
+ "sizehint must be greater zero, got %d",
+ sizehint);
+ return NULL;
+ }
+
+ assert(type != NULL && type->tp_alloc != NULL);
+ self = (pyEpoll_Object *) type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ if (fd == -1) {
+ Py_BEGIN_ALLOW_THREADS
+ self->epfd = epoll_create(sizehint);
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ self->epfd = fd;
+ }
+ if (self->epfd < 0) {
+ Py_DECREF(self);
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return (PyObject *)self;
}
static PyObject *
pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- int sizehint = -1;
- static char *kwlist[] = {"sizehint", NULL};
+ int sizehint = -1;
+ static char *kwlist[] = {"sizehint", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist,
- &sizehint))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist,
+ &sizehint))
+ return NULL;
- return newPyEpoll_Object(type, sizehint, -1);
+ return newPyEpoll_Object(type, sizehint, -1);
}
static void
pyepoll_dealloc(pyEpoll_Object *self)
{
- (void)pyepoll_internal_close(self);
- Py_TYPE(self)->tp_free(self);
+ (void)pyepoll_internal_close(self);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject*
pyepoll_close(pyEpoll_Object *self)
{
- errno = pyepoll_internal_close(self);
- if (errno < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_RETURN_NONE;
+ errno = pyepoll_internal_close(self);
+ if (errno < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(pyepoll_close_doc,
@@ -815,18 +815,18 @@ object will raise an exception.");
static PyObject*
pyepoll_get_closed(pyEpoll_Object *self)
{
- if (self->epfd < 0)
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
+ if (self->epfd < 0)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
}
static PyObject*
pyepoll_fileno(pyEpoll_Object *self)
{
- if (self->epfd < 0)
- return pyepoll_err_closed();
- return PyLong_FromLong(self->epfd);
+ if (self->epfd < 0)
+ return pyepoll_err_closed();
+ return PyLong_FromLong(self->epfd);
}
PyDoc_STRVAR(pyepoll_fileno_doc,
@@ -837,12 +837,12 @@ Return the epoll control file descriptor.");
static PyObject*
pyepoll_fromfd(PyObject *cls, PyObject *args)
{
- SOCKET fd;
+ SOCKET fd;
- if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
+ return NULL;
- return newPyEpoll_Object((PyTypeObject*)cls, -1, fd);
+ return newPyEpoll_Object((PyTypeObject*)cls, -1, fd);
}
PyDoc_STRVAR(pyepoll_fromfd_doc,
@@ -853,65 +853,65 @@ Create an epoll object from a given control fd.");
static PyObject *
pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
{
- struct epoll_event ev;
- int result;
- int fd;
-
- if (epfd < 0)
- return pyepoll_err_closed();
-
- fd = PyObject_AsFileDescriptor(pfd);
- if (fd == -1) {
- return NULL;
- }
-
- switch(op) {
- case EPOLL_CTL_ADD:
- case EPOLL_CTL_MOD:
- ev.events = events;
- ev.data.fd = fd;
- Py_BEGIN_ALLOW_THREADS
- result = epoll_ctl(epfd, op, fd, &ev);
- Py_END_ALLOW_THREADS
- break;
- case EPOLL_CTL_DEL:
- /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
- * operation required a non-NULL pointer in event, even
- * though this argument is ignored. */
- Py_BEGIN_ALLOW_THREADS
- result = epoll_ctl(epfd, op, fd, &ev);
- if (errno == EBADF) {
- /* fd already closed */
- result = 0;
- errno = 0;
- }
- Py_END_ALLOW_THREADS
- break;
- default:
- result = -1;
- errno = EINVAL;
- }
-
- if (result < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_RETURN_NONE;
+ struct epoll_event ev;
+ int result;
+ int fd;
+
+ if (epfd < 0)
+ return pyepoll_err_closed();
+
+ fd = PyObject_AsFileDescriptor(pfd);
+ if (fd == -1) {
+ return NULL;
+ }
+
+ switch(op) {
+ case EPOLL_CTL_ADD:
+ case EPOLL_CTL_MOD:
+ ev.events = events;
+ ev.data.fd = fd;
+ Py_BEGIN_ALLOW_THREADS
+ result = epoll_ctl(epfd, op, fd, &ev);
+ Py_END_ALLOW_THREADS
+ break;
+ case EPOLL_CTL_DEL:
+ /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
+ * operation required a non-NULL pointer in event, even
+ * though this argument is ignored. */
+ Py_BEGIN_ALLOW_THREADS
+ result = epoll_ctl(epfd, op, fd, &ev);
+ if (errno == EBADF) {
+ /* fd already closed */
+ result = 0;
+ errno = 0;
+ }
+ Py_END_ALLOW_THREADS
+ break;
+ default:
+ result = -1;
+ errno = EINVAL;
+ }
+
+ if (result < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject *
pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
- static char *kwlist[] = {"fd", "eventmask", NULL};
+ PyObject *pfd;
+ unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
+ static char *kwlist[] = {"fd", "eventmask", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
- &pfd, &events)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
+ &pfd, &events)) {
+ return NULL;
+ }
- return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
+ return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
}
PyDoc_STRVAR(pyepoll_register_doc,
@@ -928,16 +928,16 @@ The epoll interface supports all file descriptors that support poll.");
static PyObject *
pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- unsigned int events;
- static char *kwlist[] = {"fd", "eventmask", NULL};
+ PyObject *pfd;
+ unsigned int events;
+ static char *kwlist[] = {"fd", "eventmask", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
- &pfd, &events)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
+ &pfd, &events)) {
+ return NULL;
+ }
- return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
+ return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
}
PyDoc_STRVAR(pyepoll_modify_doc,
@@ -949,15 +949,15 @@ events is a bit set composed of the various EPOLL constants");
static PyObject *
pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- static char *kwlist[] = {"fd", NULL};
+ PyObject *pfd;
+ static char *kwlist[] = {"fd", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
- &pfd)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
+ &pfd)) {
+ return NULL;
+ }
- return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
+ return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
}
PyDoc_STRVAR(pyepoll_unregister_doc,
@@ -968,76 +968,76 @@ fd is the target file descriptor of the operation.");
static PyObject *
pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- double dtimeout = -1.;
- int timeout;
- int maxevents = -1;
- int nfds, i;
- PyObject *elist = NULL, *etuple = NULL;
- struct epoll_event *evs = NULL;
- static char *kwlist[] = {"timeout", "maxevents", NULL};
-
- if (self->epfd < 0)
- return pyepoll_err_closed();
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
- &dtimeout, &maxevents)) {
- return NULL;
- }
-
- if (dtimeout < 0) {
- timeout = -1;
- }
- else if (dtimeout * 1000.0 > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout is too large");
- return NULL;
- }
- else {
- timeout = (int)(dtimeout * 1000.0);
- }
-
- if (maxevents == -1) {
- maxevents = FD_SETSIZE-1;
- }
- else if (maxevents < 1) {
- PyErr_Format(PyExc_ValueError,
- "maxevents must be greater than 0, got %d",
- maxevents);
- return NULL;
- }
-
- evs = PyMem_New(struct epoll_event, maxevents);
- if (evs == NULL) {
- Py_DECREF(self);
- PyErr_NoMemory();
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
- Py_END_ALLOW_THREADS
- if (nfds < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- goto error;
- }
-
- elist = PyList_New(nfds);
- if (elist == NULL) {
- goto error;
- }
-
- for (i = 0; i < nfds; i++) {
- etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
- if (etuple == NULL) {
- Py_CLEAR(elist);
- goto error;
- }
- PyList_SET_ITEM(elist, i, etuple);
- }
+ double dtimeout = -1.;
+ int timeout;
+ int maxevents = -1;
+ int nfds, i;
+ PyObject *elist = NULL, *etuple = NULL;
+ struct epoll_event *evs = NULL;
+ static char *kwlist[] = {"timeout", "maxevents", NULL};
+
+ if (self->epfd < 0)
+ return pyepoll_err_closed();
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
+ &dtimeout, &maxevents)) {
+ return NULL;
+ }
+
+ if (dtimeout < 0) {
+ timeout = -1;
+ }
+ else if (dtimeout * 1000.0 > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout is too large");
+ return NULL;
+ }
+ else {
+ timeout = (int)(dtimeout * 1000.0);
+ }
+
+ if (maxevents == -1) {
+ maxevents = FD_SETSIZE-1;
+ }
+ else if (maxevents < 1) {
+ PyErr_Format(PyExc_ValueError,
+ "maxevents must be greater than 0, got %d",
+ maxevents);
+ return NULL;
+ }
+
+ evs = PyMem_New(struct epoll_event, maxevents);
+ if (evs == NULL) {
+ Py_DECREF(self);
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
+ Py_END_ALLOW_THREADS
+ if (nfds < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ goto error;
+ }
+
+ elist = PyList_New(nfds);
+ if (elist == NULL) {
+ goto error;
+ }
+
+ for (i = 0; i < nfds; i++) {
+ etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
+ if (etuple == NULL) {
+ Py_CLEAR(elist);
+ goto error;
+ }
+ PyList_SET_ITEM(elist, i, etuple);
+ }
error:
- PyMem_Free(evs);
- return elist;
+ PyMem_Free(evs);
+ return elist;
}
PyDoc_STRVAR(pyepoll_poll_doc,
@@ -1048,27 +1048,27 @@ in seconds (as float). -1 makes poll wait indefinitely.\n\
Up to maxevents are returned to the caller.");
static PyMethodDef pyepoll_methods[] = {
- {"fromfd", (PyCFunction)pyepoll_fromfd,
- METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
- {"close", (PyCFunction)pyepoll_close, METH_NOARGS,
- pyepoll_close_doc},
- {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS,
- pyepoll_fileno_doc},
- {"modify", (PyCFunction)pyepoll_modify,
- METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc},
- {"register", (PyCFunction)pyepoll_register,
- METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc},
- {"unregister", (PyCFunction)pyepoll_unregister,
- METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc},
- {"poll", (PyCFunction)pyepoll_poll,
- METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc},
- {NULL, NULL},
+ {"fromfd", (PyCFunction)pyepoll_fromfd,
+ METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
+ {"close", (PyCFunction)pyepoll_close, METH_NOARGS,
+ pyepoll_close_doc},
+ {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS,
+ pyepoll_fileno_doc},
+ {"modify", (PyCFunction)pyepoll_modify,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc},
+ {"register", (PyCFunction)pyepoll_register,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc},
+ {"unregister", (PyCFunction)pyepoll_unregister,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc},
+ {"poll", (PyCFunction)pyepoll_poll,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc},
+ {NULL, NULL},
};
static PyGetSetDef pyepoll_getsetlist[] = {
- {"closed", (getter)pyepoll_get_closed, NULL,
- "True if the epoll handler is closed"},
- {0},
+ {"closed", (getter)pyepoll_get_closed, NULL,
+ "True if the epoll handler is closed"},
+ {0},
};
PyDoc_STRVAR(pyepoll_doc,
@@ -1081,45 +1081,45 @@ sizehint is used to optimize internal data structures. It doesn't limit\n\
the maximum number of monitored events.");
static PyTypeObject pyEpoll_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.epoll", /* tp_name */
- sizeof(pyEpoll_Object), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)pyepoll_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- pyepoll_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- pyepoll_methods, /* tp_methods */
- 0, /* tp_members */
- pyepoll_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- pyepoll_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.epoll", /* tp_name */
+ sizeof(pyEpoll_Object), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)pyepoll_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ pyepoll_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ pyepoll_methods, /* tp_methods */
+ 0, /* tp_members */
+ pyepoll_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ pyepoll_new, /* tp_new */
+ 0, /* tp_free */
};
#endif /* HAVE_EPOLL */
@@ -1174,8 +1174,8 @@ of. You could also set up a dictionary on the python side to store a\n\
udata->object mapping.");
typedef struct {
- PyObject_HEAD
- struct kevent e;
+ PyObject_HEAD
+ struct kevent e;
} kqueue_event_Object;
static PyTypeObject kqueue_event_Type;
@@ -1183,8 +1183,8 @@ static PyTypeObject kqueue_event_Type;
#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))
typedef struct {
- PyObject_HEAD
- SOCKET kqfd; /* kqueue control fd */
+ PyObject_HEAD
+ SOCKET kqfd; /* kqueue control fd */
} kqueue_queue_Object;
static PyTypeObject kqueue_queue_Type;
@@ -1222,13 +1222,13 @@ static PyTypeObject kqueue_queue_Type;
#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
static struct PyMemberDef kqueue_event_members[] = {
- {"ident", T_UINTPTRT, KQ_OFF(e.ident)},
- {"filter", T_SHORT, KQ_OFF(e.filter)},
- {"flags", T_USHORT, KQ_OFF(e.flags)},
- {"fflags", T_UINT, KQ_OFF(e.fflags)},
- {"data", T_INTPTRT, KQ_OFF(e.data)},
- {"udata", T_UINTPTRT, KQ_OFF(e.udata)},
- {NULL} /* Sentinel */
+ {"ident", T_UINTPTRT, KQ_OFF(e.ident)},
+ {"filter", T_SHORT, KQ_OFF(e.filter)},
+ {"flags", T_USHORT, KQ_OFF(e.flags)},
+ {"fflags", T_UINT, KQ_OFF(e.fflags)},
+ {"data", T_INTPTRT, KQ_OFF(e.data)},
+ {"udata", T_UINTPTRT, KQ_OFF(e.udata)},
+ {NULL} /* Sentinel */
};
#undef KQ_OFF
@@ -1236,214 +1236,214 @@ static PyObject *
kqueue_event_repr(kqueue_event_Object *s)
{
- char buf[1024];
- PyOS_snprintf(
- buf, sizeof(buf),
- "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
- "data=0x%zd udata=%p>",
- (size_t)(s->e.ident), s->e.filter, s->e.flags,
- s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);
- return PyUnicode_FromString(buf);
+ char buf[1024];
+ PyOS_snprintf(
+ buf, sizeof(buf),
+ "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
+ "data=0x%zd udata=%p>",
+ (size_t)(s->e.ident), s->e.filter, s->e.flags,
+ s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);
+ return PyUnicode_FromString(buf);
}
static int
kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- static char *kwlist[] = {"ident", "filter", "flags", "fflags",
- "data", "udata", NULL};
- static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";
-
- EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
- &pfd, &(self->e.filter), &(self->e.flags),
- &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
- return -1;
- }
-
- if (PyLong_Check(pfd)) {
- self->e.ident = PyLong_AsUintptr_t(pfd);
- }
- else {
- self->e.ident = PyObject_AsFileDescriptor(pfd);
- }
- if (PyErr_Occurred()) {
- return -1;
- }
- return 0;
+ PyObject *pfd;
+ static char *kwlist[] = {"ident", "filter", "flags", "fflags",
+ "data", "udata", NULL};
+ static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";
+
+ EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
+ &pfd, &(self->e.filter), &(self->e.flags),
+ &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
+ return -1;
+ }
+
+ if (PyLong_Check(pfd)) {
+ self->e.ident = PyLong_AsUintptr_t(pfd);
+ }
+ else {
+ self->e.ident = PyObject_AsFileDescriptor(pfd);
+ }
+ if (PyErr_Occurred()) {
+ return -1;
+ }
+ return 0;
}
static PyObject *
kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
- int op)
+ int op)
{
- Py_intptr_t result = 0;
-
- if (!kqueue_event_Check(o)) {
- if (op == Py_EQ || op == Py_NE) {
- PyObject *res = op == Py_EQ ? Py_False : Py_True;
- Py_INCREF(res);
- return res;
- }
- PyErr_Format(PyExc_TypeError,
- "can't compare %.200s to %.200s",
- Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);
- return NULL;
- }
- if (((result = s->e.ident - o->e.ident) == 0) &&
- ((result = s->e.filter - o->e.filter) == 0) &&
- ((result = s->e.flags - o->e.flags) == 0) &&
- ((result = s->e.fflags - o->e.fflags) == 0) &&
- ((result = s->e.data - o->e.data) == 0) &&
- ((result = s->e.udata - o->e.udata) == 0)
- ) {
- result = 0;
- }
-
- switch (op) {
- case Py_EQ:
- result = (result == 0);
- break;
- case Py_NE:
- result = (result != 0);
- break;
- case Py_LE:
- result = (result <= 0);
- break;
- case Py_GE:
- result = (result >= 0);
- break;
- case Py_LT:
- result = (result < 0);
- break;
- case Py_GT:
- result = (result > 0);
- break;
- }
- return PyBool_FromLong((long)result);
+ Py_intptr_t result = 0;
+
+ if (!kqueue_event_Check(o)) {
+ if (op == Py_EQ || op == Py_NE) {
+ PyObject *res = op == Py_EQ ? Py_False : Py_True;
+ Py_INCREF(res);
+ return res;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "can't compare %.200s to %.200s",
+ Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);
+ return NULL;
+ }
+ if (((result = s->e.ident - o->e.ident) == 0) &&
+ ((result = s->e.filter - o->e.filter) == 0) &&
+ ((result = s->e.flags - o->e.flags) == 0) &&
+ ((result = s->e.fflags - o->e.fflags) == 0) &&
+ ((result = s->e.data - o->e.data) == 0) &&
+ ((result = s->e.udata - o->e.udata) == 0)
+ ) {
+ result = 0;
+ }
+
+ switch (op) {
+ case Py_EQ:
+ result = (result == 0);
+ break;
+ case Py_NE:
+ result = (result != 0);
+ break;
+ case Py_LE:
+ result = (result <= 0);
+ break;
+ case Py_GE:
+ result = (result >= 0);
+ break;
+ case Py_LT:
+ result = (result < 0);
+ break;
+ case Py_GT:
+ result = (result > 0);
+ break;
+ }
+ return PyBool_FromLong((long)result);
}
static PyTypeObject kqueue_event_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.kevent", /* tp_name */
- sizeof(kqueue_event_Object), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)kqueue_event_repr, /* 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, /* tp_flags */
- kqueue_event_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- kqueue_event_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)kqueue_event_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.kevent", /* tp_name */
+ sizeof(kqueue_event_Object), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)kqueue_event_repr, /* 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, /* tp_flags */
+ kqueue_event_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ kqueue_event_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)kqueue_event_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
static PyObject *
kqueue_queue_err_closed(void)
{
- PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
+ return NULL;
}
static int
kqueue_queue_internal_close(kqueue_queue_Object *self)
{
- int save_errno = 0;
- if (self->kqfd >= 0) {
- int kqfd = self->kqfd;
- self->kqfd = -1;
- Py_BEGIN_ALLOW_THREADS
- if (close(kqfd) < 0)
- save_errno = errno;
- Py_END_ALLOW_THREADS
- }
- return save_errno;
+ int save_errno = 0;
+ if (self->kqfd >= 0) {
+ int kqfd = self->kqfd;
+ self->kqfd = -1;
+ Py_BEGIN_ALLOW_THREADS
+ if (close(kqfd) < 0)
+ save_errno = errno;
+ Py_END_ALLOW_THREADS
+ }
+ return save_errno;
}
static PyObject *
newKqueue_Object(PyTypeObject *type, SOCKET fd)
{
- kqueue_queue_Object *self;
- assert(type != NULL && type->tp_alloc != NULL);
- self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
- if (self == NULL) {
- return NULL;
- }
-
- if (fd == -1) {
- Py_BEGIN_ALLOW_THREADS
- self->kqfd = kqueue();
- Py_END_ALLOW_THREADS
- }
- else {
- self->kqfd = fd;
- }
- if (self->kqfd < 0) {
- Py_DECREF(self);
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return (PyObject *)self;
+ kqueue_queue_Object *self;
+ assert(type != NULL && type->tp_alloc != NULL);
+ self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
+ if (self == NULL) {
+ return NULL;
+ }
+
+ if (fd == -1) {
+ Py_BEGIN_ALLOW_THREADS
+ self->kqfd = kqueue();
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ self->kqfd = fd;
+ }
+ if (self->kqfd < 0) {
+ Py_DECREF(self);
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return (PyObject *)self;
}
static PyObject *
kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- if ((args != NULL && PyObject_Size(args)) ||
- (kwds != NULL && PyObject_Size(kwds))) {
- PyErr_SetString(PyExc_ValueError,
- "select.kqueue doesn't accept arguments");
- return NULL;
- }
+ if ((args != NULL && PyObject_Size(args)) ||
+ (kwds != NULL && PyObject_Size(kwds))) {
+ PyErr_SetString(PyExc_ValueError,
+ "select.kqueue doesn't accept arguments");
+ return NULL;
+ }
- return newKqueue_Object(type, -1);
+ return newKqueue_Object(type, -1);
}
static void
kqueue_queue_dealloc(kqueue_queue_Object *self)
{
- kqueue_queue_internal_close(self);
- Py_TYPE(self)->tp_free(self);
+ kqueue_queue_internal_close(self);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject*
kqueue_queue_close(kqueue_queue_Object *self)
{
- errno = kqueue_queue_internal_close(self);
- if (errno < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_RETURN_NONE;
+ errno = kqueue_queue_internal_close(self);
+ if (errno < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(kqueue_queue_close_doc,
@@ -1455,18 +1455,18 @@ object will raise an exception.");
static PyObject*
kqueue_queue_get_closed(kqueue_queue_Object *self)
{
- if (self->kqfd < 0)
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
+ if (self->kqfd < 0)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
}
static PyObject*
kqueue_queue_fileno(kqueue_queue_Object *self)
{
- if (self->kqfd < 0)
- return kqueue_queue_err_closed();
- return PyLong_FromLong(self->kqfd);
+ if (self->kqfd < 0)
+ return kqueue_queue_err_closed();
+ return PyLong_FromLong(self->kqfd);
}
PyDoc_STRVAR(kqueue_queue_fileno_doc,
@@ -1477,12 +1477,12 @@ Return the kqueue control file descriptor.");
static PyObject*
kqueue_queue_fromfd(PyObject *cls, PyObject *args)
{
- SOCKET fd;
+ SOCKET fd;
- if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
+ return NULL;
- return newKqueue_Object((PyTypeObject*)cls, fd);
+ return newKqueue_Object((PyTypeObject*)cls, fd);
}
PyDoc_STRVAR(kqueue_queue_fromfd_doc,
@@ -1493,144 +1493,144 @@ Create a kqueue object from a given control fd.");
static PyObject *
kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)
{
- int nevents = 0;
- int gotevents = 0;
- int nchanges = 0;
- int i = 0;
- PyObject *otimeout = NULL;
- PyObject *ch = NULL;
- PyObject *it = NULL, *ei = NULL;
- PyObject *result = NULL;
- struct kevent *evl = NULL;
- struct kevent *chl = NULL;
- struct timespec timeoutspec;
- struct timespec *ptimeoutspec;
-
- if (self->kqfd < 0)
- return kqueue_queue_err_closed();
-
- if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
- return NULL;
-
- if (nevents < 0) {
- PyErr_Format(PyExc_ValueError,
- "Length of eventlist must be 0 or positive, got %d",
- nevents);
- return NULL;
- }
-
- if (otimeout == Py_None || otimeout == NULL) {
- ptimeoutspec = NULL;
- }
- else if (PyNumber_Check(otimeout)) {
- double timeout;
- long seconds;
-
- timeout = PyFloat_AsDouble(otimeout);
- if (timeout == -1 && PyErr_Occurred())
- return NULL;
- if (timeout > (double)LONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout period too long");
- return NULL;
- }
- if (timeout < 0) {
- PyErr_SetString(PyExc_ValueError,
- "timeout must be positive or None");
- return NULL;
- }
-
- seconds = (long)timeout;
- timeout = timeout - (double)seconds;
- timeoutspec.tv_sec = seconds;
- timeoutspec.tv_nsec = (long)(timeout * 1E9);
- ptimeoutspec = &timeoutspec;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "timeout argument must be an number "
- "or None, got %.200s",
- Py_TYPE(otimeout)->tp_name);
- return NULL;
- }
-
- if (ch != NULL && ch != Py_None) {
- it = PyObject_GetIter(ch);
- if (it == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "changelist is not iterable");
- return NULL;
- }
- nchanges = PyObject_Size(ch);
- if (nchanges < 0) {
- goto error;
- }
-
- chl = PyMem_New(struct kevent, nchanges);
- if (chl == NULL) {
- PyErr_NoMemory();
- goto error;
- }
- i = 0;
- while ((ei = PyIter_Next(it)) != NULL) {
- if (!kqueue_event_Check(ei)) {
- Py_DECREF(ei);
- PyErr_SetString(PyExc_TypeError,
- "changelist must be an iterable of "
- "select.kevent objects");
- goto error;
- } else {
- chl[i++] = ((kqueue_event_Object *)ei)->e;
- }
- Py_DECREF(ei);
- }
- }
- Py_CLEAR(it);
-
- /* event list */
- if (nevents) {
- evl = PyMem_New(struct kevent, nevents);
- if (evl == NULL) {
- PyErr_NoMemory();
- goto error;
- }
- }
-
- Py_BEGIN_ALLOW_THREADS
- gotevents = kevent(self->kqfd, chl, nchanges,
- evl, nevents, ptimeoutspec);
- Py_END_ALLOW_THREADS
-
- if (gotevents == -1) {
- PyErr_SetFromErrno(PyExc_OSError);
- goto error;
- }
-
- result = PyList_New(gotevents);
- if (result == NULL) {
- goto error;
- }
-
- for (i = 0; i < gotevents; i++) {
- kqueue_event_Object *ch;
-
- ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
- if (ch == NULL) {
- goto error;
- }
- ch->e = evl[i];
- PyList_SET_ITEM(result, i, (PyObject *)ch);
- }
- PyMem_Free(chl);
- PyMem_Free(evl);
- return result;
+ int nevents = 0;
+ int gotevents = 0;
+ int nchanges = 0;
+ int i = 0;
+ PyObject *otimeout = NULL;
+ PyObject *ch = NULL;
+ PyObject *it = NULL, *ei = NULL;
+ PyObject *result = NULL;
+ struct kevent *evl = NULL;
+ struct kevent *chl = NULL;
+ struct timespec timeoutspec;
+ struct timespec *ptimeoutspec;
+
+ if (self->kqfd < 0)
+ return kqueue_queue_err_closed();
+
+ if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
+ return NULL;
+
+ if (nevents < 0) {
+ PyErr_Format(PyExc_ValueError,
+ "Length of eventlist must be 0 or positive, got %d",
+ nevents);
+ return NULL;
+ }
+
+ if (otimeout == Py_None || otimeout == NULL) {
+ ptimeoutspec = NULL;
+ }
+ else if (PyNumber_Check(otimeout)) {
+ double timeout;
+ long seconds;
+
+ timeout = PyFloat_AsDouble(otimeout);
+ if (timeout == -1 && PyErr_Occurred())
+ return NULL;
+ if (timeout > (double)LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout period too long");
+ return NULL;
+ }
+ if (timeout < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "timeout must be positive or None");
+ return NULL;
+ }
+
+ seconds = (long)timeout;
+ timeout = timeout - (double)seconds;
+ timeoutspec.tv_sec = seconds;
+ timeoutspec.tv_nsec = (long)(timeout * 1E9);
+ ptimeoutspec = &timeoutspec;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "timeout argument must be an number "
+ "or None, got %.200s",
+ Py_TYPE(otimeout)->tp_name);
+ return NULL;
+ }
+
+ if (ch != NULL && ch != Py_None) {
+ it = PyObject_GetIter(ch);
+ if (it == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "changelist is not iterable");
+ return NULL;
+ }
+ nchanges = PyObject_Size(ch);
+ if (nchanges < 0) {
+ goto error;
+ }
+
+ chl = PyMem_New(struct kevent, nchanges);
+ if (chl == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+ i = 0;
+ while ((ei = PyIter_Next(it)) != NULL) {
+ if (!kqueue_event_Check(ei)) {
+ Py_DECREF(ei);
+ PyErr_SetString(PyExc_TypeError,
+ "changelist must be an iterable of "
+ "select.kevent objects");
+ goto error;
+ } else {
+ chl[i++] = ((kqueue_event_Object *)ei)->e;
+ }
+ Py_DECREF(ei);
+ }
+ }
+ Py_CLEAR(it);
+
+ /* event list */
+ if (nevents) {
+ evl = PyMem_New(struct kevent, nevents);
+ if (evl == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ gotevents = kevent(self->kqfd, chl, nchanges,
+ evl, nevents, ptimeoutspec);
+ Py_END_ALLOW_THREADS
+
+ if (gotevents == -1) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ goto error;
+ }
+
+ result = PyList_New(gotevents);
+ if (result == NULL) {
+ goto error;
+ }
+
+ for (i = 0; i < gotevents; i++) {
+ kqueue_event_Object *ch;
+
+ ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
+ if (ch == NULL) {
+ goto error;
+ }
+ ch->e = evl[i];
+ PyList_SET_ITEM(result, i, (PyObject *)ch);
+ }
+ PyMem_Free(chl);
+ PyMem_Free(evl);
+ return result;
error:
- PyMem_Free(chl);
- PyMem_Free(evl);
- Py_XDECREF(result);
- Py_XDECREF(it);
- return NULL;
+ PyMem_Free(chl);
+ PyMem_Free(evl);
+ Py_XDECREF(result);
+ Py_XDECREF(it);
+ return NULL;
}
PyDoc_STRVAR(kqueue_queue_control_doc,
@@ -1646,21 +1646,21 @@ Calls the kernel kevent function.\n\
static PyMethodDef kqueue_queue_methods[] = {
- {"fromfd", (PyCFunction)kqueue_queue_fromfd,
- METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
- {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS,
- kqueue_queue_close_doc},
- {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS,
- kqueue_queue_fileno_doc},
- {"control", (PyCFunction)kqueue_queue_control,
- METH_VARARGS , kqueue_queue_control_doc},
- {NULL, NULL},
+ {"fromfd", (PyCFunction)kqueue_queue_fromfd,
+ METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
+ {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS,
+ kqueue_queue_close_doc},
+ {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS,
+ kqueue_queue_fileno_doc},
+ {"control", (PyCFunction)kqueue_queue_control,
+ METH_VARARGS , kqueue_queue_control_doc},
+ {NULL, NULL},
};
static PyGetSetDef kqueue_queue_getsetlist[] = {
- {"closed", (getter)kqueue_queue_get_closed, NULL,
- "True if the kqueue handler is closed"},
- {0},
+ {"closed", (getter)kqueue_queue_get_closed, NULL,
+ "True if the kqueue handler is closed"},
+ {0},
};
PyDoc_STRVAR(kqueue_queue_doc,
@@ -1679,45 +1679,45 @@ To stop listening:\n\
>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");
static PyTypeObject kqueue_queue_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.kqueue", /* tp_name */
- sizeof(kqueue_queue_Object), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)kqueue_queue_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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, /* tp_flags */
- kqueue_queue_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- kqueue_queue_methods, /* tp_methods */
- 0, /* tp_members */
- kqueue_queue_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- kqueue_queue_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.kqueue", /* tp_name */
+ sizeof(kqueue_queue_Object), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)kqueue_queue_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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, /* tp_flags */
+ kqueue_queue_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ kqueue_queue_methods, /* tp_methods */
+ 0, /* tp_members */
+ kqueue_queue_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ kqueue_queue_new, /* tp_new */
+ 0, /* tp_free */
};
#endif /* HAVE_KQUEUE */
@@ -1748,11 +1748,11 @@ On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\
descriptors can be used.");
static PyMethodDef select_methods[] = {
- {"select", select_select, METH_VARARGS, select_doc},
+ {"select", select_select, METH_VARARGS, select_doc},
#ifdef HAVE_POLL
- {"poll", select_poll, METH_NOARGS, poll_doc},
+ {"poll", select_poll, METH_NOARGS, poll_doc},
#endif /* HAVE_POLL */
- {0, 0}, /* sentinel */
+ {0, 0}, /* sentinel */
};
PyDoc_STRVAR(module_doc,
@@ -1763,167 +1763,167 @@ On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptor
static struct PyModuleDef selectmodule = {
- PyModuleDef_HEAD_INIT,
- "select",
- module_doc,
- -1,
- select_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "select",
+ module_doc,
+ -1,
+ select_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_select(void)
{
- PyObject *m;
- m = PyModule_Create(&selectmodule);
- if (m == NULL)
- return NULL;
+ PyObject *m;
+ m = PyModule_Create(&selectmodule);
+ if (m == NULL)
+ return NULL;
- SelectError = PyErr_NewException("select.error", NULL, NULL);
- Py_INCREF(SelectError);
- PyModule_AddObject(m, "error", SelectError);
+ SelectError = PyErr_NewException("select.error", NULL, NULL);
+ Py_INCREF(SelectError);
+ PyModule_AddObject(m, "error", SelectError);
#ifdef PIPE_BUF
- PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
+ PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
#endif
#if defined(HAVE_POLL)
#ifdef __APPLE__
- if (select_have_broken_poll()) {
- if (PyObject_DelAttrString(m, "poll") == -1) {
- PyErr_Clear();
- }
- } else {
+ if (select_have_broken_poll()) {
+ if (PyObject_DelAttrString(m, "poll") == -1) {
+ PyErr_Clear();
+ }
+ } else {
#else
- {
+ {
#endif
- if (PyType_Ready(&poll_Type) < 0)
- return NULL;
- PyModule_AddIntConstant(m, "POLLIN", POLLIN);
- PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
- PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
- PyModule_AddIntConstant(m, "POLLERR", POLLERR);
- PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
- PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
+ if (PyType_Ready(&poll_Type) < 0)
+ return NULL;
+ PyModule_AddIntConstant(m, "POLLIN", POLLIN);
+ PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
+ PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
+ PyModule_AddIntConstant(m, "POLLERR", POLLERR);
+ PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
+ PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
#ifdef POLLRDNORM
- PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
+ PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
#endif
#ifdef POLLRDBAND
- PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
+ PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
#endif
#ifdef POLLWRNORM
- PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
+ PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
#endif
#ifdef POLLWRBAND
- PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
+ PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
#endif
#ifdef POLLMSG
- PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
+ PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
#endif
- }
+ }
#endif /* HAVE_POLL */
#ifdef HAVE_EPOLL
- Py_TYPE(&pyEpoll_Type) = &PyType_Type;
- if (PyType_Ready(&pyEpoll_Type) < 0)
- return NULL;
-
- Py_INCREF(&pyEpoll_Type);
- PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
-
- PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
- PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
- PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
- PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
- PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
- PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
+ Py_TYPE(&pyEpoll_Type) = &PyType_Type;
+ if (PyType_Ready(&pyEpoll_Type) < 0)
+ return NULL;
+
+ Py_INCREF(&pyEpoll_Type);
+ PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
+
+ PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
+ PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
+ PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
+ PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
+ PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
+ PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
#ifdef EPOLLONESHOT
- /* Kernel 2.6.2+ */
- PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
+ /* Kernel 2.6.2+ */
+ PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
#endif
- /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
- PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
- PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
- PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
- PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
- PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
+ /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
+ PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
+ PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
+ PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
+ PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
+ PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
#endif /* HAVE_EPOLL */
#ifdef HAVE_KQUEUE
- kqueue_event_Type.tp_new = PyType_GenericNew;
- Py_TYPE(&kqueue_event_Type) = &PyType_Type;
- if(PyType_Ready(&kqueue_event_Type) < 0)
- return NULL;
-
- Py_INCREF(&kqueue_event_Type);
- PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
-
- Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
- if(PyType_Ready(&kqueue_queue_Type) < 0)
- return NULL;
- Py_INCREF(&kqueue_queue_Type);
- PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
-
- /* event filters */
- PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
- PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
- PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
- PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
- PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
+ kqueue_event_Type.tp_new = PyType_GenericNew;
+ Py_TYPE(&kqueue_event_Type) = &PyType_Type;
+ if(PyType_Ready(&kqueue_event_Type) < 0)
+ return NULL;
+
+ Py_INCREF(&kqueue_event_Type);
+ PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
+
+ Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
+ if(PyType_Ready(&kqueue_queue_Type) < 0)
+ return NULL;
+ Py_INCREF(&kqueue_queue_Type);
+ PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
+
+ /* event filters */
+ PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
+ PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
+ PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
+ PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
+ PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
#ifdef EVFILT_NETDEV
- PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
+ PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
#endif
- PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
- PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
-
- /* event flags */
- PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
- PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
- PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
- PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
- PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
- PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
-
- PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
- PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
-
- PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
- PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
-
- /* READ WRITE filter flag */
- PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
-
- /* VNODE filter flags */
- PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
- PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
- PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
- PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
- PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
- PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
- PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
-
- /* PROC filter flags */
- PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
- PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
- PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
- PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
- PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
-
- PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
- PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
- PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
-
- /* NETDEV filter flags */
+ PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
+ PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
+
+ /* event flags */
+ PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
+ PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
+ PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
+ PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
+ PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
+ PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
+
+ PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
+ PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
+
+ PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
+ PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
+
+ /* READ WRITE filter flag */
+ PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
+
+ /* VNODE filter flags */
+ PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
+ PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
+ PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
+ PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
+ PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
+
+ /* PROC filter flags */
+ PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
+ PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
+ PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
+
+ PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
+ PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
+
+ /* NETDEV filter flags */
#ifdef EVFILT_NETDEV
- PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
- PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
- PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
#endif
#endif /* HAVE_KQUEUE */
- return m;
+ return m;
}
diff --git a/Modules/sha1module.c b/Modules/sha1module.c
index 3e630eb..b8e8880 100644
--- a/Modules/sha1module.c
+++ b/Modules/sha1module.c
@@ -23,8 +23,8 @@
/* Some useful types */
#if SIZEOF_INT == 4
-typedef unsigned int SHA1_INT32; /* 32-bit integer */
-typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */
+typedef unsigned int SHA1_INT32; /* 32-bit integer */
+typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -122,7 +122,7 @@ static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
/* expand it */
for (i = 16; i < 80; i++) {
- W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
+ W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
}
/* compress */
@@ -131,7 +131,7 @@ static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
#define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
#define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
#define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
-
+
for (i = 0; i < 20; ) {
FF0(a,b,c,d,e,i++);
FF0(e,a,b,c,d,i++);
@@ -141,7 +141,7 @@ static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
}
/* round two */
- for (; i < 40; ) {
+ for (; i < 40; ) {
FF1(a,b,c,d,e,i++);
FF1(e,a,b,c,d,i++);
FF1(d,e,a,b,c,i++);
@@ -150,7 +150,7 @@ static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
}
/* round three */
- for (; i < 60; ) {
+ for (; i < 60; ) {
FF2(a,b,c,d,e,i++);
FF2(e,a,b,c,d,i++);
FF2(d,e,a,b,c,i++);
@@ -159,7 +159,7 @@ static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
}
/* round four */
- for (; i < 80; ) {
+ for (; i < 80; ) {
FF3(a,b,c,d,e,i++);
FF3(e,a,b,c,d,i++);
FF3(d,e,a,b,c,i++);
@@ -362,21 +362,21 @@ SHA1_hexdigest(SHA1object *self, PyObject *unused)
/* Create a new string */
retval = PyUnicode_FromStringAndSize(NULL, SHA1_DIGESTSIZE * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyUnicode_AS_UNICODE(retval);
if (!hex_digest) {
- Py_DECREF(retval);
- return NULL;
+ Py_DECREF(retval);
+ return NULL;
}
/* Make hex version of the digest */
for(i=j=0; i<SHA1_DIGESTSIZE; i++) {
char c;
c = (digest[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = (digest[i] & 0xf);
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
return retval;
@@ -404,11 +404,11 @@ SHA1_update(SHA1object *self, PyObject *args)
}
static PyMethodDef SHA1_methods[] = {
- {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__},
- {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__},
+ {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__},
+ {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__},
{"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__},
- {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -448,13 +448,13 @@ static PyGetSetDef SHA1_getseters[] = {
static PyTypeObject SHA1type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha1.sha1", /*tp_name*/
- sizeof(SHA1object), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha1.sha1", /*tp_name*/
+ sizeof(SHA1object), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA1_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA1_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@@ -470,13 +470,13 @@ static PyTypeObject SHA1type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA1_methods, /* tp_methods */
- NULL, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA1_methods, /* tp_methods */
+ NULL, /* tp_members */
SHA1_getseters, /* tp_getset */
};
@@ -529,7 +529,7 @@ SHA1_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA1_functions[] = {
{"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -539,15 +539,15 @@ static struct PyMethodDef SHA1_functions[] = {
static struct PyModuleDef _sha1module = {
- PyModuleDef_HEAD_INIT,
- "_sha1",
- NULL,
- -1,
- SHA1_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_sha1",
+ NULL,
+ -1,
+ SHA1_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
diff --git a/Modules/sha256module.c b/Modules/sha256module.c
index a9ac748..705b31a 100644
--- a/Modules/sha256module.c
+++ b/Modules/sha256module.c
@@ -23,7 +23,7 @@
/* Endianness testing and definitions */
#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
- if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
+ if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
#define PCT_LITTLE_ENDIAN 1
#define PCT_BIG_ENDIAN 0
@@ -33,7 +33,7 @@
typedef unsigned char SHA_BYTE;
#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
+typedef unsigned int SHA_INT32; /* 32-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -47,11 +47,11 @@ typedef unsigned int SHA_INT32; /* 32-bit integer */
typedef struct {
PyObject_HEAD
- SHA_INT32 digest[8]; /* Message digest */
- SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
- SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
+ SHA_INT32 digest[8]; /* Message digest */
+ SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
+ SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
int Endianness;
- int local; /* unprocessed amount in data */
+ int local; /* unprocessed amount in data */
int digestsize;
} SHAobject;
@@ -63,7 +63,7 @@ static void longReverse(SHA_INT32 *buffer, int byteCount, int Endianness)
SHA_INT32 value;
if ( Endianness == PCT_BIG_ENDIAN )
- return;
+ return;
byteCount /= sizeof(*buffer);
while (byteCount--) {
@@ -115,7 +115,7 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \
((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
-#define Maj(x,y,z) (((x | y) & z) | (x & y))
+#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) ROR((x),(n))
#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
@@ -128,13 +128,13 @@ static void
sha_transform(SHAobject *sha_info)
{
int i;
- SHA_INT32 S[8], W[64], t0, t1;
+ SHA_INT32 S[8], W[64], t0, t1;
memcpy(W, sha_info->data, sizeof(sha_info->data));
longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
for (i = 16; i < 64; ++i) {
- W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
+ W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
}
for (i = 0; i < 8; ++i) {
S[i] = sha_info->digest[i];
@@ -212,8 +212,8 @@ sha_transform(SHAobject *sha_info)
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);
-#undef RND
-
+#undef RND
+
/* feedback */
for (i = 0; i < 8; i++) {
sha_info->digest[i] = sha_info->digest[i] + S[i];
@@ -315,14 +315,14 @@ sha_final(unsigned char digest[SHA_DIGESTSIZE], SHAobject *sha_info)
count = (int) ((lo_bit_count >> 3) & 0x3f);
((SHA_BYTE *) sha_info->data)[count++] = 0x80;
if (count > SHA_BLOCKSIZE - 8) {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - count);
- sha_transform(sha_info);
- memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - count);
+ sha_transform(sha_info);
+ memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
}
else {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - 8 - count);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - 8 - count);
}
/* GJS: note that we add the hi/lo in big-endian. sha_transform will
@@ -455,21 +455,21 @@ SHA256_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyUnicode_AS_UNICODE(retval);
if (!hex_digest) {
- Py_DECREF(retval);
- return NULL;
+ Py_DECREF(retval);
+ return NULL;
}
/* Make hex version of the digest */
for(i=j=0; i<self->digestsize; i++) {
char c;
c = (digest[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = (digest[i] & 0xf);
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
return retval;
@@ -497,11 +497,11 @@ SHA256_update(SHAobject *self, PyObject *args)
}
static PyMethodDef SHA_methods[] = {
- {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__},
- {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__},
+ {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__},
+ {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__},
{"hexdigest", (PyCFunction)SHA256_hexdigest, METH_NOARGS, SHA256_hexdigest__doc__},
- {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -538,13 +538,13 @@ static PyMemberDef SHA_members[] = {
static PyTypeObject SHA224type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha256.sha224", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha256.sha224", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@@ -560,25 +560,25 @@ static PyTypeObject SHA224type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
static PyTypeObject SHA256type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha256.sha256", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha256.sha256", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@@ -594,13 +594,13 @@ static PyTypeObject SHA256type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
@@ -695,7 +695,7 @@ SHA224_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA_functions[] = {
{"sha256", (PyCFunction)SHA256_new, METH_VARARGS|METH_KEYWORDS, SHA256_new__doc__},
{"sha224", (PyCFunction)SHA224_new, METH_VARARGS|METH_KEYWORDS, SHA224_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -705,15 +705,15 @@ static struct PyMethodDef SHA_functions[] = {
static struct PyModuleDef _sha256module = {
- PyModuleDef_HEAD_INIT,
- "_sha256",
- NULL,
- -1,
- SHA_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_sha256",
+ NULL,
+ -1,
+ SHA_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
diff --git a/Modules/sha512module.c b/Modules/sha512module.c
index e29ddec..c403ed6 100644
--- a/Modules/sha512module.c
+++ b/Modules/sha512module.c
@@ -24,7 +24,7 @@
/* Endianness testing and definitions */
#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
- if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
+ if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
#define PCT_LITTLE_ENDIAN 1
#define PCT_BIG_ENDIAN 0
@@ -34,8 +34,8 @@
typedef unsigned char SHA_BYTE;
#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
-typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */
+typedef unsigned int SHA_INT32; /* 32-bit integer */
+typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -49,11 +49,11 @@ typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */
typedef struct {
PyObject_HEAD
- SHA_INT64 digest[8]; /* Message digest */
- SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
- SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
+ SHA_INT64 digest[8]; /* Message digest */
+ SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
+ SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
int Endianness;
- int local; /* unprocessed amount in data */
+ int local; /* unprocessed amount in data */
int digestsize;
} SHAobject;
@@ -65,22 +65,22 @@ static void longReverse(SHA_INT64 *buffer, int byteCount, int Endianness)
SHA_INT64 value;
if ( Endianness == PCT_BIG_ENDIAN )
- return;
+ return;
byteCount /= sizeof(*buffer);
while (byteCount--) {
value = *buffer;
- ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff;
- ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff;
- ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff;
- ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff;
- ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff;
- ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff;
- ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff;
- ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff;
-
- buffer++;
+ ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff;
+ ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff;
+ ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff;
+ ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff;
+ ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff;
+ ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff;
+ ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff;
+ ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff;
+
+ buffer++;
}
}
@@ -125,7 +125,7 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
( ((((x) & Py_ULL(0xFFFFFFFFFFFFFFFF))>>((unsigned PY_LONG_LONG)(y) & 63)) | \
((x)<<((unsigned PY_LONG_LONG)(64-((y) & 63))))) & Py_ULL(0xFFFFFFFFFFFFFFFF))
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
-#define Maj(x,y,z) (((x | y) & z) | (x & y))
+#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) ROR64((x),(n))
#define R(x, n) (((x) & Py_ULL(0xFFFFFFFFFFFFFFFF)) >> ((unsigned PY_LONG_LONG)n))
#define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39))
@@ -144,7 +144,7 @@ sha512_transform(SHAobject *sha_info)
longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
for (i = 16; i < 80; ++i) {
- W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
+ W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
}
for (i = 0; i < 8; ++i) {
S[i] = sha_info->digest[i];
@@ -238,8 +238,8 @@ sha512_transform(SHAobject *sha_info)
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],78,Py_ULL(0x5fcb6fab3ad6faec));
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],79,Py_ULL(0x6c44198c4a475817));
-#undef RND
-
+#undef RND
+
/* feedback */
for (i = 0; i < 8; i++) {
sha_info->digest[i] = sha_info->digest[i] + S[i];
@@ -341,14 +341,14 @@ sha512_final(unsigned char digest[SHA_DIGESTSIZE], SHAobject *sha_info)
count = (int) ((lo_bit_count >> 3) & 0x7f);
((SHA_BYTE *) sha_info->data)[count++] = 0x80;
if (count > SHA_BLOCKSIZE - 16) {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - count);
- sha512_transform(sha_info);
- memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - count);
+ sha512_transform(sha_info);
+ memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16);
}
else {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - 16 - count);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - 16 - count);
}
/* GJS: note that we add the hi/lo in big-endian. sha512_transform will
@@ -521,21 +521,21 @@ SHA512_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyUnicode_AS_UNICODE(retval);
if (!hex_digest) {
- Py_DECREF(retval);
- return NULL;
+ Py_DECREF(retval);
+ return NULL;
}
/* Make hex version of the digest */
for (i=j=0; i<self->digestsize; i++) {
char c;
c = (digest[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = (digest[i] & 0xf);
- c = (c>9) ? c+'a'-10 : c + '0';
+ c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
return retval;
@@ -563,11 +563,11 @@ SHA512_update(SHAobject *self, PyObject *args)
}
static PyMethodDef SHA_methods[] = {
- {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__},
- {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__},
+ {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__},
+ {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__},
{"hexdigest", (PyCFunction)SHA512_hexdigest, METH_NOARGS, SHA512_hexdigest__doc__},
- {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -604,13 +604,13 @@ static PyMemberDef SHA_members[] = {
static PyTypeObject SHA384type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha512.sha384", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha512.sha384", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA512_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA512_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@@ -626,25 +626,25 @@ static PyTypeObject SHA384type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
static PyTypeObject SHA512type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha512.sha512", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha512.sha512", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA512_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA512_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@@ -660,13 +660,13 @@ static PyTypeObject SHA512type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
@@ -761,7 +761,7 @@ SHA384_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA_functions[] = {
{"sha512", (PyCFunction)SHA512_new, METH_VARARGS|METH_KEYWORDS, SHA512_new__doc__},
{"sha384", (PyCFunction)SHA384_new, METH_VARARGS|METH_KEYWORDS, SHA384_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -771,15 +771,15 @@ static struct PyMethodDef SHA_functions[] = {
static struct PyModuleDef _sha512module = {
- PyModuleDef_HEAD_INIT,
- "_sha512",
- NULL,
- -1,
- SHA_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_sha512",
+ NULL,
+ -1,
+ SHA_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c
index 6437cb4..f4fd964 100644
--- a/Modules/signalmodule.c
+++ b/Modules/signalmodule.c
@@ -34,13 +34,13 @@
#ifndef NSIG
# if defined(_NSIG)
-# define NSIG _NSIG /* For BSD/SysV */
+# define NSIG _NSIG /* For BSD/SysV */
# elif defined(_SIGMAX)
-# define NSIG (_SIGMAX + 1) /* For QNX */
+# define NSIG (_SIGMAX + 1) /* For QNX */
# elif defined(SIGMAX)
-# define NSIG (SIGMAX + 1) /* For djgpp */
+# define NSIG (SIGMAX + 1) /* For djgpp */
# else
-# define NSIG 64 /* Use a reasonable default value */
+# define NSIG 64 /* Use a reasonable default value */
# endif
#endif
@@ -82,8 +82,8 @@ static pid_t main_pid;
#endif
static struct {
- int tripped;
- PyObject *func;
+ int tripped;
+ PyObject *func;
} Handlers[NSIG];
static sig_atomic_t wakeup_fd = -1;
@@ -126,18 +126,18 @@ itimer_retval(struct itimerval *iv)
r = PyTuple_New(2);
if (r == NULL)
- return NULL;
+ return NULL;
if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
- Py_DECREF(r);
- return NULL;
+ Py_DECREF(r);
+ return NULL;
}
PyTuple_SET_ITEM(r, 0, v);
if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
- Py_DECREF(r);
- return NULL;
+ Py_DECREF(r);
+ return NULL;
}
PyTuple_SET_ITEM(r, 1, v);
@@ -149,8 +149,8 @@ itimer_retval(struct itimerval *iv)
static PyObject *
signal_default_int_handler(PyObject *self, PyObject *args)
{
- PyErr_SetNone(PyExc_KeyboardInterrupt);
- return NULL;
+ PyErr_SetNone(PyExc_KeyboardInterrupt);
+ return NULL;
}
PyDoc_STRVAR(default_int_handler_doc,
@@ -163,7 +163,7 @@ It raises KeyboardInterrupt.");
static int
checksignals_witharg(void * unused)
{
- return PyErr_CheckSignals();
+ return PyErr_CheckSignals();
}
static void
@@ -171,38 +171,38 @@ signal_handler(int sig_num)
{
#ifdef WITH_THREAD
#ifdef WITH_PTH
- if (PyThread_get_thread_ident() != main_thread) {
- pth_raise(*(pth_t *) main_thread, sig_num);
- return;
- }
-#endif
- /* See NOTES section above */
- if (getpid() == main_pid) {
-#endif
- Handlers[sig_num].tripped = 1;
- /* Set is_tripped after setting .tripped, as it gets
- cleared in PyErr_CheckSignals() before .tripped. */
- is_tripped = 1;
- Py_AddPendingCall(checksignals_witharg, NULL);
- if (wakeup_fd != -1)
- write(wakeup_fd, "\0", 1);
+ if (PyThread_get_thread_ident() != main_thread) {
+ pth_raise(*(pth_t *) main_thread, sig_num);
+ return;
+ }
+#endif
+ /* See NOTES section above */
+ if (getpid() == main_pid) {
+#endif
+ Handlers[sig_num].tripped = 1;
+ /* Set is_tripped after setting .tripped, as it gets
+ cleared in PyErr_CheckSignals() before .tripped. */
+ is_tripped = 1;
+ Py_AddPendingCall(checksignals_witharg, NULL);
+ if (wakeup_fd != -1)
+ write(wakeup_fd, "\0", 1);
#ifdef WITH_THREAD
- }
+ }
#endif
#ifdef SIGCHLD
- if (sig_num == SIGCHLD) {
- /* To avoid infinite recursion, this signal remains
- reset until explicit re-instated.
- Don't clear the 'func' field as it is our pointer
- to the Python handler... */
- return;
- }
+ if (sig_num == SIGCHLD) {
+ /* To avoid infinite recursion, this signal remains
+ reset until explicit re-instated.
+ Don't clear the 'func' field as it is our pointer
+ to the Python handler... */
+ return;
+ }
#endif
#ifndef HAVE_SIGACTION
- /* If the handler was not set up with sigaction, reinstall it. See
- * Python/pythonrun.c for the implementation of PyOS_setsig which
- * makes this true. See also issue8354. */
- PyOS_setsig(sig_num, signal_handler);
+ /* If the handler was not set up with sigaction, reinstall it. See
+ * Python/pythonrun.c for the implementation of PyOS_setsig which
+ * makes this true. See also issue8354. */
+ PyOS_setsig(sig_num, signal_handler);
#endif
}
@@ -211,11 +211,11 @@ signal_handler(int sig_num)
static PyObject *
signal_alarm(PyObject *self, PyObject *args)
{
- int t;
- if (!PyArg_ParseTuple(args, "i:alarm", &t))
- return NULL;
- /* alarm() returns the number of seconds remaining */
- return PyLong_FromLong((long)alarm(t));
+ int t;
+ if (!PyArg_ParseTuple(args, "i:alarm", &t))
+ return NULL;
+ /* alarm() returns the number of seconds remaining */
+ return PyLong_FromLong((long)alarm(t));
}
PyDoc_STRVAR(alarm_doc,
@@ -228,17 +228,17 @@ Arrange for SIGALRM to arrive after the given number of seconds.");
static PyObject *
signal_pause(PyObject *self)
{
- Py_BEGIN_ALLOW_THREADS
- (void)pause();
- Py_END_ALLOW_THREADS
- /* make sure that any exceptions that got raised are propagated
- * back into Python
- */
- if (PyErr_CheckSignals())
- return NULL;
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_BEGIN_ALLOW_THREADS
+ (void)pause();
+ Py_END_ALLOW_THREADS
+ /* make sure that any exceptions that got raised are propagated
+ * back into Python
+ */
+ if (PyErr_CheckSignals())
+ return NULL;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(pause_doc,
"pause()\n\
@@ -251,44 +251,44 @@ Wait until a signal arrives.");
static PyObject *
signal_signal(PyObject *self, PyObject *args)
{
- PyObject *obj;
- int sig_num;
- PyObject *old_handler;
- void (*func)(int);
- if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj))
- return NULL;
+ PyObject *obj;
+ int sig_num;
+ PyObject *old_handler;
+ void (*func)(int);
+ if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj))
+ return NULL;
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread) {
- PyErr_SetString(PyExc_ValueError,
- "signal only works in main thread");
- return NULL;
- }
-#endif
- if (sig_num < 1 || sig_num >= NSIG) {
- PyErr_SetString(PyExc_ValueError,
- "signal number out of range");
- return NULL;
- }
- if (obj == IgnoreHandler)
- func = SIG_IGN;
- else if (obj == DefaultHandler)
- func = SIG_DFL;
- else if (!PyCallable_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
+ if (PyThread_get_thread_ident() != main_thread) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal only works in main thread");
+ return NULL;
+ }
+#endif
+ if (sig_num < 1 || sig_num >= NSIG) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal number out of range");
+ return NULL;
+ }
+ if (obj == IgnoreHandler)
+ func = SIG_IGN;
+ else if (obj == DefaultHandler)
+ func = SIG_DFL;
+ else if (!PyCallable_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
- return NULL;
- }
- else
- func = signal_handler;
- if (PyOS_setsig(sig_num, func) == SIG_ERR) {
- PyErr_SetFromErrno(PyExc_RuntimeError);
- return NULL;
- }
- old_handler = Handlers[sig_num].func;
- Handlers[sig_num].tripped = 0;
- Py_INCREF(obj);
- Handlers[sig_num].func = obj;
- return old_handler;
+ return NULL;
+ }
+ else
+ func = signal_handler;
+ if (PyOS_setsig(sig_num, func) == SIG_ERR) {
+ PyErr_SetFromErrno(PyExc_RuntimeError);
+ return NULL;
+ }
+ old_handler = Handlers[sig_num].func;
+ Handlers[sig_num].tripped = 0;
+ Py_INCREF(obj);
+ Handlers[sig_num].func = obj;
+ return old_handler;
}
PyDoc_STRVAR(signal_doc,
@@ -306,18 +306,18 @@ the first is the signal number, the second is the interrupted stack frame.");
static PyObject *
signal_getsignal(PyObject *self, PyObject *args)
{
- int sig_num;
- PyObject *old_handler;
- if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num))
- return NULL;
- if (sig_num < 1 || sig_num >= NSIG) {
- PyErr_SetString(PyExc_ValueError,
- "signal number out of range");
- return NULL;
- }
- old_handler = Handlers[sig_num].func;
- Py_INCREF(old_handler);
- return old_handler;
+ int sig_num;
+ PyObject *old_handler;
+ if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num))
+ return NULL;
+ if (sig_num < 1 || sig_num >= NSIG) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal number out of range");
+ return NULL;
+ }
+ old_handler = Handlers[sig_num].func;
+ Py_INCREF(old_handler);
+ return old_handler;
}
PyDoc_STRVAR(getsignal_doc,
@@ -339,23 +339,23 @@ will be interrupted.");
static PyObject *
signal_siginterrupt(PyObject *self, PyObject *args)
{
- int sig_num;
- int flag;
-
- if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag))
- return NULL;
- if (sig_num < 1 || sig_num >= NSIG) {
- PyErr_SetString(PyExc_ValueError,
- "signal number out of range");
- return NULL;
- }
- if (siginterrupt(sig_num, flag)<0) {
- PyErr_SetFromErrno(PyExc_RuntimeError);
- return NULL;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ int sig_num;
+ int flag;
+
+ if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag))
+ return NULL;
+ if (sig_num < 1 || sig_num >= NSIG) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal number out of range");
+ return NULL;
+ }
+ if (siginterrupt(sig_num, flag)<0) {
+ PyErr_SetFromErrno(PyExc_RuntimeError);
+ return NULL;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -363,24 +363,24 @@ signal_siginterrupt(PyObject *self, PyObject *args)
static PyObject *
signal_set_wakeup_fd(PyObject *self, PyObject *args)
{
- struct stat buf;
- int fd, old_fd;
- if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd))
- return NULL;
+ struct stat buf;
+ int fd, old_fd;
+ if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd))
+ return NULL;
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread) {
- PyErr_SetString(PyExc_ValueError,
- "set_wakeup_fd only works in main thread");
- return NULL;
- }
-#endif
- if (fd != -1 && fstat(fd, &buf) != 0) {
- PyErr_SetString(PyExc_ValueError, "invalid fd");
- return NULL;
- }
- old_fd = wakeup_fd;
- wakeup_fd = fd;
- return PyLong_FromLong(old_fd);
+ if (PyThread_get_thread_ident() != main_thread) {
+ PyErr_SetString(PyExc_ValueError,
+ "set_wakeup_fd only works in main thread");
+ return NULL;
+ }
+#endif
+ if (fd != -1 && fstat(fd, &buf) != 0) {
+ PyErr_SetString(PyExc_ValueError, "invalid fd");
+ return NULL;
+ }
+ old_fd = wakeup_fd;
+ wakeup_fd = fd;
+ return PyLong_FromLong(old_fd);
}
PyDoc_STRVAR(set_wakeup_fd_doc,
@@ -396,11 +396,11 @@ The fd must be non-blocking.");
int
PySignal_SetWakeupFd(int fd)
{
- int old_fd = wakeup_fd;
- if (fd < 0)
- fd = -1;
- wakeup_fd = fd;
- return old_fd;
+ int old_fd = wakeup_fd;
+ if (fd < 0)
+ fd = -1;
+ wakeup_fd = fd;
+ return old_fd;
}
@@ -414,14 +414,14 @@ signal_setitimer(PyObject *self, PyObject *args)
struct itimerval new, old;
if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval))
- return NULL;
+ return NULL;
timeval_from_double(first, &new.it_value);
timeval_from_double(interval, &new.it_interval);
/* Let OS check "which" value */
if (setitimer(which, &new, &old) != 0) {
- PyErr_SetFromErrno(ItimerError);
- return NULL;
+ PyErr_SetFromErrno(ItimerError);
+ return NULL;
}
return itimer_retval(&old);
@@ -447,11 +447,11 @@ signal_getitimer(PyObject *self, PyObject *args)
struct itimerval old;
if (!PyArg_ParseTuple(args, "i:getitimer", &which))
- return NULL;
+ return NULL;
if (getitimer(which, &old) != 0) {
- PyErr_SetFromErrno(ItimerError);
- return NULL;
+ PyErr_SetFromErrno(ItimerError);
+ return NULL;
}
return itimer_retval(&old);
@@ -467,27 +467,27 @@ Returns current value of given itimer.");
/* List of functions defined in the module */
static PyMethodDef signal_methods[] = {
#ifdef HAVE_ALARM
- {"alarm", signal_alarm, METH_VARARGS, alarm_doc},
+ {"alarm", signal_alarm, METH_VARARGS, alarm_doc},
#endif
#ifdef HAVE_SETITIMER
{"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc},
#endif
#ifdef HAVE_GETITIMER
- {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc},
+ {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc},
#endif
- {"signal", signal_signal, METH_VARARGS, signal_doc},
- {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc},
- {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc},
+ {"signal", signal_signal, METH_VARARGS, signal_doc},
+ {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc},
+ {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc},
#ifdef HAVE_SIGINTERRUPT
- {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc},
+ {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc},
#endif
#ifdef HAVE_PAUSE
- {"pause", (PyCFunction)signal_pause,
- METH_NOARGS,pause_doc},
+ {"pause", (PyCFunction)signal_pause,
+ METH_NOARGS,pause_doc},
#endif
- {"default_int_handler", signal_default_int_handler,
- METH_VARARGS, default_int_handler_doc},
- {NULL, NULL} /* sentinel */
+ {"default_int_handler", signal_default_int_handler,
+ METH_VARARGS, default_int_handler_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -528,264 +528,264 @@ A signal handler function is called with two arguments:\n\
the first is the signal number, the second is the interrupted stack frame.");
static struct PyModuleDef signalmodule = {
- PyModuleDef_HEAD_INIT,
- "signal",
- module_doc,
- -1,
- signal_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "signal",
+ module_doc,
+ -1,
+ signal_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_signal(void)
{
- PyObject *m, *d, *x;
- int i;
+ PyObject *m, *d, *x;
+ int i;
#ifdef WITH_THREAD
- main_thread = PyThread_get_thread_ident();
- main_pid = getpid();
-#endif
-
- /* Create the module and add the functions */
- m = PyModule_Create(&signalmodule);
- if (m == NULL)
- return NULL;
-
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
-
- x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
- if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0)
- goto finally;
-
- x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
- if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0)
- goto finally;
-
- x = PyLong_FromLong((long)NSIG);
- if (!x || PyDict_SetItemString(d, "NSIG", x) < 0)
- goto finally;
- Py_DECREF(x);
-
- x = IntHandler = PyDict_GetItemString(d, "default_int_handler");
- if (!x)
- goto finally;
- Py_INCREF(IntHandler);
-
- Handlers[0].tripped = 0;
- for (i = 1; i < NSIG; i++) {
- void (*t)(int);
- t = PyOS_getsig(i);
- Handlers[i].tripped = 0;
- if (t == SIG_DFL)
- Handlers[i].func = DefaultHandler;
- else if (t == SIG_IGN)
- Handlers[i].func = IgnoreHandler;
- else
- Handlers[i].func = Py_None; /* None of our business */
- Py_INCREF(Handlers[i].func);
- }
- if (Handlers[SIGINT].func == DefaultHandler) {
- /* Install default int handler */
- Py_INCREF(IntHandler);
- Py_DECREF(Handlers[SIGINT].func);
- Handlers[SIGINT].func = IntHandler;
- old_siginthandler = PyOS_setsig(SIGINT, signal_handler);
- }
+ main_thread = PyThread_get_thread_ident();
+ main_pid = getpid();
+#endif
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&signalmodule);
+ if (m == NULL)
+ return NULL;
+
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+
+ x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
+ if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0)
+ goto finally;
+
+ x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
+ if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0)
+ goto finally;
+
+ x = PyLong_FromLong((long)NSIG);
+ if (!x || PyDict_SetItemString(d, "NSIG", x) < 0)
+ goto finally;
+ Py_DECREF(x);
+
+ x = IntHandler = PyDict_GetItemString(d, "default_int_handler");
+ if (!x)
+ goto finally;
+ Py_INCREF(IntHandler);
+
+ Handlers[0].tripped = 0;
+ for (i = 1; i < NSIG; i++) {
+ void (*t)(int);
+ t = PyOS_getsig(i);
+ Handlers[i].tripped = 0;
+ if (t == SIG_DFL)
+ Handlers[i].func = DefaultHandler;
+ else if (t == SIG_IGN)
+ Handlers[i].func = IgnoreHandler;
+ else
+ Handlers[i].func = Py_None; /* None of our business */
+ Py_INCREF(Handlers[i].func);
+ }
+ if (Handlers[SIGINT].func == DefaultHandler) {
+ /* Install default int handler */
+ Py_INCREF(IntHandler);
+ Py_DECREF(Handlers[SIGINT].func);
+ Handlers[SIGINT].func = IntHandler;
+ old_siginthandler = PyOS_setsig(SIGINT, signal_handler);
+ }
#ifdef SIGHUP
- x = PyLong_FromLong(SIGHUP);
- PyDict_SetItemString(d, "SIGHUP", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGHUP);
+ PyDict_SetItemString(d, "SIGHUP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGINT
- x = PyLong_FromLong(SIGINT);
- PyDict_SetItemString(d, "SIGINT", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGINT);
+ PyDict_SetItemString(d, "SIGINT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGBREAK
- x = PyLong_FromLong(SIGBREAK);
- PyDict_SetItemString(d, "SIGBREAK", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGBREAK);
+ PyDict_SetItemString(d, "SIGBREAK", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGQUIT
- x = PyLong_FromLong(SIGQUIT);
- PyDict_SetItemString(d, "SIGQUIT", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGQUIT);
+ PyDict_SetItemString(d, "SIGQUIT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGILL
- x = PyLong_FromLong(SIGILL);
- PyDict_SetItemString(d, "SIGILL", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGILL);
+ PyDict_SetItemString(d, "SIGILL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTRAP
- x = PyLong_FromLong(SIGTRAP);
- PyDict_SetItemString(d, "SIGTRAP", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGTRAP);
+ PyDict_SetItemString(d, "SIGTRAP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGIOT
- x = PyLong_FromLong(SIGIOT);
- PyDict_SetItemString(d, "SIGIOT", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGIOT);
+ PyDict_SetItemString(d, "SIGIOT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGABRT
- x = PyLong_FromLong(SIGABRT);
- PyDict_SetItemString(d, "SIGABRT", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGABRT);
+ PyDict_SetItemString(d, "SIGABRT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGEMT
- x = PyLong_FromLong(SIGEMT);
- PyDict_SetItemString(d, "SIGEMT", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGEMT);
+ PyDict_SetItemString(d, "SIGEMT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGFPE
- x = PyLong_FromLong(SIGFPE);
- PyDict_SetItemString(d, "SIGFPE", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGFPE);
+ PyDict_SetItemString(d, "SIGFPE", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGKILL
- x = PyLong_FromLong(SIGKILL);
- PyDict_SetItemString(d, "SIGKILL", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGKILL);
+ PyDict_SetItemString(d, "SIGKILL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGBUS
- x = PyLong_FromLong(SIGBUS);
- PyDict_SetItemString(d, "SIGBUS", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGBUS);
+ PyDict_SetItemString(d, "SIGBUS", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSEGV
- x = PyLong_FromLong(SIGSEGV);
- PyDict_SetItemString(d, "SIGSEGV", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGSEGV);
+ PyDict_SetItemString(d, "SIGSEGV", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSYS
- x = PyLong_FromLong(SIGSYS);
- PyDict_SetItemString(d, "SIGSYS", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGSYS);
+ PyDict_SetItemString(d, "SIGSYS", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPIPE
- x = PyLong_FromLong(SIGPIPE);
- PyDict_SetItemString(d, "SIGPIPE", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGPIPE);
+ PyDict_SetItemString(d, "SIGPIPE", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGALRM
- x = PyLong_FromLong(SIGALRM);
- PyDict_SetItemString(d, "SIGALRM", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGALRM);
+ PyDict_SetItemString(d, "SIGALRM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTERM
- x = PyLong_FromLong(SIGTERM);
- PyDict_SetItemString(d, "SIGTERM", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGTERM);
+ PyDict_SetItemString(d, "SIGTERM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGUSR1
- x = PyLong_FromLong(SIGUSR1);
- PyDict_SetItemString(d, "SIGUSR1", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGUSR1);
+ PyDict_SetItemString(d, "SIGUSR1", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGUSR2
- x = PyLong_FromLong(SIGUSR2);
- PyDict_SetItemString(d, "SIGUSR2", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGUSR2);
+ PyDict_SetItemString(d, "SIGUSR2", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCLD
- x = PyLong_FromLong(SIGCLD);
- PyDict_SetItemString(d, "SIGCLD", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGCLD);
+ PyDict_SetItemString(d, "SIGCLD", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCHLD
- x = PyLong_FromLong(SIGCHLD);
- PyDict_SetItemString(d, "SIGCHLD", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGCHLD);
+ PyDict_SetItemString(d, "SIGCHLD", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPWR
- x = PyLong_FromLong(SIGPWR);
- PyDict_SetItemString(d, "SIGPWR", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGPWR);
+ PyDict_SetItemString(d, "SIGPWR", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGIO
- x = PyLong_FromLong(SIGIO);
- PyDict_SetItemString(d, "SIGIO", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGIO);
+ PyDict_SetItemString(d, "SIGIO", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGURG
- x = PyLong_FromLong(SIGURG);
- PyDict_SetItemString(d, "SIGURG", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGURG);
+ PyDict_SetItemString(d, "SIGURG", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGWINCH
- x = PyLong_FromLong(SIGWINCH);
- PyDict_SetItemString(d, "SIGWINCH", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGWINCH);
+ PyDict_SetItemString(d, "SIGWINCH", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPOLL
- x = PyLong_FromLong(SIGPOLL);
- PyDict_SetItemString(d, "SIGPOLL", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGPOLL);
+ PyDict_SetItemString(d, "SIGPOLL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSTOP
- x = PyLong_FromLong(SIGSTOP);
- PyDict_SetItemString(d, "SIGSTOP", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGSTOP);
+ PyDict_SetItemString(d, "SIGSTOP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTSTP
- x = PyLong_FromLong(SIGTSTP);
- PyDict_SetItemString(d, "SIGTSTP", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGTSTP);
+ PyDict_SetItemString(d, "SIGTSTP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCONT
- x = PyLong_FromLong(SIGCONT);
- PyDict_SetItemString(d, "SIGCONT", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGCONT);
+ PyDict_SetItemString(d, "SIGCONT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTTIN
- x = PyLong_FromLong(SIGTTIN);
- PyDict_SetItemString(d, "SIGTTIN", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGTTIN);
+ PyDict_SetItemString(d, "SIGTTIN", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTTOU
- x = PyLong_FromLong(SIGTTOU);
- PyDict_SetItemString(d, "SIGTTOU", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGTTOU);
+ PyDict_SetItemString(d, "SIGTTOU", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGVTALRM
- x = PyLong_FromLong(SIGVTALRM);
- PyDict_SetItemString(d, "SIGVTALRM", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGVTALRM);
+ PyDict_SetItemString(d, "SIGVTALRM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPROF
- x = PyLong_FromLong(SIGPROF);
- PyDict_SetItemString(d, "SIGPROF", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGPROF);
+ PyDict_SetItemString(d, "SIGPROF", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGXCPU
- x = PyLong_FromLong(SIGXCPU);
- PyDict_SetItemString(d, "SIGXCPU", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGXCPU);
+ PyDict_SetItemString(d, "SIGXCPU", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGXFSZ
- x = PyLong_FromLong(SIGXFSZ);
- PyDict_SetItemString(d, "SIGXFSZ", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGXFSZ);
+ PyDict_SetItemString(d, "SIGXFSZ", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGRTMIN
- x = PyLong_FromLong(SIGRTMIN);
- PyDict_SetItemString(d, "SIGRTMIN", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGRTMIN);
+ PyDict_SetItemString(d, "SIGRTMIN", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGRTMAX
- x = PyLong_FromLong(SIGRTMAX);
- PyDict_SetItemString(d, "SIGRTMAX", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGRTMAX);
+ PyDict_SetItemString(d, "SIGRTMAX", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGINFO
- x = PyLong_FromLong(SIGINFO);
- PyDict_SetItemString(d, "SIGINFO", x);
- Py_XDECREF(x);
+ x = PyLong_FromLong(SIGINFO);
+ PyDict_SetItemString(d, "SIGINFO", x);
+ Py_XDECREF(x);
#endif
#ifdef ITIMER_REAL
@@ -805,10 +805,10 @@ PyInit_signal(void)
#endif
#if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER)
- ItimerError = PyErr_NewException("signal.ItimerError",
- PyExc_IOError, NULL);
+ ItimerError = PyErr_NewException("signal.ItimerError",
+ PyExc_IOError, NULL);
if (ItimerError != NULL)
- PyDict_SetItemString(d, "ItimerError", ItimerError);
+ PyDict_SetItemString(d, "ItimerError", ItimerError);
#endif
#ifdef CTRL_C_EVENT
@@ -824,8 +824,8 @@ PyInit_signal(void)
#endif
if (PyErr_Occurred()) {
- Py_DECREF(m);
- m = NULL;
+ Py_DECREF(m);
+ m = NULL;
}
finally:
@@ -835,28 +835,28 @@ PyInit_signal(void)
static void
finisignal(void)
{
- int i;
- PyObject *func;
-
- PyOS_setsig(SIGINT, old_siginthandler);
- old_siginthandler = SIG_DFL;
-
- for (i = 1; i < NSIG; i++) {
- func = Handlers[i].func;
- Handlers[i].tripped = 0;
- Handlers[i].func = NULL;
- if (i != SIGINT && func != NULL && func != Py_None &&
- func != DefaultHandler && func != IgnoreHandler)
- PyOS_setsig(i, SIG_DFL);
- Py_XDECREF(func);
- }
-
- Py_XDECREF(IntHandler);
- IntHandler = NULL;
- Py_XDECREF(DefaultHandler);
- DefaultHandler = NULL;
- Py_XDECREF(IgnoreHandler);
- IgnoreHandler = NULL;
+ int i;
+ PyObject *func;
+
+ PyOS_setsig(SIGINT, old_siginthandler);
+ old_siginthandler = SIG_DFL;
+
+ for (i = 1; i < NSIG; i++) {
+ func = Handlers[i].func;
+ Handlers[i].tripped = 0;
+ Handlers[i].func = NULL;
+ if (i != SIGINT && func != NULL && func != Py_None &&
+ func != DefaultHandler && func != IgnoreHandler)
+ PyOS_setsig(i, SIG_DFL);
+ Py_XDECREF(func);
+ }
+
+ Py_XDECREF(IntHandler);
+ IntHandler = NULL;
+ Py_XDECREF(DefaultHandler);
+ DefaultHandler = NULL;
+ Py_XDECREF(IgnoreHandler);
+ IgnoreHandler = NULL;
}
@@ -864,55 +864,55 @@ finisignal(void)
int
PyErr_CheckSignals(void)
{
- int i;
- PyObject *f;
+ int i;
+ PyObject *f;
- if (!is_tripped)
- return 0;
+ if (!is_tripped)
+ return 0;
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread)
- return 0;
-#endif
-
- /*
- * The is_tripped variable is meant to speed up the calls to
- * PyErr_CheckSignals (both directly or via pending calls) when no
- * signal has arrived. This variable is set to 1 when a signal arrives
- * and it is set to 0 here, when we know some signals arrived. This way
- * we can run the registered handlers with no signals blocked.
- *
- * NOTE: with this approach we can have a situation where is_tripped is
- * 1 but we have no more signals to handle (Handlers[i].tripped
- * is 0 for every signal i). This won't do us any harm (except
- * we're gonna spent some cycles for nothing). This happens when
- * we receive a signal i after we zero is_tripped and before we
- * check Handlers[i].tripped.
- */
- is_tripped = 0;
-
- if (!(f = (PyObject *)PyEval_GetFrame()))
- f = Py_None;
-
- for (i = 1; i < NSIG; i++) {
- if (Handlers[i].tripped) {
- PyObject *result = NULL;
- PyObject *arglist = Py_BuildValue("(iO)", i, f);
- Handlers[i].tripped = 0;
-
- if (arglist) {
- result = PyEval_CallObject(Handlers[i].func,
- arglist);
- Py_DECREF(arglist);
- }
- if (!result)
- return -1;
-
- Py_DECREF(result);
- }
- }
-
- return 0;
+ if (PyThread_get_thread_ident() != main_thread)
+ return 0;
+#endif
+
+ /*
+ * The is_tripped variable is meant to speed up the calls to
+ * PyErr_CheckSignals (both directly or via pending calls) when no
+ * signal has arrived. This variable is set to 1 when a signal arrives
+ * and it is set to 0 here, when we know some signals arrived. This way
+ * we can run the registered handlers with no signals blocked.
+ *
+ * NOTE: with this approach we can have a situation where is_tripped is
+ * 1 but we have no more signals to handle (Handlers[i].tripped
+ * is 0 for every signal i). This won't do us any harm (except
+ * we're gonna spent some cycles for nothing). This happens when
+ * we receive a signal i after we zero is_tripped and before we
+ * check Handlers[i].tripped.
+ */
+ is_tripped = 0;
+
+ if (!(f = (PyObject *)PyEval_GetFrame()))
+ f = Py_None;
+
+ for (i = 1; i < NSIG; i++) {
+ if (Handlers[i].tripped) {
+ PyObject *result = NULL;
+ PyObject *arglist = Py_BuildValue("(iO)", i, f);
+ Handlers[i].tripped = 0;
+
+ if (arglist) {
+ result = PyEval_CallObject(Handlers[i].func,
+ arglist);
+ Py_DECREF(arglist);
+ }
+ if (!result)
+ return -1;
+
+ Py_DECREF(result);
+ }
+ }
+
+ return 0;
}
@@ -922,49 +922,49 @@ PyErr_CheckSignals(void)
void
PyErr_SetInterrupt(void)
{
- is_tripped = 1;
- Handlers[SIGINT].tripped = 1;
- Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL);
+ is_tripped = 1;
+ Handlers[SIGINT].tripped = 1;
+ Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL);
}
void
PyOS_InitInterrupts(void)
{
- PyObject *m = PyInit_signal();
- if (m) {
- _PyImport_FixupExtension(m, "signal", "signal");
- Py_DECREF(m);
- }
+ PyObject *m = PyInit_signal();
+ if (m) {
+ _PyImport_FixupExtension(m, "signal", "signal");
+ Py_DECREF(m);
+ }
}
void
PyOS_FiniInterrupts(void)
{
- finisignal();
+ finisignal();
}
int
PyOS_InterruptOccurred(void)
{
- if (Handlers[SIGINT].tripped) {
+ if (Handlers[SIGINT].tripped) {
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread)
- return 0;
+ if (PyThread_get_thread_ident() != main_thread)
+ return 0;
#endif
- Handlers[SIGINT].tripped = 0;
- return 1;
- }
- return 0;
+ Handlers[SIGINT].tripped = 0;
+ return 1;
+ }
+ return 0;
}
void
PyOS_AfterFork(void)
{
#ifdef WITH_THREAD
- PyEval_ReInitThreads();
- main_thread = PyThread_get_thread_ident();
- main_pid = getpid();
- _PyImport_ReInitLock();
- PyThread_ReInitTLS();
+ PyEval_ReInitThreads();
+ main_thread = PyThread_get_thread_ident();
+ main_pid = getpid();
+ _PyImport_ReInitLock();
+ PyThread_ReInitTLS();
#endif
}
diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c
index 085d585..563bdea 100644
--- a/Modules/socketmodule.c
+++ b/Modules/socketmodule.c
@@ -17,9 +17,9 @@ Module interface:
- socket.error: exception raised for socket specific errors
- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
- a subclass of socket.error
+ a subclass of socket.error
- socket.herror: exception raised for gethostby* errors,
- a subclass of socket.error
+ a subclass of socket.error
- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
@@ -27,14 +27,14 @@ Module interface:
- socket.getservbyname(servicename[, protocolname]) --> port number
- socket.getservbyport(portnumber[, protocolname]) --> service name
- socket.socket([family[, type [, proto, fileno]]]) --> new socket object
- (fileno specifies a pre-existing socket file descriptor)
+ (fileno specifies a pre-existing socket file descriptor)
- socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
- socket.ntohs(16 bit value) --> new int object
- socket.ntohl(32 bit value) --> new int object
- socket.htons(16 bit value) --> new int object
- socket.htonl(32 bit value) --> new int object
- socket.getaddrinfo(host, port [, family, socktype, proto, flags])
- --> List of (family, socktype, proto, canonname, sockaddr)
+ --> List of (family, socktype, proto, canonname, sockaddr)
- socket.getnameinfo(sockaddr, flags) --> (host, port)
- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
- socket.has_ipv6: boolean value indicating if IPv6 is supported
@@ -54,22 +54,22 @@ Module interface:
specify packet-type and ha-type/addr.
- an AF_TIPC socket address is expressed as
(addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
- TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
+ TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
and scope can be one of:
- TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
+ TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
The meaning of v1, v2 and v3 depends on the value of addr_type:
- if addr_type is TIPC_ADDR_NAME:
- v1 is the server type
- v2 is the port identifier
- v3 is ignored
- if addr_type is TIPC_ADDR_NAMESEQ:
- v1 is the server type
- v2 is the lower port number
- v3 is the upper port number
- if addr_type is TIPC_ADDR_ID:
- v1 is the node
- v2 is the ref
- v3 is ignored
+ if addr_type is TIPC_ADDR_NAME:
+ v1 is the server type
+ v2 is the port identifier
+ v3 is ignored
+ if addr_type is TIPC_ADDR_NAMESEQ:
+ v1 is the server type
+ v2 is the lower port number
+ v3 is the upper port number
+ if addr_type is TIPC_ADDR_ID:
+ v1 is the node
+ v2 is the ref
+ v3 is ignored
Local naming conventions:
@@ -283,7 +283,7 @@ typedef size_t socklen_t;
#include <stddef.h>
#ifndef offsetof
-# define offsetof(type, member) ((size_t)(&((type *)0)->member))
+# define offsetof(type, member) ((size_t)(&((type *)0)->member))
#endif
#ifndef O_NONBLOCK
@@ -351,16 +351,16 @@ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
static SOCKET
dup_socket(SOCKET handle)
{
- HANDLE newhandle;
-
- if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle,
- GetCurrentProcess(), &newhandle,
- 0, FALSE, DUPLICATE_SAME_ACCESS))
- {
- WSASetLastError(GetLastError());
- return INVALID_SOCKET;
- }
- return (SOCKET)newhandle;
+ HANDLE newhandle;
+
+ if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle,
+ GetCurrentProcess(), &newhandle,
+ 0, FALSE, DUPLICATE_SAME_ACCESS))
+ {
+ WSASetLastError(GetLastError());
+ return INVALID_SOCKET;
+ }
+ return (SOCKET)newhandle;
}
#define SOCKETCLOSE closesocket
#else
@@ -418,7 +418,7 @@ dup_socket(SOCKET handle)
#define SEGMENT_SIZE (32 * 1024 -1)
#endif
-#define SAS2SA(x) ((struct sockaddr *)(x))
+#define SAS2SA(x) ((struct sockaddr *)(x))
/*
* Constants for getnameinfo()
@@ -473,8 +473,8 @@ static PyTypeObject sock_type;
static PyObject*
select_error(void)
{
- PyErr_SetString(socket_error, "unable to select on socket");
- return NULL;
+ PyErr_SetString(socket_error, "unable to select on socket");
+ return NULL;
}
/* Convenience function to raise an error according to errno
@@ -484,95 +484,95 @@ static PyObject *
set_error(void)
{
#ifdef MS_WINDOWS
- int err_no = WSAGetLastError();
- /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
- recognizes the error codes used by both GetLastError() and
- WSAGetLastError */
- if (err_no)
- return PyErr_SetExcFromWindowsErr(socket_error, err_no);
+ int err_no = WSAGetLastError();
+ /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
+ recognizes the error codes used by both GetLastError() and
+ WSAGetLastError */
+ if (err_no)
+ return PyErr_SetExcFromWindowsErr(socket_error, err_no);
#endif
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
- if (sock_errno() != NO_ERROR) {
- APIRET rc;
- ULONG msglen;
- char outbuf[100];
- int myerrorcode = sock_errno();
-
- /* Retrieve socket-related error message from MPTN.MSG file */
- rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
- myerrorcode - SOCBASEERR + 26,
- "mptn.msg",
- &msglen);
- if (rc == NO_ERROR) {
- PyObject *v;
-
- /* OS/2 doesn't guarantee a terminator */
- outbuf[msglen] = '\0';
- if (strlen(outbuf) > 0) {
- /* If non-empty msg, trim CRLF */
- char *lastc = &outbuf[ strlen(outbuf)-1 ];
- while (lastc > outbuf &&
- isspace(Py_CHARMASK(*lastc))) {
- /* Trim trailing whitespace (CRLF) */
- *lastc-- = '\0';
- }
- }
- v = Py_BuildValue("(is)", myerrorcode, outbuf);
- if (v != NULL) {
- PyErr_SetObject(socket_error, v);
- Py_DECREF(v);
- }
- return NULL;
- }
- }
-#endif
-
- return PyErr_SetFromErrno(socket_error);
+ if (sock_errno() != NO_ERROR) {
+ APIRET rc;
+ ULONG msglen;
+ char outbuf[100];
+ int myerrorcode = sock_errno();
+
+ /* Retrieve socket-related error message from MPTN.MSG file */
+ rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
+ myerrorcode - SOCBASEERR + 26,
+ "mptn.msg",
+ &msglen);
+ if (rc == NO_ERROR) {
+ PyObject *v;
+
+ /* OS/2 doesn't guarantee a terminator */
+ outbuf[msglen] = '\0';
+ if (strlen(outbuf) > 0) {
+ /* If non-empty msg, trim CRLF */
+ char *lastc = &outbuf[ strlen(outbuf)-1 ];
+ while (lastc > outbuf &&
+ isspace(Py_CHARMASK(*lastc))) {
+ /* Trim trailing whitespace (CRLF) */
+ *lastc-- = '\0';
+ }
+ }
+ v = Py_BuildValue("(is)", myerrorcode, outbuf);
+ if (v != NULL) {
+ PyErr_SetObject(socket_error, v);
+ Py_DECREF(v);
+ }
+ return NULL;
+ }
+ }
+#endif
+
+ return PyErr_SetFromErrno(socket_error);
}
static PyObject *
set_herror(int h_error)
{
- PyObject *v;
+ PyObject *v;
#ifdef HAVE_HSTRERROR
- v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
+ v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
#else
- v = Py_BuildValue("(is)", h_error, "host not found");
+ v = Py_BuildValue("(is)", h_error, "host not found");
#endif
- if (v != NULL) {
- PyErr_SetObject(socket_herror, v);
- Py_DECREF(v);
- }
+ if (v != NULL) {
+ PyErr_SetObject(socket_herror, v);
+ Py_DECREF(v);
+ }
- return NULL;
+ return NULL;
}
static PyObject *
set_gaierror(int error)
{
- PyObject *v;
+ PyObject *v;
#ifdef EAI_SYSTEM
- /* EAI_SYSTEM is not available on Windows XP. */
- if (error == EAI_SYSTEM)
- return set_error();
+ /* EAI_SYSTEM is not available on Windows XP. */
+ if (error == EAI_SYSTEM)
+ return set_error();
#endif
#ifdef HAVE_GAI_STRERROR
- v = Py_BuildValue("(is)", error, gai_strerror(error));
+ v = Py_BuildValue("(is)", error, gai_strerror(error));
#else
- v = Py_BuildValue("(is)", error, "getaddrinfo failed");
+ v = Py_BuildValue("(is)", error, "getaddrinfo failed");
#endif
- if (v != NULL) {
- PyErr_SetObject(socket_gaierror, v);
- Py_DECREF(v);
- }
+ if (v != NULL) {
+ PyErr_SetObject(socket_gaierror, v);
+ Py_DECREF(v);
+ }
- return NULL;
+ return NULL;
}
#ifdef __VMS
@@ -580,22 +580,22 @@ set_gaierror(int error)
static int
sendsegmented(int sock_fd, char *buf, int len, int flags)
{
- int n = 0;
- int remaining = len;
-
- while (remaining > 0) {
- unsigned int segment;
-
- segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
- n = send(sock_fd, buf, segment, flags);
- if (n < 0) {
- return n;
- }
- remaining -= segment;
- buf += segment;
- } /* end while */
-
- return len;
+ int n = 0;
+ int remaining = len;
+
+ while (remaining > 0) {
+ unsigned int segment;
+
+ segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
+ n = send(sock_fd, buf, segment, flags);
+ if (n < 0) {
+ return n;
+ }
+ remaining -= segment;
+ buf += segment;
+ } /* end while */
+
+ return len;
}
#endif
@@ -605,33 +605,33 @@ static int
internal_setblocking(PySocketSockObject *s, int block)
{
#ifndef MS_WINDOWS
- int delay_flag;
+ int delay_flag;
#endif
- Py_BEGIN_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
#ifndef MS_WINDOWS
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
- block = !block;
- ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
+ block = !block;
+ ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
#elif defined(__VMS)
- block = !block;
- ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
+ block = !block;
+ ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
#else /* !PYOS_OS2 && !__VMS */
- delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
- if (block)
- delay_flag &= (~O_NONBLOCK);
- else
- delay_flag |= O_NONBLOCK;
- fcntl(s->sock_fd, F_SETFL, delay_flag);
+ delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
+ if (block)
+ delay_flag &= (~O_NONBLOCK);
+ else
+ delay_flag |= O_NONBLOCK;
+ fcntl(s->sock_fd, F_SETFL, delay_flag);
#endif /* !PYOS_OS2 */
#else /* MS_WINDOWS */
- block = !block;
- ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
+ block = !block;
+ ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
#endif /* MS_WINDOWS */
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
- /* Since these don't return anything */
- return 1;
+ /* Since these don't return anything */
+ return 1;
}
/* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
@@ -642,53 +642,53 @@ internal_setblocking(PySocketSockObject *s, int block)
static int
internal_select(PySocketSockObject *s, int writing)
{
- int n;
+ int n;
- /* Nothing to do unless we're in timeout mode (not non-blocking) */
- if (s->sock_timeout <= 0.0)
- return 0;
+ /* Nothing to do unless we're in timeout mode (not non-blocking) */
+ if (s->sock_timeout <= 0.0)
+ return 0;
- /* Guard against closed socket */
- if (s->sock_fd < 0)
- return 0;
+ /* Guard against closed socket */
+ if (s->sock_fd < 0)
+ return 0;
- /* Prefer poll, if available, since you can poll() any fd
- * which can't be done with select(). */
+ /* Prefer poll, if available, since you can poll() any fd
+ * which can't be done with select(). */
#ifdef HAVE_POLL
- {
- struct pollfd pollfd;
- int timeout;
+ {
+ struct pollfd pollfd;
+ int timeout;
- pollfd.fd = s->sock_fd;
- pollfd.events = writing ? POLLOUT : POLLIN;
+ pollfd.fd = s->sock_fd;
+ pollfd.events = writing ? POLLOUT : POLLIN;
- /* s->sock_timeout is in seconds, timeout in ms */
- timeout = (int)(s->sock_timeout * 1000 + 0.5);
- n = poll(&pollfd, 1, timeout);
- }
+ /* s->sock_timeout is in seconds, timeout in ms */
+ timeout = (int)(s->sock_timeout * 1000 + 0.5);
+ n = poll(&pollfd, 1, timeout);
+ }
#else
- {
- /* Construct the arguments to select */
- fd_set fds;
- struct timeval tv;
- tv.tv_sec = (int)s->sock_timeout;
- tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
- FD_ZERO(&fds);
- FD_SET(s->sock_fd, &fds);
-
- /* See if the socket is ready */
- if (writing)
- n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
- else
- n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
- }
-#endif
-
- if (n < 0)
- return -1;
- if (n == 0)
- return 1;
- return 0;
+ {
+ /* Construct the arguments to select */
+ fd_set fds;
+ struct timeval tv;
+ tv.tv_sec = (int)s->sock_timeout;
+ tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
+ FD_ZERO(&fds);
+ FD_SET(s->sock_fd, &fds);
+
+ /* See if the socket is ready */
+ if (writing)
+ n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
+ else
+ n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
+ }
+#endif
+
+ if (n < 0)
+ return -1;
+ if (n == 0)
+ return 1;
+ return 0;
}
/* Initialize a new socket object. */
@@ -697,18 +697,18 @@ static double defaulttimeout = -1.0; /* Default timeout for new sockets */
static void
init_sockobject(PySocketSockObject *s,
- SOCKET_T fd, int family, int type, int proto)
+ SOCKET_T fd, int family, int type, int proto)
{
- s->sock_fd = fd;
- s->sock_family = family;
- s->sock_type = type;
- s->sock_proto = proto;
- s->sock_timeout = defaulttimeout;
+ s->sock_fd = fd;
+ s->sock_family = family;
+ s->sock_type = type;
+ s->sock_proto = proto;
+ s->sock_timeout = defaulttimeout;
- s->errorhandler = &set_error;
+ s->errorhandler = &set_error;
- if (defaulttimeout >= 0.0)
- internal_setblocking(s, 0);
+ if (defaulttimeout >= 0.0)
+ internal_setblocking(s, 0);
}
@@ -721,12 +721,12 @@ init_sockobject(PySocketSockObject *s,
static PySocketSockObject *
new_sockobject(SOCKET_T fd, int family, int type, int proto)
{
- PySocketSockObject *s;
- s = (PySocketSockObject *)
- PyType_GenericNew(&sock_type, NULL, NULL);
- if (s != NULL)
- init_sockobject(s, fd, family, type, proto);
- return s;
+ PySocketSockObject *s;
+ s = (PySocketSockObject *)
+ PyType_GenericNew(&sock_type, NULL, NULL);
+ if (s != NULL)
+ init_sockobject(s, fd, family, type, proto);
+ return s;
}
@@ -746,122 +746,122 @@ PyThread_type_lock netdb_lock;
static int
setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
{
- struct addrinfo hints, *res;
- int error;
- int d1, d2, d3, d4;
- char ch;
-
- memset((void *) addr_ret, '\0', sizeof(*addr_ret));
- if (name[0] == '\0') {
- int siz;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
- hints.ai_socktype = SOCK_DGRAM; /*dummy*/
- hints.ai_flags = AI_PASSIVE;
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(NULL, "0", &hints, &res);
- Py_END_ALLOW_THREADS
- /* We assume that those thread-unsafe getaddrinfo() versions
- *are* safe regarding their return value, ie. that a
- subsequent call to getaddrinfo() does not destroy the
- outcome of the first call. */
- RELEASE_GETADDRINFO_LOCK
- if (error) {
- set_gaierror(error);
- return -1;
- }
- switch (res->ai_family) {
- case AF_INET:
- siz = 4;
- break;
+ struct addrinfo hints, *res;
+ int error;
+ int d1, d2, d3, d4;
+ char ch;
+
+ memset((void *) addr_ret, '\0', sizeof(*addr_ret));
+ if (name[0] == '\0') {
+ int siz;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = af;
+ hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+ hints.ai_flags = AI_PASSIVE;
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(NULL, "0", &hints, &res);
+ Py_END_ALLOW_THREADS
+ /* We assume that those thread-unsafe getaddrinfo() versions
+ *are* safe regarding their return value, ie. that a
+ subsequent call to getaddrinfo() does not destroy the
+ outcome of the first call. */
+ RELEASE_GETADDRINFO_LOCK
+ if (error) {
+ set_gaierror(error);
+ return -1;
+ }
+ switch (res->ai_family) {
+ case AF_INET:
+ siz = 4;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- siz = 16;
- break;
-#endif
- default:
- freeaddrinfo(res);
- PyErr_SetString(socket_error,
- "unsupported address family");
- return -1;
- }
- if (res->ai_next) {
- freeaddrinfo(res);
- PyErr_SetString(socket_error,
- "wildcard resolved to multiple address");
- return -1;
- }
- if (res->ai_addrlen < addr_ret_size)
- addr_ret_size = res->ai_addrlen;
- memcpy(addr_ret, res->ai_addr, addr_ret_size);
- freeaddrinfo(res);
- return siz;
- }
- if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
- struct sockaddr_in *sin;
- if (af != AF_INET && af != AF_UNSPEC) {
- PyErr_SetString(socket_error,
- "address family mismatched");
- return -1;
- }
- sin = (struct sockaddr_in *)addr_ret;
- memset((void *) sin, '\0', sizeof(*sin));
- sin->sin_family = AF_INET;
+ case AF_INET6:
+ siz = 16;
+ break;
+#endif
+ default:
+ freeaddrinfo(res);
+ PyErr_SetString(socket_error,
+ "unsupported address family");
+ return -1;
+ }
+ if (res->ai_next) {
+ freeaddrinfo(res);
+ PyErr_SetString(socket_error,
+ "wildcard resolved to multiple address");
+ return -1;
+ }
+ if (res->ai_addrlen < addr_ret_size)
+ addr_ret_size = res->ai_addrlen;
+ memcpy(addr_ret, res->ai_addr, addr_ret_size);
+ freeaddrinfo(res);
+ return siz;
+ }
+ if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
+ struct sockaddr_in *sin;
+ if (af != AF_INET && af != AF_UNSPEC) {
+ PyErr_SetString(socket_error,
+ "address family mismatched");
+ return -1;
+ }
+ sin = (struct sockaddr_in *)addr_ret;
+ memset((void *) sin, '\0', sizeof(*sin));
+ sin->sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin->sin_len = sizeof(*sin);
-#endif
- sin->sin_addr.s_addr = INADDR_BROADCAST;
- return sizeof(sin->sin_addr);
- }
- if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
- 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
- 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
- struct sockaddr_in *sin;
- sin = (struct sockaddr_in *)addr_ret;
- sin->sin_addr.s_addr = htonl(
- ((long) d1 << 24) | ((long) d2 << 16) |
- ((long) d3 << 8) | ((long) d4 << 0));
- sin->sin_family = AF_INET;
+ sin->sin_len = sizeof(*sin);
+#endif
+ sin->sin_addr.s_addr = INADDR_BROADCAST;
+ return sizeof(sin->sin_addr);
+ }
+ if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
+ 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
+ 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
+ struct sockaddr_in *sin;
+ sin = (struct sockaddr_in *)addr_ret;
+ sin->sin_addr.s_addr = htonl(
+ ((long) d1 << 24) | ((long) d2 << 16) |
+ ((long) d3 << 8) | ((long) d4 << 0));
+ sin->sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin->sin_len = sizeof(*sin);
-#endif
- return 4;
- }
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(name, NULL, &hints, &res);
+ sin->sin_len = sizeof(*sin);
+#endif
+ return 4;
+ }
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = af;
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(name, NULL, &hints, &res);
#if defined(__digital__) && defined(__unix__)
- if (error == EAI_NONAME && af == AF_UNSPEC) {
- /* On Tru64 V5.1, numeric-to-addr conversion fails
- if no address family is given. Assume IPv4 for now.*/
- hints.ai_family = AF_INET;
- error = getaddrinfo(name, NULL, &hints, &res);
- }
-#endif
- Py_END_ALLOW_THREADS
- RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
- if (error) {
- set_gaierror(error);
- return -1;
- }
- if (res->ai_addrlen < addr_ret_size)
- addr_ret_size = res->ai_addrlen;
- memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
- freeaddrinfo(res);
- switch (addr_ret->sa_family) {
- case AF_INET:
- return 4;
+ if (error == EAI_NONAME && af == AF_UNSPEC) {
+ /* On Tru64 V5.1, numeric-to-addr conversion fails
+ if no address family is given. Assume IPv4 for now.*/
+ hints.ai_family = AF_INET;
+ error = getaddrinfo(name, NULL, &hints, &res);
+ }
+#endif
+ Py_END_ALLOW_THREADS
+ RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
+ if (error) {
+ set_gaierror(error);
+ return -1;
+ }
+ if (res->ai_addrlen < addr_ret_size)
+ addr_ret_size = res->ai_addrlen;
+ memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
+ freeaddrinfo(res);
+ switch (addr_ret->sa_family) {
+ case AF_INET:
+ return 4;
#ifdef ENABLE_IPV6
- case AF_INET6:
- return 16;
+ case AF_INET6:
+ return 16;
#endif
- default:
- PyErr_SetString(socket_error, "unknown address family");
- return -1;
- }
+ default:
+ PyErr_SetString(socket_error, "unknown address family");
+ return -1;
+ }
}
@@ -872,16 +872,16 @@ setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
static PyObject *
makeipaddr(struct sockaddr *addr, int addrlen)
{
- char buf[NI_MAXHOST];
- int error;
-
- error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
- NI_NUMERICHOST);
- if (error) {
- set_gaierror(error);
- return NULL;
- }
- return PyUnicode_FromString(buf);
+ char buf[NI_MAXHOST];
+ int error;
+
+ error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
+ NI_NUMERICHOST);
+ if (error) {
+ set_gaierror(error);
+ return NULL;
+ }
+ return PyUnicode_FromString(buf);
}
@@ -893,24 +893,24 @@ makeipaddr(struct sockaddr *addr, int addrlen)
static int
setbdaddr(char *name, bdaddr_t *bdaddr)
{
- unsigned int b0, b1, b2, b3, b4, b5;
- char ch;
- int n;
-
- n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
- &b5, &b4, &b3, &b2, &b1, &b0, &ch);
- if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
- bdaddr->b[0] = b0;
- bdaddr->b[1] = b1;
- bdaddr->b[2] = b2;
- bdaddr->b[3] = b3;
- bdaddr->b[4] = b4;
- bdaddr->b[5] = b5;
- return 6;
- } else {
- PyErr_SetString(socket_error, "bad bluetooth address");
- return -1;
- }
+ unsigned int b0, b1, b2, b3, b4, b5;
+ char ch;
+ int n;
+
+ n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
+ &b5, &b4, &b3, &b2, &b1, &b0, &ch);
+ if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
+ bdaddr->b[0] = b0;
+ bdaddr->b[1] = b1;
+ bdaddr->b[2] = b2;
+ bdaddr->b[3] = b3;
+ bdaddr->b[4] = b4;
+ bdaddr->b[5] = b5;
+ return 6;
+ } else {
+ PyErr_SetString(socket_error, "bad bluetooth address");
+ return -1;
+ }
}
/* Create a string representation of the Bluetooth address. This is always a
@@ -920,12 +920,12 @@ setbdaddr(char *name, bdaddr_t *bdaddr)
static PyObject *
makebdaddr(bdaddr_t *bdaddr)
{
- char buf[(6 * 2) + 5 + 1];
+ char buf[(6 * 2) + 5 + 1];
- sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
- bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
- bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
- return PyUnicode_FromString(buf);
+ sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
+ bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
+ bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
+ return PyUnicode_FromString(buf);
}
#endif
@@ -939,193 +939,193 @@ makebdaddr(bdaddr_t *bdaddr)
static PyObject *
makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
{
- if (addrlen == 0) {
- /* No address -- may be recvfrom() from known socket */
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- switch (addr->sa_family) {
-
- case AF_INET:
- {
- struct sockaddr_in *a;
- PyObject *addrobj = makeipaddr(addr, sizeof(*a));
- PyObject *ret = NULL;
- if (addrobj) {
- a = (struct sockaddr_in *)addr;
- ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
- Py_DECREF(addrobj);
- }
- return ret;
- }
+ if (addrlen == 0) {
+ /* No address -- may be recvfrom() from known socket */
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ switch (addr->sa_family) {
+
+ case AF_INET:
+ {
+ struct sockaddr_in *a;
+ PyObject *addrobj = makeipaddr(addr, sizeof(*a));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ a = (struct sockaddr_in *)addr;
+ ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
#if defined(AF_UNIX)
- case AF_UNIX:
- {
- struct sockaddr_un *a = (struct sockaddr_un *) addr;
+ case AF_UNIX:
+ {
+ struct sockaddr_un *a = (struct sockaddr_un *) addr;
#ifdef linux
- if (a->sun_path[0] == 0) { /* Linux abstract namespace */
- addrlen -= offsetof(struct sockaddr_un, sun_path);
- return PyBytes_FromStringAndSize(a->sun_path, addrlen);
- }
- else
+ if (a->sun_path[0] == 0) { /* Linux abstract namespace */
+ addrlen -= offsetof(struct sockaddr_un, sun_path);
+ return PyBytes_FromStringAndSize(a->sun_path, addrlen);
+ }
+ else
#endif /* linux */
- {
- /* regular NULL-terminated string */
- return PyUnicode_FromString(a->sun_path);
- }
- }
+ {
+ /* regular NULL-terminated string */
+ return PyUnicode_FromString(a->sun_path);
+ }
+ }
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
case AF_NETLINK:
{
- struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
- return Py_BuildValue("II", a->nl_pid, a->nl_groups);
+ struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
+ return Py_BuildValue("II", a->nl_pid, a->nl_groups);
}
#endif /* AF_NETLINK */
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6 *a;
- PyObject *addrobj = makeipaddr(addr, sizeof(*a));
- PyObject *ret = NULL;
- if (addrobj) {
- a = (struct sockaddr_in6 *)addr;
- ret = Py_BuildValue("Oiii",
- addrobj,
- ntohs(a->sin6_port),
- a->sin6_flowinfo,
- a->sin6_scope_id);
- Py_DECREF(addrobj);
- }
- return ret;
- }
+ case AF_INET6:
+ {
+ struct sockaddr_in6 *a;
+ PyObject *addrobj = makeipaddr(addr, sizeof(*a));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ a = (struct sockaddr_in6 *)addr;
+ ret = Py_BuildValue("Oiii",
+ addrobj,
+ ntohs(a->sin6_port),
+ a->sin6_flowinfo,
+ a->sin6_scope_id);
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
#endif
#ifdef USE_BLUETOOTH
- case AF_BLUETOOTH:
- switch (proto) {
-
- case BTPROTO_L2CAP:
- {
- struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
- PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
- PyObject *ret = NULL;
- if (addrobj) {
- ret = Py_BuildValue("Oi",
- addrobj,
- _BT_L2_MEMB(a, psm));
- Py_DECREF(addrobj);
- }
- return ret;
- }
-
- case BTPROTO_RFCOMM:
- {
- struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
- PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
- PyObject *ret = NULL;
- if (addrobj) {
- ret = Py_BuildValue("Oi",
- addrobj,
- _BT_RC_MEMB(a, channel));
- Py_DECREF(addrobj);
- }
- return ret;
- }
-
- case BTPROTO_HCI:
- {
- struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
- PyObject *ret = NULL;
- ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
- return ret;
- }
+ case AF_BLUETOOTH:
+ switch (proto) {
+
+ case BTPROTO_L2CAP:
+ {
+ struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
+ PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ ret = Py_BuildValue("Oi",
+ addrobj,
+ _BT_L2_MEMB(a, psm));
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
+
+ case BTPROTO_RFCOMM:
+ {
+ struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
+ PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ ret = Py_BuildValue("Oi",
+ addrobj,
+ _BT_RC_MEMB(a, channel));
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
+
+ case BTPROTO_HCI:
+ {
+ struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
+ PyObject *ret = NULL;
+ ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
+ return ret;
+ }
#if !defined(__FreeBSD__)
- case BTPROTO_SCO:
- {
- struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
- return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
- }
+ case BTPROTO_SCO:
+ {
+ struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
+ return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
+ }
#endif
- default:
- PyErr_SetString(PyExc_ValueError,
- "Unknown Bluetooth protocol");
- return NULL;
- }
+ default:
+ PyErr_SetString(PyExc_ValueError,
+ "Unknown Bluetooth protocol");
+ return NULL;
+ }
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- case AF_PACKET:
- {
- struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
- char *ifname = "";
- struct ifreq ifr;
- /* need to look up interface name give index */
- if (a->sll_ifindex) {
- ifr.ifr_ifindex = a->sll_ifindex;
- if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
- ifname = ifr.ifr_name;
- }
- return Py_BuildValue("shbhy#",
- ifname,
- ntohs(a->sll_protocol),
- a->sll_pkttype,
- a->sll_hatype,
- a->sll_addr,
- a->sll_halen);
- }
+ case AF_PACKET:
+ {
+ struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
+ char *ifname = "";
+ struct ifreq ifr;
+ /* need to look up interface name give index */
+ if (a->sll_ifindex) {
+ ifr.ifr_ifindex = a->sll_ifindex;
+ if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
+ ifname = ifr.ifr_name;
+ }
+ return Py_BuildValue("shbhy#",
+ ifname,
+ ntohs(a->sll_protocol),
+ a->sll_pkttype,
+ a->sll_hatype,
+ a->sll_addr,
+ a->sll_halen);
+ }
#endif
#ifdef HAVE_LINUX_TIPC_H
- case AF_TIPC:
- {
- struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
- if (a->addrtype == TIPC_ADDR_NAMESEQ) {
- return Py_BuildValue("IIIII",
- a->addrtype,
- a->addr.nameseq.type,
- a->addr.nameseq.lower,
- a->addr.nameseq.upper,
- a->scope);
- } else if (a->addrtype == TIPC_ADDR_NAME) {
- return Py_BuildValue("IIIII",
- a->addrtype,
- a->addr.name.name.type,
- a->addr.name.name.instance,
- a->addr.name.name.instance,
- a->scope);
- } else if (a->addrtype == TIPC_ADDR_ID) {
- return Py_BuildValue("IIIII",
- a->addrtype,
- a->addr.id.node,
- a->addr.id.ref,
- 0,
- a->scope);
- } else {
- PyErr_SetString(PyExc_ValueError,
- "Invalid address type");
- return NULL;
- }
- }
-#endif
-
- /* More cases here... */
-
- default:
- /* If we don't know the address family, don't raise an
- exception -- return it as an (int, bytes) tuple. */
- return Py_BuildValue("iy#",
- addr->sa_family,
- addr->sa_data,
- sizeof(addr->sa_data));
-
- }
+ case AF_TIPC:
+ {
+ struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
+ if (a->addrtype == TIPC_ADDR_NAMESEQ) {
+ return Py_BuildValue("IIIII",
+ a->addrtype,
+ a->addr.nameseq.type,
+ a->addr.nameseq.lower,
+ a->addr.nameseq.upper,
+ a->scope);
+ } else if (a->addrtype == TIPC_ADDR_NAME) {
+ return Py_BuildValue("IIIII",
+ a->addrtype,
+ a->addr.name.name.type,
+ a->addr.name.name.instance,
+ a->addr.name.name.instance,
+ a->scope);
+ } else if (a->addrtype == TIPC_ADDR_ID) {
+ return Py_BuildValue("IIIII",
+ a->addrtype,
+ a->addr.id.node,
+ a->addr.id.ref,
+ 0,
+ a->scope);
+ } else {
+ PyErr_SetString(PyExc_ValueError,
+ "Invalid address type");
+ return NULL;
+ }
+ }
+#endif
+
+ /* More cases here... */
+
+ default:
+ /* If we don't know the address family, don't raise an
+ exception -- return it as an (int, bytes) tuple. */
+ return Py_BuildValue("iy#",
+ addr->sa_family,
+ addr->sa_data,
+ sizeof(addr->sa_data));
+
+ }
}
@@ -1136,346 +1136,346 @@ makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
static int
getsockaddrarg(PySocketSockObject *s, PyObject *args,
- struct sockaddr *addr_ret, int *len_ret)
+ struct sockaddr *addr_ret, int *len_ret)
{
- switch (s->sock_family) {
+ switch (s->sock_family) {
#if defined(AF_UNIX)
- case AF_UNIX:
- {
- struct sockaddr_un* addr;
- char *path;
- int len;
- if (!PyArg_Parse(args, "s#", &path, &len))
- return 0;
-
- addr = (struct sockaddr_un*)addr_ret;
+ case AF_UNIX:
+ {
+ struct sockaddr_un* addr;
+ char *path;
+ int len;
+ if (!PyArg_Parse(args, "s#", &path, &len))
+ return 0;
+
+ addr = (struct sockaddr_un*)addr_ret;
#ifdef linux
- if (len > 0 && path[0] == 0) {
- /* Linux abstract namespace extension */
- if (len > sizeof addr->sun_path) {
- PyErr_SetString(socket_error,
- "AF_UNIX path too long");
- return 0;
- }
- }
- else
+ if (len > 0 && path[0] == 0) {
+ /* Linux abstract namespace extension */
+ if (len > sizeof addr->sun_path) {
+ PyErr_SetString(socket_error,
+ "AF_UNIX path too long");
+ return 0;
+ }
+ }
+ else
#endif /* linux */
- {
- /* regular NULL-terminated string */
- if (len >= sizeof addr->sun_path) {
- PyErr_SetString(socket_error,
- "AF_UNIX path too long");
- return 0;
- }
- addr->sun_path[len] = 0;
- }
- addr->sun_family = s->sock_family;
- memcpy(addr->sun_path, path, len);
+ {
+ /* regular NULL-terminated string */
+ if (len >= sizeof addr->sun_path) {
+ PyErr_SetString(socket_error,
+ "AF_UNIX path too long");
+ return 0;
+ }
+ addr->sun_path[len] = 0;
+ }
+ addr->sun_family = s->sock_family;
+ memcpy(addr->sun_path, path, len);
#if defined(PYOS_OS2)
- *len_ret = sizeof(*addr);
+ *len_ret = sizeof(*addr);
#else
- *len_ret = len + offsetof(struct sockaddr_un, sun_path);
+ *len_ret = len + offsetof(struct sockaddr_un, sun_path);
#endif
- return 1;
- }
+ return 1;
+ }
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
- case AF_NETLINK:
- {
- struct sockaddr_nl* addr;
- int pid, groups;
- addr = (struct sockaddr_nl *)addr_ret;
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_NETLINK address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
- return 0;
- addr->nl_family = AF_NETLINK;
- addr->nl_pid = pid;
- addr->nl_groups = groups;
- *len_ret = sizeof(*addr);
- return 1;
- }
-#endif
-
- case AF_INET:
- {
- struct sockaddr_in* addr;
- char *host;
- int port, result;
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_INET address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
- "idna", &host, &port))
- return 0;
- addr=(struct sockaddr_in*)addr_ret;
- result = setipaddr(host, (struct sockaddr *)addr,
- sizeof(*addr), AF_INET);
- PyMem_Free(host);
- if (result < 0)
- return 0;
- if (port < 0 || port > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getsockaddrarg: port must be 0-65535.");
- return 0;
- }
- addr->sin_family = AF_INET;
- addr->sin_port = htons((short)port);
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_NETLINK:
+ {
+ struct sockaddr_nl* addr;
+ int pid, groups;
+ addr = (struct sockaddr_nl *)addr_ret;
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_NETLINK address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
+ return 0;
+ addr->nl_family = AF_NETLINK;
+ addr->nl_pid = pid;
+ addr->nl_groups = groups;
+ *len_ret = sizeof(*addr);
+ return 1;
+ }
+#endif
+
+ case AF_INET:
+ {
+ struct sockaddr_in* addr;
+ char *host;
+ int port, result;
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_INET address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
+ "idna", &host, &port))
+ return 0;
+ addr=(struct sockaddr_in*)addr_ret;
+ result = setipaddr(host, (struct sockaddr *)addr,
+ sizeof(*addr), AF_INET);
+ PyMem_Free(host);
+ if (result < 0)
+ return 0;
+ if (port < 0 || port > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getsockaddrarg: port must be 0-65535.");
+ return 0;
+ }
+ addr->sin_family = AF_INET;
+ addr->sin_port = htons((short)port);
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6* addr;
- char *host;
- int port, flowinfo, scope_id, result;
- flowinfo = scope_id = 0;
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_INET6 address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "eti|ii",
- "idna", &host, &port, &flowinfo,
- &scope_id)) {
- return 0;
- }
- addr = (struct sockaddr_in6*)addr_ret;
- result = setipaddr(host, (struct sockaddr *)addr,
- sizeof(*addr), AF_INET6);
- PyMem_Free(host);
- if (result < 0)
- return 0;
- if (port < 0 || port > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getsockaddrarg: port must be 0-65535.");
- return 0;
- }
- addr->sin6_family = s->sock_family;
- addr->sin6_port = htons((short)port);
- addr->sin6_flowinfo = flowinfo;
- addr->sin6_scope_id = scope_id;
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_INET6:
+ {
+ struct sockaddr_in6* addr;
+ char *host;
+ int port, flowinfo, scope_id, result;
+ flowinfo = scope_id = 0;
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_INET6 address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "eti|ii",
+ "idna", &host, &port, &flowinfo,
+ &scope_id)) {
+ return 0;
+ }
+ addr = (struct sockaddr_in6*)addr_ret;
+ result = setipaddr(host, (struct sockaddr *)addr,
+ sizeof(*addr), AF_INET6);
+ PyMem_Free(host);
+ if (result < 0)
+ return 0;
+ if (port < 0 || port > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getsockaddrarg: port must be 0-65535.");
+ return 0;
+ }
+ addr->sin6_family = s->sock_family;
+ addr->sin6_port = htons((short)port);
+ addr->sin6_flowinfo = flowinfo;
+ addr->sin6_scope_id = scope_id;
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#endif
#ifdef USE_BLUETOOTH
- case AF_BLUETOOTH:
- {
- switch (s->sock_proto) {
- case BTPROTO_L2CAP:
- {
- struct sockaddr_l2 *addr;
- char *straddr;
-
- addr = (struct sockaddr_l2 *)addr_ret;
- memset(addr, 0, sizeof(struct sockaddr_l2));
- _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyArg_ParseTuple(args, "si", &straddr,
- &_BT_L2_MEMB(addr, psm))) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
- return 0;
-
- *len_ret = sizeof *addr;
- return 1;
- }
- case BTPROTO_RFCOMM:
- {
- struct sockaddr_rc *addr;
- char *straddr;
-
- addr = (struct sockaddr_rc *)addr_ret;
- _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyArg_ParseTuple(args, "si", &straddr,
- &_BT_RC_MEMB(addr, channel))) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
- return 0;
-
- *len_ret = sizeof *addr;
- return 1;
- }
- case BTPROTO_HCI:
- {
- struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
- _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_BLUETOOTH:
+ {
+ switch (s->sock_proto) {
+ case BTPROTO_L2CAP:
+ {
+ struct sockaddr_l2 *addr;
+ char *straddr;
+
+ addr = (struct sockaddr_l2 *)addr_ret;
+ memset(addr, 0, sizeof(struct sockaddr_l2));
+ _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "si", &straddr,
+ &_BT_L2_MEMB(addr, psm))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
+ return 0;
+
+ *len_ret = sizeof *addr;
+ return 1;
+ }
+ case BTPROTO_RFCOMM:
+ {
+ struct sockaddr_rc *addr;
+ char *straddr;
+
+ addr = (struct sockaddr_rc *)addr_ret;
+ _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "si", &straddr,
+ &_BT_RC_MEMB(addr, channel))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
+ return 0;
+
+ *len_ret = sizeof *addr;
+ return 1;
+ }
+ case BTPROTO_HCI:
+ {
+ struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
+ _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#if !defined(__FreeBSD__)
- case BTPROTO_SCO:
- {
- struct sockaddr_sco *addr;
- char *straddr;
-
- addr = (struct sockaddr_sco *)addr_ret;
- _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyBytes_Check(args)) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- straddr = PyBytes_AS_STRING(args);
- if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
- return 0;
-
- *len_ret = sizeof *addr;
- return 1;
- }
-#endif
- default:
- PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
- return 0;
- }
- }
+ case BTPROTO_SCO:
+ {
+ struct sockaddr_sco *addr;
+ char *straddr;
+
+ addr = (struct sockaddr_sco *)addr_ret;
+ _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyBytes_Check(args)) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ straddr = PyBytes_AS_STRING(args);
+ if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
+ return 0;
+
+ *len_ret = sizeof *addr;
+ return 1;
+ }
+#endif
+ default:
+ PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
+ return 0;
+ }
+ }
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- case AF_PACKET:
- {
- struct sockaddr_ll* addr;
- struct ifreq ifr;
- char *interfaceName;
- int protoNumber;
- int hatype = 0;
- int pkttype = 0;
- char *haddr = NULL;
- unsigned int halen = 0;
-
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_PACKET address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName,
- &protoNumber, &pkttype, &hatype,
- &haddr, &halen))
- return 0;
- strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
- ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
- if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
- s->errorhandler();
- return 0;
- }
- if (halen > 8) {
- PyErr_SetString(PyExc_ValueError,
- "Hardware address must be 8 bytes or less");
- return 0;
- }
- if (protoNumber < 0 || protoNumber > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getsockaddrarg: protoNumber must be 0-65535.");
- return 0;
- }
- addr = (struct sockaddr_ll*)addr_ret;
- addr->sll_family = AF_PACKET;
- addr->sll_protocol = htons((short)protoNumber);
- addr->sll_ifindex = ifr.ifr_ifindex;
- addr->sll_pkttype = pkttype;
- addr->sll_hatype = hatype;
- if (halen != 0) {
- memcpy(&addr->sll_addr, haddr, halen);
- }
- addr->sll_halen = halen;
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_PACKET:
+ {
+ struct sockaddr_ll* addr;
+ struct ifreq ifr;
+ char *interfaceName;
+ int protoNumber;
+ int hatype = 0;
+ int pkttype = 0;
+ char *haddr = NULL;
+ unsigned int halen = 0;
+
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_PACKET address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName,
+ &protoNumber, &pkttype, &hatype,
+ &haddr, &halen))
+ return 0;
+ strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
+ ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
+ if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
+ s->errorhandler();
+ return 0;
+ }
+ if (halen > 8) {
+ PyErr_SetString(PyExc_ValueError,
+ "Hardware address must be 8 bytes or less");
+ return 0;
+ }
+ if (protoNumber < 0 || protoNumber > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getsockaddrarg: protoNumber must be 0-65535.");
+ return 0;
+ }
+ addr = (struct sockaddr_ll*)addr_ret;
+ addr->sll_family = AF_PACKET;
+ addr->sll_protocol = htons((short)protoNumber);
+ addr->sll_ifindex = ifr.ifr_ifindex;
+ addr->sll_pkttype = pkttype;
+ addr->sll_hatype = hatype;
+ if (halen != 0) {
+ memcpy(&addr->sll_addr, haddr, halen);
+ }
+ addr->sll_halen = halen;
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#endif
#ifdef HAVE_LINUX_TIPC_H
- case AF_TIPC:
- {
- unsigned int atype, v1, v2, v3;
- unsigned int scope = TIPC_CLUSTER_SCOPE;
- struct sockaddr_tipc *addr;
-
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_TIPC address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
-
- if (!PyArg_ParseTuple(args,
- "IIII|I;Invalid TIPC address format",
- &atype, &v1, &v2, &v3, &scope))
- return 0;
-
- addr = (struct sockaddr_tipc *) addr_ret;
- memset(addr, 0, sizeof(struct sockaddr_tipc));
-
- addr->family = AF_TIPC;
- addr->scope = scope;
- addr->addrtype = atype;
-
- if (atype == TIPC_ADDR_NAMESEQ) {
- addr->addr.nameseq.type = v1;
- addr->addr.nameseq.lower = v2;
- addr->addr.nameseq.upper = v3;
- } else if (atype == TIPC_ADDR_NAME) {
- addr->addr.name.name.type = v1;
- addr->addr.name.name.instance = v2;
- } else if (atype == TIPC_ADDR_ID) {
- addr->addr.id.node = v1;
- addr->addr.id.ref = v2;
- } else {
- /* Shouldn't happen */
- PyErr_SetString(PyExc_TypeError, "Invalid address type");
- return 0;
- }
-
- *len_ret = sizeof(*addr);
-
- return 1;
- }
-#endif
-
- /* More cases here... */
-
- default:
- PyErr_SetString(socket_error, "getsockaddrarg: bad family");
- return 0;
-
- }
+ case AF_TIPC:
+ {
+ unsigned int atype, v1, v2, v3;
+ unsigned int scope = TIPC_CLUSTER_SCOPE;
+ struct sockaddr_tipc *addr;
+
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_TIPC address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+
+ if (!PyArg_ParseTuple(args,
+ "IIII|I;Invalid TIPC address format",
+ &atype, &v1, &v2, &v3, &scope))
+ return 0;
+
+ addr = (struct sockaddr_tipc *) addr_ret;
+ memset(addr, 0, sizeof(struct sockaddr_tipc));
+
+ addr->family = AF_TIPC;
+ addr->scope = scope;
+ addr->addrtype = atype;
+
+ if (atype == TIPC_ADDR_NAMESEQ) {
+ addr->addr.nameseq.type = v1;
+ addr->addr.nameseq.lower = v2;
+ addr->addr.nameseq.upper = v3;
+ } else if (atype == TIPC_ADDR_NAME) {
+ addr->addr.name.name.type = v1;
+ addr->addr.name.name.instance = v2;
+ } else if (atype == TIPC_ADDR_ID) {
+ addr->addr.id.node = v1;
+ addr->addr.id.ref = v2;
+ } else {
+ /* Shouldn't happen */
+ PyErr_SetString(PyExc_TypeError, "Invalid address type");
+ return 0;
+ }
+
+ *len_ret = sizeof(*addr);
+
+ return 1;
+ }
+#endif
+
+ /* More cases here... */
+
+ default:
+ PyErr_SetString(socket_error, "getsockaddrarg: bad family");
+ return 0;
+
+ }
}
@@ -1486,89 +1486,89 @@ getsockaddrarg(PySocketSockObject *s, PyObject *args,
static int
getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
{
- switch (s->sock_family) {
+ switch (s->sock_family) {
#if defined(AF_UNIX)
- case AF_UNIX:
- {
- *len_ret = sizeof (struct sockaddr_un);
- return 1;
- }
+ case AF_UNIX:
+ {
+ *len_ret = sizeof (struct sockaddr_un);
+ return 1;
+ }
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
case AF_NETLINK:
{
- *len_ret = sizeof (struct sockaddr_nl);
- return 1;
+ *len_ret = sizeof (struct sockaddr_nl);
+ return 1;
}
#endif
- case AF_INET:
- {
- *len_ret = sizeof (struct sockaddr_in);
- return 1;
- }
+ case AF_INET:
+ {
+ *len_ret = sizeof (struct sockaddr_in);
+ return 1;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- *len_ret = sizeof (struct sockaddr_in6);
- return 1;
- }
+ case AF_INET6:
+ {
+ *len_ret = sizeof (struct sockaddr_in6);
+ return 1;
+ }
#endif
#ifdef USE_BLUETOOTH
- case AF_BLUETOOTH:
- {
- switch(s->sock_proto)
- {
-
- case BTPROTO_L2CAP:
- *len_ret = sizeof (struct sockaddr_l2);
- return 1;
- case BTPROTO_RFCOMM:
- *len_ret = sizeof (struct sockaddr_rc);
- return 1;
- case BTPROTO_HCI:
- *len_ret = sizeof (struct sockaddr_hci);
- return 1;
+ case AF_BLUETOOTH:
+ {
+ switch(s->sock_proto)
+ {
+
+ case BTPROTO_L2CAP:
+ *len_ret = sizeof (struct sockaddr_l2);
+ return 1;
+ case BTPROTO_RFCOMM:
+ *len_ret = sizeof (struct sockaddr_rc);
+ return 1;
+ case BTPROTO_HCI:
+ *len_ret = sizeof (struct sockaddr_hci);
+ return 1;
#if !defined(__FreeBSD__)
- case BTPROTO_SCO:
- *len_ret = sizeof (struct sockaddr_sco);
- return 1;
+ case BTPROTO_SCO:
+ *len_ret = sizeof (struct sockaddr_sco);
+ return 1;
#endif
- default:
- PyErr_SetString(socket_error, "getsockaddrlen: "
- "unknown BT protocol");
- return 0;
+ default:
+ PyErr_SetString(socket_error, "getsockaddrlen: "
+ "unknown BT protocol");
+ return 0;
- }
- }
+ }
+ }
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- case AF_PACKET:
- {
- *len_ret = sizeof (struct sockaddr_ll);
- return 1;
- }
+ case AF_PACKET:
+ {
+ *len_ret = sizeof (struct sockaddr_ll);
+ return 1;
+ }
#endif
#ifdef HAVE_LINUX_TIPC_H
- case AF_TIPC:
- {
- *len_ret = sizeof (struct sockaddr_tipc);
- return 1;
- }
+ case AF_TIPC:
+ {
+ *len_ret = sizeof (struct sockaddr_tipc);
+ return 1;
+ }
#endif
- /* More cases here... */
+ /* More cases here... */
- default:
- PyErr_SetString(socket_error, "getsockaddrlen: bad family");
- return 0;
+ default:
+ PyErr_SetString(socket_error, "getsockaddrlen: bad family");
+ return 0;
- }
+ }
}
@@ -1577,52 +1577,52 @@ getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
static PyObject *
sock_accept(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- SOCKET_T newfd = INVALID_SOCKET;
- socklen_t addrlen;
- PyObject *sock = NULL;
- PyObject *addr = NULL;
- PyObject *res = NULL;
- int timeout;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
-
- if (!IS_SELECTABLE(s))
- return select_error();
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 0);
- if (!timeout)
- newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
-
- if (newfd == INVALID_SOCKET)
- return s->errorhandler();
-
- sock = PyLong_FromSocket_t(newfd);
- if (sock == NULL) {
- SOCKETCLOSE(newfd);
- goto finally;
- }
-
- addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
- addrlen, s->sock_proto);
- if (addr == NULL)
- goto finally;
-
- res = PyTuple_Pack(2, sock, addr);
+ sock_addr_t addrbuf;
+ SOCKET_T newfd = INVALID_SOCKET;
+ socklen_t addrlen;
+ PyObject *sock = NULL;
+ PyObject *addr = NULL;
+ PyObject *res = NULL;
+ int timeout;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
+
+ if (!IS_SELECTABLE(s))
+ return select_error();
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 0);
+ if (!timeout)
+ newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+
+ if (newfd == INVALID_SOCKET)
+ return s->errorhandler();
+
+ sock = PyLong_FromSocket_t(newfd);
+ if (sock == NULL) {
+ SOCKETCLOSE(newfd);
+ goto finally;
+ }
+
+ addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
+ addrlen, s->sock_proto);
+ if (addr == NULL)
+ goto finally;
+
+ res = PyTuple_Pack(2, sock, addr);
finally:
- Py_XDECREF(sock);
- Py_XDECREF(addr);
- return res;
+ Py_XDECREF(sock);
+ Py_XDECREF(addr);
+ return res;
}
PyDoc_STRVAR(accept_doc,
@@ -1640,17 +1640,17 @@ For IP sockets, the address info is a pair (hostaddr, port).");
static PyObject *
sock_setblocking(PySocketSockObject *s, PyObject *arg)
{
- int block;
+ int block;
- block = PyLong_AsLong(arg);
- if (block == -1 && PyErr_Occurred())
- return NULL;
+ block = PyLong_AsLong(arg);
+ if (block == -1 && PyErr_Occurred())
+ return NULL;
- s->sock_timeout = block ? -1.0 : 0.0;
- internal_setblocking(s, block);
+ s->sock_timeout = block ? -1.0 : 0.0;
+ internal_setblocking(s, block);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setblocking_doc,
@@ -1669,25 +1669,25 @@ setblocking(False) is equivalent to settimeout(0.0).");
static PyObject *
sock_settimeout(PySocketSockObject *s, PyObject *arg)
{
- double timeout;
-
- if (arg == Py_None)
- timeout = -1.0;
- else {
- timeout = PyFloat_AsDouble(arg);
- if (timeout < 0.0) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_ValueError,
- "Timeout value out of range");
- return NULL;
- }
- }
-
- s->sock_timeout = timeout;
- internal_setblocking(s, timeout < 0.0);
-
- Py_INCREF(Py_None);
- return Py_None;
+ double timeout;
+
+ if (arg == Py_None)
+ timeout = -1.0;
+ else {
+ timeout = PyFloat_AsDouble(arg);
+ if (timeout < 0.0) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_ValueError,
+ "Timeout value out of range");
+ return NULL;
+ }
+ }
+
+ s->sock_timeout = timeout;
+ internal_setblocking(s, timeout < 0.0);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(settimeout_doc,
@@ -1703,12 +1703,12 @@ Setting a timeout of zero is the same as setblocking(0).");
static PyObject *
sock_gettimeout(PySocketSockObject *s)
{
- if (s->sock_timeout < 0.0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyFloat_FromDouble(s->sock_timeout);
+ if (s->sock_timeout < 0.0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyFloat_FromDouble(s->sock_timeout);
}
PyDoc_STRVAR(gettimeout_doc,
@@ -1726,29 +1726,29 @@ operations are disabled.");
static PyObject *
sock_setsockopt(PySocketSockObject *s, PyObject *args)
{
- int level;
- int optname;
- int res;
- char *buf;
- int buflen;
- int flag;
-
- if (PyArg_ParseTuple(args, "iii:setsockopt",
- &level, &optname, &flag)) {
- buf = (char *) &flag;
- buflen = sizeof flag;
- }
- else {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "iiy#:setsockopt",
- &level, &optname, &buf, &buflen))
- return NULL;
- }
- res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ int level;
+ int optname;
+ int res;
+ char *buf;
+ int buflen;
+ int flag;
+
+ if (PyArg_ParseTuple(args, "iii:setsockopt",
+ &level, &optname, &flag)) {
+ buf = (char *) &flag;
+ buflen = sizeof flag;
+ }
+ else {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "iiy#:setsockopt",
+ &level, &optname, &buf, &buflen))
+ return NULL;
+ }
+ res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setsockopt_doc,
@@ -1766,47 +1766,47 @@ The value argument can either be an integer or a string.");
static PyObject *
sock_getsockopt(PySocketSockObject *s, PyObject *args)
{
- int level;
- int optname;
- int res;
- PyObject *buf;
- socklen_t buflen = 0;
-
- if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
- &level, &optname, &buflen))
- return NULL;
-
- if (buflen == 0) {
- int flag = 0;
- socklen_t flagsize = sizeof flag;
- res = getsockopt(s->sock_fd, level, optname,
- (void *)&flag, &flagsize);
- if (res < 0)
- return s->errorhandler();
- return PyLong_FromLong(flag);
- }
+ int level;
+ int optname;
+ int res;
+ PyObject *buf;
+ socklen_t buflen = 0;
+
+ if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
+ &level, &optname, &buflen))
+ return NULL;
+
+ if (buflen == 0) {
+ int flag = 0;
+ socklen_t flagsize = sizeof flag;
+ res = getsockopt(s->sock_fd, level, optname,
+ (void *)&flag, &flagsize);
+ if (res < 0)
+ return s->errorhandler();
+ return PyLong_FromLong(flag);
+ }
#ifdef __VMS
- /* socklen_t is unsigned so no negative test is needed,
- test buflen == 0 is previously done */
- if (buflen > 1024) {
+ /* socklen_t is unsigned so no negative test is needed,
+ test buflen == 0 is previously done */
+ if (buflen > 1024) {
#else
- if (buflen <= 0 || buflen > 1024) {
-#endif
- PyErr_SetString(socket_error,
- "getsockopt buflen out of range");
- return NULL;
- }
- buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
- if (buf == NULL)
- return NULL;
- res = getsockopt(s->sock_fd, level, optname,
- (void *)PyBytes_AS_STRING(buf), &buflen);
- if (res < 0) {
- Py_DECREF(buf);
- return s->errorhandler();
- }
- _PyBytes_Resize(&buf, buflen);
- return buf;
+ if (buflen <= 0 || buflen > 1024) {
+#endif
+ PyErr_SetString(socket_error,
+ "getsockopt buflen out of range");
+ return NULL;
+ }
+ buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
+ if (buf == NULL)
+ return NULL;
+ res = getsockopt(s->sock_fd, level, optname,
+ (void *)PyBytes_AS_STRING(buf), &buflen);
+ if (res < 0) {
+ Py_DECREF(buf);
+ return s->errorhandler();
+ }
+ _PyBytes_Resize(&buf, buflen);
+ return buf;
}
PyDoc_STRVAR(getsockopt_doc,
@@ -1822,19 +1822,19 @@ string of that length; otherwise it is an integer.");
static PyObject *
sock_bind(PySocketSockObject *s, PyObject *addro)
{
- sock_addr_t addrbuf;
- int addrlen;
- int res;
-
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ sock_addr_t addrbuf;
+ int addrlen;
+ int res;
+
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(bind_doc,
@@ -1852,16 +1852,16 @@ sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
static PyObject *
sock_close(PySocketSockObject *s)
{
- SOCKET_T fd;
-
- if ((fd = s->sock_fd) != -1) {
- s->sock_fd = -1;
- Py_BEGIN_ALLOW_THREADS
- (void) SOCKETCLOSE(fd);
- Py_END_ALLOW_THREADS
- }
- Py_INCREF(Py_None);
- return Py_None;
+ SOCKET_T fd;
+
+ if ((fd = s->sock_fd) != -1) {
+ s->sock_fd = -1;
+ Py_BEGIN_ALLOW_THREADS
+ (void) SOCKETCLOSE(fd);
+ Py_END_ALLOW_THREADS
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(close_doc,
@@ -1871,90 +1871,90 @@ Close the socket. It cannot be used after this call.");
static int
internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
- int *timeoutp)
+ int *timeoutp)
{
- int res, timeout;
+ int res, timeout;
- timeout = 0;
- res = connect(s->sock_fd, addr, addrlen);
+ timeout = 0;
+ res = connect(s->sock_fd, addr, addrlen);
#ifdef MS_WINDOWS
- if (s->sock_timeout > 0.0) {
- if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
- IS_SELECTABLE(s)) {
- /* This is a mess. Best solution: trust select */
- fd_set fds;
- fd_set fds_exc;
- struct timeval tv;
- tv.tv_sec = (int)s->sock_timeout;
- tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
- FD_ZERO(&fds);
- FD_SET(s->sock_fd, &fds);
- FD_ZERO(&fds_exc);
- FD_SET(s->sock_fd, &fds_exc);
- res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
- if (res == 0) {
- res = WSAEWOULDBLOCK;
- timeout = 1;
- } else if (res > 0) {
- if (FD_ISSET(s->sock_fd, &fds))
- /* The socket is in the writable set - this
- means connected */
- res = 0;
- else {
- /* As per MS docs, we need to call getsockopt()
- to get the underlying error */
- int res_size = sizeof res;
- /* It must be in the exception set */
- assert(FD_ISSET(s->sock_fd, &fds_exc));
- if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
- (char *)&res, &res_size))
- /* getsockopt also clears WSAGetLastError,
- so reset it back. */
- WSASetLastError(res);
- else
- res = WSAGetLastError();
- }
- }
- /* else if (res < 0) an error occurred */
- }
- }
-
- if (res < 0)
- res = WSAGetLastError();
+ if (s->sock_timeout > 0.0) {
+ if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
+ IS_SELECTABLE(s)) {
+ /* This is a mess. Best solution: trust select */
+ fd_set fds;
+ fd_set fds_exc;
+ struct timeval tv;
+ tv.tv_sec = (int)s->sock_timeout;
+ tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
+ FD_ZERO(&fds);
+ FD_SET(s->sock_fd, &fds);
+ FD_ZERO(&fds_exc);
+ FD_SET(s->sock_fd, &fds_exc);
+ res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
+ if (res == 0) {
+ res = WSAEWOULDBLOCK;
+ timeout = 1;
+ } else if (res > 0) {
+ if (FD_ISSET(s->sock_fd, &fds))
+ /* The socket is in the writable set - this
+ means connected */
+ res = 0;
+ else {
+ /* As per MS docs, we need to call getsockopt()
+ to get the underlying error */
+ int res_size = sizeof res;
+ /* It must be in the exception set */
+ assert(FD_ISSET(s->sock_fd, &fds_exc));
+ if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
+ (char *)&res, &res_size))
+ /* getsockopt also clears WSAGetLastError,
+ so reset it back. */
+ WSASetLastError(res);
+ else
+ res = WSAGetLastError();
+ }
+ }
+ /* else if (res < 0) an error occurred */
+ }
+ }
+
+ if (res < 0)
+ res = WSAGetLastError();
#else
- if (s->sock_timeout > 0.0) {
- if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
- timeout = internal_select(s, 1);
- if (timeout == 0) {
- /* Bug #1019808: in case of an EINPROGRESS,
- use getsockopt(SO_ERROR) to get the real
- error. */
- socklen_t res_size = sizeof res;
- (void)getsockopt(s->sock_fd, SOL_SOCKET,
- SO_ERROR, &res, &res_size);
- if (res == EISCONN)
- res = 0;
- errno = res;
- }
- else if (timeout == -1) {
- res = errno; /* had error */
- }
- else
- res = EWOULDBLOCK; /* timed out */
- }
- }
-
- if (res < 0)
- res = errno;
-
-#endif
- *timeoutp = timeout;
-
- return res;
+ if (s->sock_timeout > 0.0) {
+ if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
+ timeout = internal_select(s, 1);
+ if (timeout == 0) {
+ /* Bug #1019808: in case of an EINPROGRESS,
+ use getsockopt(SO_ERROR) to get the real
+ error. */
+ socklen_t res_size = sizeof res;
+ (void)getsockopt(s->sock_fd, SOL_SOCKET,
+ SO_ERROR, &res, &res_size);
+ if (res == EISCONN)
+ res = 0;
+ errno = res;
+ }
+ else if (timeout == -1) {
+ res = errno; /* had error */
+ }
+ else
+ res = EWOULDBLOCK; /* timed out */
+ }
+ }
+
+ if (res < 0)
+ res = errno;
+
+#endif
+ *timeoutp = timeout;
+
+ return res;
}
/* s.connect(sockaddr) method */
@@ -1962,26 +1962,26 @@ internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
static PyObject *
sock_connect(PySocketSockObject *s, PyObject *addro)
{
- sock_addr_t addrbuf;
- int addrlen;
- int res;
- int timeout;
-
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (res != 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ sock_addr_t addrbuf;
+ int addrlen;
+ int res;
+ int timeout;
+
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (res != 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(connect_doc,
@@ -1996,26 +1996,26 @@ is a pair (host, port).");
static PyObject *
sock_connect_ex(PySocketSockObject *s, PyObject *addro)
{
- sock_addr_t addrbuf;
- int addrlen;
- int res;
- int timeout;
+ sock_addr_t addrbuf;
+ int addrlen;
+ int res;
+ int timeout;
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
- return NULL;
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
+ Py_END_ALLOW_THREADS
- /* Signals are not errors (though they may raise exceptions). Adapted
- from PyErr_SetFromErrnoWithFilenameObject(). */
+ /* Signals are not errors (though they may raise exceptions). Adapted
+ from PyErr_SetFromErrnoWithFilenameObject(). */
#ifdef EINTR
- if (res == EINTR && PyErr_CheckSignals())
- return NULL;
+ if (res == EINTR && PyErr_CheckSignals())
+ return NULL;
#endif
- return PyLong_FromLong((long) res);
+ return PyLong_FromLong((long) res);
}
PyDoc_STRVAR(connect_ex_doc,
@@ -2030,7 +2030,7 @@ instead of raising an exception when an error occurs.");
static PyObject *
sock_fileno(PySocketSockObject *s)
{
- return PyLong_FromSocket_t(s->sock_fd);
+ return PyLong_FromSocket_t(s->sock_fd);
}
PyDoc_STRVAR(fileno_doc,
@@ -2044,20 +2044,20 @@ Return the integer file descriptor of the socket.");
static PyObject *
sock_getsockname(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- int res;
- socklen_t addrlen;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
- Py_BEGIN_ALLOW_THREADS
- res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
- s->sock_proto);
+ sock_addr_t addrbuf;
+ int res;
+ socklen_t addrlen;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
+ Py_BEGIN_ALLOW_THREADS
+ res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
+ s->sock_proto);
}
PyDoc_STRVAR(getsockname_doc,
@@ -2067,26 +2067,26 @@ Return the address of the local endpoint. For IP sockets, the address\n\
info is a pair (hostaddr, port).");
-#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
+#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
/* s.getpeername() method */
static PyObject *
sock_getpeername(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- int res;
- socklen_t addrlen;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
- Py_BEGIN_ALLOW_THREADS
- res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
- s->sock_proto);
+ sock_addr_t addrbuf;
+ int res;
+ socklen_t addrlen;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
+ Py_BEGIN_ALLOW_THREADS
+ res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
+ s->sock_proto);
}
PyDoc_STRVAR(getpeername_doc,
@@ -2103,21 +2103,21 @@ info is a pair (hostaddr, port).");
static PyObject *
sock_listen(PySocketSockObject *s, PyObject *arg)
{
- int backlog;
- int res;
-
- backlog = PyLong_AsLong(arg);
- if (backlog == -1 && PyErr_Occurred())
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- if (backlog < 1)
- backlog = 1;
- res = listen(s->sock_fd, backlog);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ int backlog;
+ int res;
+
+ backlog = PyLong_AsLong(arg);
+ if (backlog == -1 && PyErr_Occurred())
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ if (backlog < 1)
+ backlog = 1;
+ res = listen(s->sock_fd, backlog);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(listen_doc,
@@ -2139,80 +2139,80 @@ will allow before refusing new connections.");
static ssize_t
sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
{
- ssize_t outlen = -1;
- int timeout;
+ ssize_t outlen = -1;
+ int timeout;
#ifdef __VMS
- int remaining;
- char *read_buf;
+ int remaining;
+ char *read_buf;
#endif
- if (!IS_SELECTABLE(s)) {
- select_error();
- return -1;
- }
- if (len == 0) {
- /* If 0 bytes were requested, do nothing. */
- return 0;
- }
+ if (!IS_SELECTABLE(s)) {
+ select_error();
+ return -1;
+ }
+ if (len == 0) {
+ /* If 0 bytes were requested, do nothing. */
+ return 0;
+ }
#ifndef __VMS
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 0);
- if (!timeout)
- outlen = recv(s->sock_fd, cbuf, len, flags);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return -1;
- }
- if (outlen < 0) {
- /* Note: the call to errorhandler() ALWAYS indirectly returned
- NULL, so ignore its return value */
- s->errorhandler();
- return -1;
- }
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 0);
+ if (!timeout)
+ outlen = recv(s->sock_fd, cbuf, len, flags);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return -1;
+ }
+ if (outlen < 0) {
+ /* Note: the call to errorhandler() ALWAYS indirectly returned
+ NULL, so ignore its return value */
+ s->errorhandler();
+ return -1;
+ }
#else
- read_buf = cbuf;
- remaining = len;
- while (remaining != 0) {
- unsigned int segment;
- int nread = -1;
-
- segment = remaining /SEGMENT_SIZE;
- if (segment != 0) {
- segment = SEGMENT_SIZE;
- }
- else {
- segment = remaining;
- }
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 0);
- if (!timeout)
- nread = recv(s->sock_fd, read_buf, segment, flags);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return -1;
- }
- if (nread < 0) {
- s->errorhandler();
- return -1;
- }
- if (nread != remaining) {
- read_buf += nread;
- break;
- }
-
- remaining -= segment;
- read_buf += segment;
- }
- outlen = read_buf - cbuf;
+ read_buf = cbuf;
+ remaining = len;
+ while (remaining != 0) {
+ unsigned int segment;
+ int nread = -1;
+
+ segment = remaining /SEGMENT_SIZE;
+ if (segment != 0) {
+ segment = SEGMENT_SIZE;
+ }
+ else {
+ segment = remaining;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 0);
+ if (!timeout)
+ nread = recv(s->sock_fd, read_buf, segment, flags);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return -1;
+ }
+ if (nread < 0) {
+ s->errorhandler();
+ return -1;
+ }
+ if (nread != remaining) {
+ read_buf += nread;
+ break;
+ }
+
+ remaining -= segment;
+ read_buf += segment;
+ }
+ outlen = read_buf - cbuf;
#endif /* !__VMS */
- return outlen;
+ return outlen;
}
@@ -2221,39 +2221,39 @@ sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
static PyObject *
sock_recv(PySocketSockObject *s, PyObject *args)
{
- int recvlen, flags = 0;
- ssize_t outlen;
- PyObject *buf;
-
- if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
- return NULL;
-
- if (recvlen < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recv");
- return NULL;
- }
-
- /* Allocate a new string. */
- buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
- if (buf == NULL)
- return NULL;
-
- /* Call the guts */
- outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
- if (outlen < 0) {
- /* An error occurred, release the string and return an
- error. */
- Py_DECREF(buf);
- return NULL;
- }
- if (outlen != recvlen) {
- /* We did not read as many bytes as we anticipated, resize the
- string if possible and be successful. */
- _PyBytes_Resize(&buf, outlen);
- }
-
- return buf;
+ int recvlen, flags = 0;
+ ssize_t outlen;
+ PyObject *buf;
+
+ if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
+ return NULL;
+
+ if (recvlen < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recv");
+ return NULL;
+ }
+
+ /* Allocate a new string. */
+ buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
+ if (buf == NULL)
+ return NULL;
+
+ /* Call the guts */
+ outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
+ if (outlen < 0) {
+ /* An error occurred, release the string and return an
+ error. */
+ Py_DECREF(buf);
+ return NULL;
+ }
+ if (outlen != recvlen) {
+ /* We did not read as many bytes as we anticipated, resize the
+ string if possible and be successful. */
+ _PyBytes_Resize(&buf, outlen);
+ }
+
+ return buf;
}
PyDoc_STRVAR(recv_doc,
@@ -2270,52 +2270,52 @@ the remote end is closed and all data is read, return the empty string.");
static PyObject*
sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
-
- int recvlen = 0, flags = 0;
- ssize_t readlen;
- Py_buffer pbuf;
- char *buf;
- int buflen;
-
- /* Get the buffer's memory */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
- &pbuf, &recvlen, &flags))
- return NULL;
- buf = pbuf.buf;
- buflen = pbuf.len;
-
- if (recvlen < 0) {
- PyBuffer_Release(&pbuf);
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recv_into");
- return NULL;
- }
- if (recvlen == 0) {
- /* If nbytes was not specified, use the buffer's length */
- recvlen = buflen;
- }
-
- /* Check if the buffer is large enough */
- if (buflen < recvlen) {
- PyBuffer_Release(&pbuf);
- PyErr_SetString(PyExc_ValueError,
- "buffer too small for requested bytes");
- return NULL;
- }
-
- /* Call the guts */
- readlen = sock_recv_guts(s, buf, recvlen, flags);
- if (readlen < 0) {
- /* Return an error. */
- PyBuffer_Release(&pbuf);
- return NULL;
- }
-
- PyBuffer_Release(&pbuf);
- /* Return the number of bytes read. Note that we do not do anything
- special here in the case that readlen < recvlen. */
- return PyLong_FromSsize_t(readlen);
+ static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
+
+ int recvlen = 0, flags = 0;
+ ssize_t readlen;
+ Py_buffer pbuf;
+ char *buf;
+ int buflen;
+
+ /* Get the buffer's memory */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
+ &pbuf, &recvlen, &flags))
+ return NULL;
+ buf = pbuf.buf;
+ buflen = pbuf.len;
+
+ if (recvlen < 0) {
+ PyBuffer_Release(&pbuf);
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recv_into");
+ return NULL;
+ }
+ if (recvlen == 0) {
+ /* If nbytes was not specified, use the buffer's length */
+ recvlen = buflen;
+ }
+
+ /* Check if the buffer is large enough */
+ if (buflen < recvlen) {
+ PyBuffer_Release(&pbuf);
+ PyErr_SetString(PyExc_ValueError,
+ "buffer too small for requested bytes");
+ return NULL;
+ }
+
+ /* Call the guts */
+ readlen = sock_recv_guts(s, buf, recvlen, flags);
+ if (readlen < 0) {
+ /* Return an error. */
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+
+ PyBuffer_Release(&pbuf);
+ /* Return the number of bytes read. Note that we do not do anything
+ special here in the case that readlen < recvlen. */
+ return PyLong_FromSsize_t(readlen);
}
PyDoc_STRVAR(recv_into_doc,
@@ -2341,56 +2341,56 @@ See recv() for documentation about the flags.");
*/
static ssize_t
sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
- PyObject** addr)
+ PyObject** addr)
{
- sock_addr_t addrbuf;
- int timeout;
- ssize_t n = -1;
- socklen_t addrlen;
+ sock_addr_t addrbuf;
+ int timeout;
+ ssize_t n = -1;
+ socklen_t addrlen;
- *addr = NULL;
+ *addr = NULL;
- if (!getsockaddrlen(s, &addrlen))
- return -1;
+ if (!getsockaddrlen(s, &addrlen))
+ return -1;
- if (!IS_SELECTABLE(s)) {
- select_error();
- return -1;
- }
+ if (!IS_SELECTABLE(s)) {
+ select_error();
+ return -1;
+ }
- Py_BEGIN_ALLOW_THREADS
- memset(&addrbuf, 0, addrlen);
- timeout = internal_select(s, 0);
- if (!timeout) {
+ Py_BEGIN_ALLOW_THREADS
+ memset(&addrbuf, 0, addrlen);
+ timeout = internal_select(s, 0);
+ if (!timeout) {
#ifndef MS_WINDOWS
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
- n = recvfrom(s->sock_fd, cbuf, len, flags,
- SAS2SA(&addrbuf), &addrlen);
+ n = recvfrom(s->sock_fd, cbuf, len, flags,
+ SAS2SA(&addrbuf), &addrlen);
#else
- n = recvfrom(s->sock_fd, cbuf, len, flags,
- (void *) &addrbuf, &addrlen);
+ n = recvfrom(s->sock_fd, cbuf, len, flags,
+ (void *) &addrbuf, &addrlen);
#endif
#else
- n = recvfrom(s->sock_fd, cbuf, len, flags,
- SAS2SA(&addrbuf), &addrlen);
-#endif
- }
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return -1;
- }
- if (n < 0) {
- s->errorhandler();
- return -1;
- }
-
- if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
- addrlen, s->sock_proto)))
- return -1;
-
- return n;
+ n = recvfrom(s->sock_fd, cbuf, len, flags,
+ SAS2SA(&addrbuf), &addrlen);
+#endif
+ }
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return -1;
+ }
+ if (n < 0) {
+ s->errorhandler();
+ return -1;
+ }
+
+ if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
+ addrlen, s->sock_proto)))
+ return -1;
+
+ return n;
}
/* s.recvfrom(nbytes [,flags]) method */
@@ -2398,45 +2398,45 @@ sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
static PyObject *
sock_recvfrom(PySocketSockObject *s, PyObject *args)
{
- PyObject *buf = NULL;
- PyObject *addr = NULL;
- PyObject *ret = NULL;
- int recvlen, flags = 0;
- ssize_t outlen;
-
- if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
- return NULL;
-
- if (recvlen < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recvfrom");
- return NULL;
- }
-
- buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
- if (buf == NULL)
- return NULL;
-
- outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
- recvlen, flags, &addr);
- if (outlen < 0) {
- goto finally;
- }
-
- if (outlen != recvlen) {
- /* We did not read as many bytes as we anticipated, resize the
- string if possible and be succesful. */
- if (_PyBytes_Resize(&buf, outlen) < 0)
- /* Oopsy, not so succesful after all. */
- goto finally;
- }
-
- ret = PyTuple_Pack(2, buf, addr);
+ PyObject *buf = NULL;
+ PyObject *addr = NULL;
+ PyObject *ret = NULL;
+ int recvlen, flags = 0;
+ ssize_t outlen;
+
+ if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
+ return NULL;
+
+ if (recvlen < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recvfrom");
+ return NULL;
+ }
+
+ buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
+ if (buf == NULL)
+ return NULL;
+
+ outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
+ recvlen, flags, &addr);
+ if (outlen < 0) {
+ goto finally;
+ }
+
+ if (outlen != recvlen) {
+ /* We did not read as many bytes as we anticipated, resize the
+ string if possible and be succesful. */
+ if (_PyBytes_Resize(&buf, outlen) < 0)
+ /* Oopsy, not so succesful after all. */
+ goto finally;
+ }
+
+ ret = PyTuple_Pack(2, buf, addr);
finally:
- Py_XDECREF(buf);
- Py_XDECREF(addr);
- return ret;
+ Py_XDECREF(buf);
+ Py_XDECREF(addr);
+ return ret;
}
PyDoc_STRVAR(recvfrom_doc,
@@ -2450,47 +2450,47 @@ Like recv(buffersize, flags) but also return the sender's address info.");
static PyObject *
sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
{
- static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
-
- int recvlen = 0, flags = 0;
- ssize_t readlen;
- Py_buffer pbuf;
- char *buf;
- int buflen;
-
- PyObject *addr = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
- kwlist, &pbuf,
- &recvlen, &flags))
- return NULL;
- buf = pbuf.buf;
- buflen = pbuf.len;
- assert(buf != 0 && buflen > 0);
-
- if (recvlen < 0) {
- PyBuffer_Release(&pbuf);
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recvfrom_into");
- return NULL;
- }
- if (recvlen == 0) {
- /* If nbytes was not specified, use the buffer's length */
- recvlen = buflen;
- }
-
- readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
- if (readlen < 0) {
- PyBuffer_Release(&pbuf);
- /* Return an error */
- Py_XDECREF(addr);
- return NULL;
- }
-
- PyBuffer_Release(&pbuf);
- /* Return the number of bytes read and the address. Note that we do
- not do anything special here in the case that readlen < recvlen. */
- return Py_BuildValue("lN", readlen, addr);
+ static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
+
+ int recvlen = 0, flags = 0;
+ ssize_t readlen;
+ Py_buffer pbuf;
+ char *buf;
+ int buflen;
+
+ PyObject *addr = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
+ kwlist, &pbuf,
+ &recvlen, &flags))
+ return NULL;
+ buf = pbuf.buf;
+ buflen = pbuf.len;
+ assert(buf != 0 && buflen > 0);
+
+ if (recvlen < 0) {
+ PyBuffer_Release(&pbuf);
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recvfrom_into");
+ return NULL;
+ }
+ if (recvlen == 0) {
+ /* If nbytes was not specified, use the buffer's length */
+ recvlen = buflen;
+ }
+
+ readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
+ if (readlen < 0) {
+ PyBuffer_Release(&pbuf);
+ /* Return an error */
+ Py_XDECREF(addr);
+ return NULL;
+ }
+
+ PyBuffer_Release(&pbuf);
+ /* Return the number of bytes read and the address. Note that we do
+ not do anything special here in the case that readlen < recvlen. */
+ return Py_BuildValue("lN", readlen, addr);
}
PyDoc_STRVAR(recvfrom_into_doc,
@@ -2504,39 +2504,39 @@ Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address i
static PyObject *
sock_send(PySocketSockObject *s, PyObject *args)
{
- char *buf;
- int len, n = -1, flags = 0, timeout;
- Py_buffer pbuf;
-
- if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
- return NULL;
-
- if (!IS_SELECTABLE(s)) {
- PyBuffer_Release(&pbuf);
- return select_error();
- }
- buf = pbuf.buf;
- len = pbuf.len;
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 1);
- if (!timeout)
+ char *buf;
+ int len, n = -1, flags = 0, timeout;
+ Py_buffer pbuf;
+
+ if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
+ return NULL;
+
+ if (!IS_SELECTABLE(s)) {
+ PyBuffer_Release(&pbuf);
+ return select_error();
+ }
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 1);
+ if (!timeout)
#ifdef __VMS
- n = sendsegmented(s->sock_fd, buf, len, flags);
+ n = sendsegmented(s->sock_fd, buf, len, flags);
#else
- n = send(s->sock_fd, buf, len, flags);
+ n = send(s->sock_fd, buf, len, flags);
#endif
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
- PyBuffer_Release(&pbuf);
+ PyBuffer_Release(&pbuf);
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (n < 0)
- return s->errorhandler();
- return PyLong_FromLong((long)n);
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+ return PyLong_FromLong((long)n);
}
PyDoc_STRVAR(send_doc,
@@ -2552,61 +2552,61 @@ sent; this may be less than len(data) if the network is busy.");
static PyObject *
sock_sendall(PySocketSockObject *s, PyObject *args)
{
- char *buf;
- int len, n = -1, flags = 0, timeout;
- Py_buffer pbuf;
-
- if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
- return NULL;
- buf = pbuf.buf;
- len = pbuf.len;
-
- if (!IS_SELECTABLE(s)) {
- PyBuffer_Release(&pbuf);
- return select_error();
- }
-
- Py_BEGIN_ALLOW_THREADS
- do {
- timeout = internal_select(s, 1);
- n = -1;
- if (timeout)
- break;
+ char *buf;
+ int len, n = -1, flags = 0, timeout;
+ Py_buffer pbuf;
+
+ if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
+ return NULL;
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ if (!IS_SELECTABLE(s)) {
+ PyBuffer_Release(&pbuf);
+ return select_error();
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ do {
+ timeout = internal_select(s, 1);
+ n = -1;
+ if (timeout)
+ break;
#ifdef __VMS
- n = sendsegmented(s->sock_fd, buf, len, flags);
+ n = sendsegmented(s->sock_fd, buf, len, flags);
#else
- n = send(s->sock_fd, buf, len, flags);
+ n = send(s->sock_fd, buf, len, flags);
#endif
- if (n < 0) {
+ if (n < 0) {
#ifdef EINTR
- /* We must handle EINTR here as there is no way for
- * the caller to know how much was sent otherwise. */
- if (errno == EINTR) {
- /* Run signal handlers. If an exception was
- * raised, abort and leave this socket in
- * an unknown state. */
- if (PyErr_CheckSignals())
- return NULL;
- continue;
- }
-#endif
- break;
- }
- buf += n;
- len -= n;
- } while (len > 0);
- Py_END_ALLOW_THREADS
- PyBuffer_Release(&pbuf);
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (n < 0)
- return s->errorhandler();
-
- Py_INCREF(Py_None);
- return Py_None;
+ /* We must handle EINTR here as there is no way for
+ * the caller to know how much was sent otherwise. */
+ if (errno == EINTR) {
+ /* Run signal handlers. If an exception was
+ * raised, abort and leave this socket in
+ * an unknown state. */
+ if (PyErr_CheckSignals())
+ return NULL;
+ continue;
+ }
+#endif
+ break;
+ }
+ buf += n;
+ len -= n;
+ } while (len > 0);
+ Py_END_ALLOW_THREADS
+ PyBuffer_Release(&pbuf);
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(sendall_doc,
@@ -2623,47 +2623,47 @@ to tell how much data has been sent.");
static PyObject *
sock_sendto(PySocketSockObject *s, PyObject *args)
{
- Py_buffer pbuf;
- PyObject *addro;
- char *buf;
- Py_ssize_t len;
- sock_addr_t addrbuf;
- int addrlen, n = -1, flags, timeout;
-
- flags = 0;
- if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "y*iO:sendto",
- &pbuf, &flags, &addro))
- return NULL;
- }
- buf = pbuf.buf;
- len = pbuf.len;
-
- if (!IS_SELECTABLE(s)) {
- PyBuffer_Release(&pbuf);
- return select_error();
- }
-
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
- PyBuffer_Release(&pbuf);
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 1);
- if (!timeout)
- n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
- Py_END_ALLOW_THREADS
-
- PyBuffer_Release(&pbuf);
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (n < 0)
- return s->errorhandler();
- return PyLong_FromLong((long)n);
+ Py_buffer pbuf;
+ PyObject *addro;
+ char *buf;
+ Py_ssize_t len;
+ sock_addr_t addrbuf;
+ int addrlen, n = -1, flags, timeout;
+
+ flags = 0;
+ if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "y*iO:sendto",
+ &pbuf, &flags, &addro))
+ return NULL;
+ }
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ if (!IS_SELECTABLE(s)) {
+ PyBuffer_Release(&pbuf);
+ return select_error();
+ }
+
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 1);
+ if (!timeout)
+ n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
+ Py_END_ALLOW_THREADS
+
+ PyBuffer_Release(&pbuf);
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+ return PyLong_FromLong((long)n);
}
PyDoc_STRVAR(sendto_doc,
@@ -2678,19 +2678,19 @@ For IP sockets, the address is a pair (hostaddr, port).");
static PyObject *
sock_shutdown(PySocketSockObject *s, PyObject *arg)
{
- int how;
- int res;
-
- how = PyLong_AsLong(arg);
- if (how == -1 && PyErr_Occurred())
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- res = shutdown(s->sock_fd, how);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ int how;
+ int res;
+
+ how = PyLong_AsLong(arg);
+ if (how == -1 && PyErr_Occurred())
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ res = shutdown(s->sock_fd, how);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(shutdown_doc,
@@ -2703,37 +2703,37 @@ of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
static PyObject*
sock_ioctl(PySocketSockObject *s, PyObject *arg)
{
- unsigned long cmd = SIO_RCVALL;
- PyObject *argO;
- DWORD recv;
-
- if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
- return NULL;
-
- switch (cmd) {
- case SIO_RCVALL: {
- unsigned int option = RCVALL_ON;
- if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
- return NULL;
- if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
- NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
- return set_error();
- }
- return PyLong_FromUnsignedLong(recv); }
- case SIO_KEEPALIVE_VALS: {
- struct tcp_keepalive ka;
- if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
- &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
- return NULL;
- if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
- NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
- return set_error();
- }
- return PyLong_FromUnsignedLong(recv); }
- default:
- PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
- return NULL;
- }
+ unsigned long cmd = SIO_RCVALL;
+ PyObject *argO;
+ DWORD recv;
+
+ if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
+ return NULL;
+
+ switch (cmd) {
+ case SIO_RCVALL: {
+ unsigned int option = RCVALL_ON;
+ if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
+ return NULL;
+ if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
+ NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
+ return set_error();
+ }
+ return PyLong_FromUnsignedLong(recv); }
+ case SIO_KEEPALIVE_VALS: {
+ struct tcp_keepalive ka;
+ if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
+ &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
+ return NULL;
+ if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
+ NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
+ return set_error();
+ }
+ return PyLong_FromUnsignedLong(recv); }
+ default:
+ PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
+ return NULL;
+ }
}
PyDoc_STRVAR(sock_ioctl_doc,
"ioctl(cmd, option) -> long\n\
@@ -2747,57 +2747,57 @@ SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
/* List of methods for socket objects */
static PyMethodDef sock_methods[] = {
- {"_accept", (PyCFunction)sock_accept, METH_NOARGS,
- accept_doc},
- {"bind", (PyCFunction)sock_bind, METH_O,
- bind_doc},
- {"close", (PyCFunction)sock_close, METH_NOARGS,
- close_doc},
- {"connect", (PyCFunction)sock_connect, METH_O,
- connect_doc},
- {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
- connect_ex_doc},
- {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
- fileno_doc},
+ {"_accept", (PyCFunction)sock_accept, METH_NOARGS,
+ accept_doc},
+ {"bind", (PyCFunction)sock_bind, METH_O,
+ bind_doc},
+ {"close", (PyCFunction)sock_close, METH_NOARGS,
+ close_doc},
+ {"connect", (PyCFunction)sock_connect, METH_O,
+ connect_doc},
+ {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
+ connect_ex_doc},
+ {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
+ fileno_doc},
#ifdef HAVE_GETPEERNAME
- {"getpeername", (PyCFunction)sock_getpeername,
- METH_NOARGS, getpeername_doc},
+ {"getpeername", (PyCFunction)sock_getpeername,
+ METH_NOARGS, getpeername_doc},
#endif
- {"getsockname", (PyCFunction)sock_getsockname,
- METH_NOARGS, getsockname_doc},
- {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
- getsockopt_doc},
+ {"getsockname", (PyCFunction)sock_getsockname,
+ METH_NOARGS, getsockname_doc},
+ {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
+ getsockopt_doc},
#if defined(MS_WINDOWS) && defined(SIO_RCVALL)
- {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
- sock_ioctl_doc},
-#endif
- {"listen", (PyCFunction)sock_listen, METH_O,
- listen_doc},
- {"recv", (PyCFunction)sock_recv, METH_VARARGS,
- recv_doc},
- {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
- recv_into_doc},
- {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
- recvfrom_doc},
- {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
- recvfrom_into_doc},
- {"send", (PyCFunction)sock_send, METH_VARARGS,
- send_doc},
- {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
- sendall_doc},
- {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
- sendto_doc},
- {"setblocking", (PyCFunction)sock_setblocking, METH_O,
- setblocking_doc},
- {"settimeout", (PyCFunction)sock_settimeout, METH_O,
- settimeout_doc},
- {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
- gettimeout_doc},
- {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
- setsockopt_doc},
- {"shutdown", (PyCFunction)sock_shutdown, METH_O,
- shutdown_doc},
- {NULL, NULL} /* sentinel */
+ {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
+ sock_ioctl_doc},
+#endif
+ {"listen", (PyCFunction)sock_listen, METH_O,
+ listen_doc},
+ {"recv", (PyCFunction)sock_recv, METH_VARARGS,
+ recv_doc},
+ {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
+ recv_into_doc},
+ {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
+ recvfrom_doc},
+ {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
+ recvfrom_into_doc},
+ {"send", (PyCFunction)sock_send, METH_VARARGS,
+ send_doc},
+ {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
+ sendall_doc},
+ {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
+ sendto_doc},
+ {"setblocking", (PyCFunction)sock_setblocking, METH_O,
+ setblocking_doc},
+ {"settimeout", (PyCFunction)sock_settimeout, METH_O,
+ settimeout_doc},
+ {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
+ gettimeout_doc},
+ {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
+ setsockopt_doc},
+ {"shutdown", (PyCFunction)sock_shutdown, METH_O,
+ shutdown_doc},
+ {NULL, NULL} /* sentinel */
};
/* SockObject members */
@@ -2815,9 +2815,9 @@ static PyMemberDef sock_memberlist[] = {
static void
sock_dealloc(PySocketSockObject *s)
{
- if (s->sock_fd != -1)
- (void) SOCKETCLOSE(s->sock_fd);
- Py_TYPE(s)->tp_free((PyObject *)s);
+ if (s->sock_fd != -1)
+ (void) SOCKETCLOSE(s->sock_fd);
+ Py_TYPE(s)->tp_free((PyObject *)s);
}
@@ -2825,21 +2825,21 @@ static PyObject *
sock_repr(PySocketSockObject *s)
{
#if SIZEOF_SOCKET_T > SIZEOF_LONG
- if (s->sock_fd > LONG_MAX) {
- /* this can occur on Win64, and actually there is a special
- ugly printf formatter for decimal pointer length integer
- printing, only bother if necessary*/
- PyErr_SetString(PyExc_OverflowError,
- "no printf formatter to display "
- "the socket descriptor in decimal");
- return NULL;
- }
-#endif
- return PyUnicode_FromFormat(
- "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
- (long)s->sock_fd, s->sock_family,
- s->sock_type,
- s->sock_proto);
+ if (s->sock_fd > LONG_MAX) {
+ /* this can occur on Win64, and actually there is a special
+ ugly printf formatter for decimal pointer length integer
+ printing, only bother if necessary*/
+ PyErr_SetString(PyExc_OverflowError,
+ "no printf formatter to display "
+ "the socket descriptor in decimal");
+ return NULL;
+ }
+#endif
+ return PyUnicode_FromFormat(
+ "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
+ (long)s->sock_fd, s->sock_family,
+ s->sock_type,
+ s->sock_proto);
}
@@ -2848,15 +2848,15 @@ sock_repr(PySocketSockObject *s)
static PyObject *
sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *new;
-
- new = type->tp_alloc(type, 0);
- if (new != NULL) {
- ((PySocketSockObject *)new)->sock_fd = -1;
- ((PySocketSockObject *)new)->sock_timeout = -1.0;
- ((PySocketSockObject *)new)->errorhandler = &set_error;
- }
- return new;
+ PyObject *new;
+
+ new = type->tp_alloc(type, 0);
+ if (new != NULL) {
+ ((PySocketSockObject *)new)->sock_fd = -1;
+ ((PySocketSockObject *)new)->sock_timeout = -1.0;
+ ((PySocketSockObject *)new)->errorhandler = &set_error;
+ }
+ return new;
}
@@ -2866,40 +2866,40 @@ sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
{
- PySocketSockObject *s = (PySocketSockObject *)self;
- PyObject *fdobj = NULL;
- SOCKET_T fd = INVALID_SOCKET;
- int family = AF_INET, type = SOCK_STREAM, proto = 0;
- static char *keywords[] = {"family", "type", "proto", "fileno", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds,
- "|iiiO:socket", keywords,
- &family, &type, &proto, &fdobj))
- return -1;
-
- if (fdobj != NULL && fdobj != Py_None) {
- fd = PyLong_AsSocket_t(fdobj);
- if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
- return -1;
- if (fd == INVALID_SOCKET) {
- PyErr_SetString(PyExc_ValueError,
- "can't use invalid socket value");
- return -1;
- }
- }
- else {
- Py_BEGIN_ALLOW_THREADS
- fd = socket(family, type, proto);
- Py_END_ALLOW_THREADS
-
- if (fd == INVALID_SOCKET) {
- set_error();
- return -1;
- }
- }
- init_sockobject(s, fd, family, type, proto);
-
- return 0;
+ PySocketSockObject *s = (PySocketSockObject *)self;
+ PyObject *fdobj = NULL;
+ SOCKET_T fd = INVALID_SOCKET;
+ int family = AF_INET, type = SOCK_STREAM, proto = 0;
+ static char *keywords[] = {"family", "type", "proto", "fileno", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds,
+ "|iiiO:socket", keywords,
+ &family, &type, &proto, &fdobj))
+ return -1;
+
+ if (fdobj != NULL && fdobj != Py_None) {
+ fd = PyLong_AsSocket_t(fdobj);
+ if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
+ return -1;
+ if (fd == INVALID_SOCKET) {
+ PyErr_SetString(PyExc_ValueError,
+ "can't use invalid socket value");
+ return -1;
+ }
+ }
+ else {
+ Py_BEGIN_ALLOW_THREADS
+ fd = socket(family, type, proto);
+ Py_END_ALLOW_THREADS
+
+ if (fd == INVALID_SOCKET) {
+ set_error();
+ return -1;
+ }
+ }
+ init_sockobject(s, fd, family, type, proto);
+
+ return 0;
}
@@ -2907,45 +2907,45 @@ sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
/* Type object for socket objects. */
static PyTypeObject sock_type = {
- PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
- "_socket.socket", /* tp_name */
- sizeof(PySocketSockObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)sock_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)sock_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- sock_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- sock_methods, /* tp_methods */
- sock_memberlist, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- sock_initobj, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- sock_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
+ "_socket.socket", /* tp_name */
+ sizeof(PySocketSockObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)sock_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)sock_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ sock_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ sock_methods, /* tp_methods */
+ sock_memberlist, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ sock_initobj, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ sock_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -2955,15 +2955,15 @@ static PyTypeObject sock_type = {
static PyObject *
socket_gethostname(PyObject *self, PyObject *unused)
{
- char buf[1024];
- int res;
- Py_BEGIN_ALLOW_THREADS
- res = gethostname(buf, (int) sizeof buf - 1);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return set_error();
- buf[sizeof buf - 1] = '\0';
- return PyUnicode_FromString(buf);
+ char buf[1024];
+ int res;
+ Py_BEGIN_ALLOW_THREADS
+ res = gethostname(buf, (int) sizeof buf - 1);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return set_error();
+ buf[sizeof buf - 1] = '\0';
+ return PyUnicode_FromString(buf);
}
PyDoc_STRVAR(gethostname_doc,
@@ -2978,14 +2978,14 @@ Return the current host name.");
static PyObject *
socket_gethostbyname(PyObject *self, PyObject *args)
{
- char *name;
- sock_addr_t addrbuf;
-
- if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
- return NULL;
- if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
- return NULL;
- return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
+ char *name;
+ sock_addr_t addrbuf;
+
+ if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
+ return NULL;
+ if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
+ return NULL;
+ return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
}
PyDoc_STRVAR(gethostbyname_doc,
@@ -2999,126 +2999,126 @@ Return the IP address (a string of the form '255.255.255.255') for a host.");
static PyObject *
gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
{
- char **pch;
- PyObject *rtn_tuple = (PyObject *)NULL;
- PyObject *name_list = (PyObject *)NULL;
- PyObject *addr_list = (PyObject *)NULL;
- PyObject *tmp;
+ char **pch;
+ PyObject *rtn_tuple = (PyObject *)NULL;
+ PyObject *name_list = (PyObject *)NULL;
+ PyObject *addr_list = (PyObject *)NULL;
+ PyObject *tmp;
- if (h == NULL) {
- /* Let's get real error message to return */
- set_herror(h_errno);
- return NULL;
- }
+ if (h == NULL) {
+ /* Let's get real error message to return */
+ set_herror(h_errno);
+ return NULL;
+ }
- if (h->h_addrtype != af) {
- /* Let's get real error message to return */
- PyErr_SetString(socket_error,
- (char *)strerror(EAFNOSUPPORT));
+ if (h->h_addrtype != af) {
+ /* Let's get real error message to return */
+ PyErr_SetString(socket_error,
+ (char *)strerror(EAFNOSUPPORT));
- return NULL;
- }
+ return NULL;
+ }
- switch (af) {
+ switch (af) {
- case AF_INET:
- if (alen < sizeof(struct sockaddr_in))
- return NULL;
- break;
+ case AF_INET:
+ if (alen < sizeof(struct sockaddr_in))
+ return NULL;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- if (alen < sizeof(struct sockaddr_in6))
- return NULL;
- break;
+ case AF_INET6:
+ if (alen < sizeof(struct sockaddr_in6))
+ return NULL;
+ break;
#endif
- }
+ }
- if ((name_list = PyList_New(0)) == NULL)
- goto err;
+ if ((name_list = PyList_New(0)) == NULL)
+ goto err;
- if ((addr_list = PyList_New(0)) == NULL)
- goto err;
+ if ((addr_list = PyList_New(0)) == NULL)
+ goto err;
- /* SF #1511317: h_aliases can be NULL */
- if (h->h_aliases) {
- for (pch = h->h_aliases; *pch != NULL; pch++) {
- int status;
- tmp = PyUnicode_FromString(*pch);
- if (tmp == NULL)
- goto err;
+ /* SF #1511317: h_aliases can be NULL */
+ if (h->h_aliases) {
+ for (pch = h->h_aliases; *pch != NULL; pch++) {
+ int status;
+ tmp = PyUnicode_FromString(*pch);
+ if (tmp == NULL)
+ goto err;
- status = PyList_Append(name_list, tmp);
- Py_DECREF(tmp);
+ status = PyList_Append(name_list, tmp);
+ Py_DECREF(tmp);
- if (status)
- goto err;
- }
- }
+ if (status)
+ goto err;
+ }
+ }
- for (pch = h->h_addr_list; *pch != NULL; pch++) {
- int status;
+ for (pch = h->h_addr_list; *pch != NULL; pch++) {
+ int status;
- switch (af) {
+ switch (af) {
- case AF_INET:
- {
- struct sockaddr_in sin;
- memset(&sin, 0, sizeof(sin));
- sin.sin_family = af;
+ case AF_INET:
+ {
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = af;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin.sin_len = sizeof(sin);
+ sin.sin_len = sizeof(sin);
#endif
- memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
- tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
+ memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
+ tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
- if (pch == h->h_addr_list && alen >= sizeof(sin))
- memcpy((char *) addr, &sin, sizeof(sin));
- break;
- }
+ if (pch == h->h_addr_list && alen >= sizeof(sin))
+ memcpy((char *) addr, &sin, sizeof(sin));
+ break;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6 sin6;
- memset(&sin6, 0, sizeof(sin6));
- sin6.sin6_family = af;
+ case AF_INET6:
+ {
+ struct sockaddr_in6 sin6;
+ memset(&sin6, 0, sizeof(sin6));
+ sin6.sin6_family = af;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin6.sin6_len = sizeof(sin6);
+ sin6.sin6_len = sizeof(sin6);
#endif
- memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
- tmp = makeipaddr((struct sockaddr *)&sin6,
- sizeof(sin6));
+ memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
+ tmp = makeipaddr((struct sockaddr *)&sin6,
+ sizeof(sin6));
- if (pch == h->h_addr_list && alen >= sizeof(sin6))
- memcpy((char *) addr, &sin6, sizeof(sin6));
- break;
- }
+ if (pch == h->h_addr_list && alen >= sizeof(sin6))
+ memcpy((char *) addr, &sin6, sizeof(sin6));
+ break;
+ }
#endif
- default: /* can't happen */
- PyErr_SetString(socket_error,
- "unsupported address family");
- return NULL;
- }
+ default: /* can't happen */
+ PyErr_SetString(socket_error,
+ "unsupported address family");
+ return NULL;
+ }
- if (tmp == NULL)
- goto err;
+ if (tmp == NULL)
+ goto err;
- status = PyList_Append(addr_list, tmp);
- Py_DECREF(tmp);
+ status = PyList_Append(addr_list, tmp);
+ Py_DECREF(tmp);
- if (status)
- goto err;
- }
+ if (status)
+ goto err;
+ }
- rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
+ rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
err:
- Py_XDECREF(name_list);
- Py_XDECREF(addr_list);
- return rtn_tuple;
+ Py_XDECREF(name_list);
+ Py_XDECREF(addr_list);
+ return rtn_tuple;
}
@@ -3128,63 +3128,63 @@ gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
static PyObject *
socket_gethostbyname_ex(PyObject *self, PyObject *args)
{
- char *name;
- struct hostent *h;
+ char *name;
+ struct hostent *h;
#ifdef ENABLE_IPV6
- struct sockaddr_storage addr;
+ struct sockaddr_storage addr;
#else
- struct sockaddr_in addr;
+ struct sockaddr_in addr;
#endif
- struct sockaddr *sa;
- PyObject *ret;
+ struct sockaddr *sa;
+ PyObject *ret;
#ifdef HAVE_GETHOSTBYNAME_R
- struct hostent hp_allocated;
+ struct hostent hp_allocated;
#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
- struct hostent_data data;
+ struct hostent_data data;
#else
- char buf[16384];
- int buf_len = (sizeof buf) - 1;
- int errnop;
+ char buf[16384];
+ int buf_len = (sizeof buf) - 1;
+ int errnop;
#endif
#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- int result;
+ int result;
#endif
#endif /* HAVE_GETHOSTBYNAME_R */
- if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
- return NULL;
- if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
- return NULL;
- Py_BEGIN_ALLOW_THREADS
+ if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
+ return NULL;
+ if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_GETHOSTBYNAME_R
#if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
- &h, &errnop);
+ result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
+ &h, &errnop);
#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
- h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
+ h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
- memset((void *) &data, '\0', sizeof(data));
- result = gethostbyname_r(name, &hp_allocated, &data);
- h = (result != 0) ? NULL : &hp_allocated;
+ memset((void *) &data, '\0', sizeof(data));
+ result = gethostbyname_r(name, &hp_allocated, &data);
+ h = (result != 0) ? NULL : &hp_allocated;
#endif
#else /* not HAVE_GETHOSTBYNAME_R */
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_acquire_lock(netdb_lock, 1);
+ PyThread_acquire_lock(netdb_lock, 1);
#endif
- h = gethostbyname(name);
+ h = gethostbyname(name);
#endif /* HAVE_GETHOSTBYNAME_R */
- Py_END_ALLOW_THREADS
- /* Some C libraries would require addr.__ss_family instead of
- addr.ss_family.
- Therefore, we cast the sockaddr_storage into sockaddr to
- access sa_family. */
- sa = (struct sockaddr*)&addr;
- ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
- sa->sa_family);
+ Py_END_ALLOW_THREADS
+ /* Some C libraries would require addr.__ss_family instead of
+ addr.ss_family.
+ Therefore, we cast the sockaddr_storage into sockaddr to
+ access sa_family. */
+ sa = (struct sockaddr*)&addr;
+ ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
+ sa->sa_family);
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_release_lock(netdb_lock);
+ PyThread_release_lock(netdb_lock);
#endif
- return ret;
+ return ret;
}
PyDoc_STRVAR(ghbn_ex_doc,
@@ -3201,84 +3201,84 @@ static PyObject *
socket_gethostbyaddr(PyObject *self, PyObject *args)
{
#ifdef ENABLE_IPV6
- struct sockaddr_storage addr;
+ struct sockaddr_storage addr;
#else
- struct sockaddr_in addr;
+ struct sockaddr_in addr;
#endif
- struct sockaddr *sa = (struct sockaddr *)&addr;
- char *ip_num;
- struct hostent *h;
- PyObject *ret;
+ struct sockaddr *sa = (struct sockaddr *)&addr;
+ char *ip_num;
+ struct hostent *h;
+ PyObject *ret;
#ifdef HAVE_GETHOSTBYNAME_R
- struct hostent hp_allocated;
+ struct hostent hp_allocated;
#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
- struct hostent_data data;
+ struct hostent_data data;
#else
- /* glibcs up to 2.10 assume that the buf argument to
- gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
- does not ensure. The attribute below instructs the compiler
- to maintain this alignment. */
- char buf[16384] Py_ALIGNED(8);
- int buf_len = (sizeof buf) - 1;
- int errnop;
+ /* glibcs up to 2.10 assume that the buf argument to
+ gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
+ does not ensure. The attribute below instructs the compiler
+ to maintain this alignment. */
+ char buf[16384] Py_ALIGNED(8);
+ int buf_len = (sizeof buf) - 1;
+ int errnop;
#endif
#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- int result;
+ int result;
#endif
#endif /* HAVE_GETHOSTBYNAME_R */
- char *ap;
- int al;
- int af;
-
- if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
- return NULL;
- af = AF_UNSPEC;
- if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
- return NULL;
- af = sa->sa_family;
- ap = NULL;
- al = 0;
- switch (af) {
- case AF_INET:
- ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
- al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
- break;
+ char *ap;
+ int al;
+ int af;
+
+ if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
+ return NULL;
+ af = AF_UNSPEC;
+ if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
+ return NULL;
+ af = sa->sa_family;
+ ap = NULL;
+ al = 0;
+ switch (af) {
+ case AF_INET:
+ ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
+ al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
- al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
- break;
-#endif
- default:
- PyErr_SetString(socket_error, "unsupported address family");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
+ case AF_INET6:
+ ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
+ al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
+ break;
+#endif
+ default:
+ PyErr_SetString(socket_error, "unsupported address family");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_GETHOSTBYNAME_R
#if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- result = gethostbyaddr_r(ap, al, af,
- &hp_allocated, buf, buf_len,
- &h, &errnop);
+ result = gethostbyaddr_r(ap, al, af,
+ &hp_allocated, buf, buf_len,
+ &h, &errnop);
#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
- h = gethostbyaddr_r(ap, al, af,
- &hp_allocated, buf, buf_len, &errnop);
+ h = gethostbyaddr_r(ap, al, af,
+ &hp_allocated, buf, buf_len, &errnop);
#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
- memset((void *) &data, '\0', sizeof(data));
- result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
- h = (result != 0) ? NULL : &hp_allocated;
+ memset((void *) &data, '\0', sizeof(data));
+ result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
+ h = (result != 0) ? NULL : &hp_allocated;
#endif
#else /* not HAVE_GETHOSTBYNAME_R */
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_acquire_lock(netdb_lock, 1);
+ PyThread_acquire_lock(netdb_lock, 1);
#endif
- h = gethostbyaddr(ap, al, af);
+ h = gethostbyaddr(ap, al, af);
#endif /* HAVE_GETHOSTBYNAME_R */
- Py_END_ALLOW_THREADS
- ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
+ Py_END_ALLOW_THREADS
+ ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_release_lock(netdb_lock);
+ PyThread_release_lock(netdb_lock);
#endif
- return ret;
+ return ret;
}
PyDoc_STRVAR(gethostbyaddr_doc,
@@ -3296,18 +3296,18 @@ for a host. The host argument is a string giving a host name or IP number.");
static PyObject *
socket_getservbyname(PyObject *self, PyObject *args)
{
- char *name, *proto=NULL;
- struct servent *sp;
- if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sp = getservbyname(name, proto);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "service/proto not found");
- return NULL;
- }
- return PyLong_FromLong((long) ntohs(sp->s_port));
+ char *name, *proto=NULL;
+ struct servent *sp;
+ if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sp = getservbyname(name, proto);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "service/proto not found");
+ return NULL;
+ }
+ return PyLong_FromLong((long) ntohs(sp->s_port));
}
PyDoc_STRVAR(getservbyname_doc,
@@ -3326,25 +3326,25 @@ otherwise any protocol will match.");
static PyObject *
socket_getservbyport(PyObject *self, PyObject *args)
{
- int port;
- char *proto=NULL;
- struct servent *sp;
- if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
- return NULL;
- if (port < 0 || port > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getservbyport: port must be 0-65535.");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- sp = getservbyport(htons((short)port), proto);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "port/proto not found");
- return NULL;
- }
- return PyUnicode_FromString(sp->s_name);
+ int port;
+ char *proto=NULL;
+ struct servent *sp;
+ if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
+ return NULL;
+ if (port < 0 || port > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getservbyport: port must be 0-65535.");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ sp = getservbyport(htons((short)port), proto);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "port/proto not found");
+ return NULL;
+ }
+ return PyUnicode_FromString(sp->s_name);
}
PyDoc_STRVAR(getservbyport_doc,
@@ -3362,18 +3362,18 @@ otherwise any protocol will match.");
static PyObject *
socket_getprotobyname(PyObject *self, PyObject *args)
{
- char *name;
- struct protoent *sp;
- if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sp = getprotobyname(name);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "protocol not found");
- return NULL;
- }
- return PyLong_FromLong((long) sp->p_proto);
+ char *name;
+ struct protoent *sp;
+ if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sp = getprotobyname(name);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "protocol not found");
+ return NULL;
+ }
+ return PyLong_FromLong((long) sp->p_proto);
}
PyDoc_STRVAR(getprotobyname_doc,
@@ -3388,22 +3388,22 @@ Return the protocol number for the named protocol. (Rarely used.)");
static PyObject *
socket_dup(PyObject *self, PyObject *fdobj)
{
- SOCKET_T fd, newfd;
- PyObject *newfdobj;
+ SOCKET_T fd, newfd;
+ PyObject *newfdobj;
- fd = PyLong_AsSocket_t(fdobj);
- if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
- return NULL;
+ fd = PyLong_AsSocket_t(fdobj);
+ if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
+ return NULL;
- newfd = dup_socket(fd);
- if (newfd == INVALID_SOCKET)
- return set_error();
+ newfd = dup_socket(fd);
+ if (newfd == INVALID_SOCKET)
+ return set_error();
- newfdobj = PyLong_FromSocket_t(newfd);
- if (newfdobj == NULL)
- SOCKETCLOSE(newfd);
- return newfdobj;
+ newfdobj = PyLong_FromSocket_t(newfd);
+ if (newfdobj == NULL)
+ SOCKETCLOSE(newfd);
+ return newfdobj;
}
PyDoc_STRVAR(dup_doc,
@@ -3423,40 +3423,40 @@ sockets; on some platforms os.dup() won't work for socket file descriptors.");
static PyObject *
socket_socketpair(PyObject *self, PyObject *args)
{
- PySocketSockObject *s0 = NULL, *s1 = NULL;
- SOCKET_T sv[2];
- int family, type = SOCK_STREAM, proto = 0;
- PyObject *res = NULL;
+ PySocketSockObject *s0 = NULL, *s1 = NULL;
+ SOCKET_T sv[2];
+ int family, type = SOCK_STREAM, proto = 0;
+ PyObject *res = NULL;
#if defined(AF_UNIX)
- family = AF_UNIX;
+ family = AF_UNIX;
#else
- family = AF_INET;
-#endif
- if (!PyArg_ParseTuple(args, "|iii:socketpair",
- &family, &type, &proto))
- return NULL;
- /* Create a pair of socket fds */
- if (socketpair(family, type, proto, sv) < 0)
- return set_error();
- s0 = new_sockobject(sv[0], family, type, proto);
- if (s0 == NULL)
- goto finally;
- s1 = new_sockobject(sv[1], family, type, proto);
- if (s1 == NULL)
- goto finally;
- res = PyTuple_Pack(2, s0, s1);
+ family = AF_INET;
+#endif
+ if (!PyArg_ParseTuple(args, "|iii:socketpair",
+ &family, &type, &proto))
+ return NULL;
+ /* Create a pair of socket fds */
+ if (socketpair(family, type, proto, sv) < 0)
+ return set_error();
+ s0 = new_sockobject(sv[0], family, type, proto);
+ if (s0 == NULL)
+ goto finally;
+ s1 = new_sockobject(sv[1], family, type, proto);
+ if (s1 == NULL)
+ goto finally;
+ res = PyTuple_Pack(2, s0, s1);
finally:
- if (res == NULL) {
- if (s0 == NULL)
- SOCKETCLOSE(sv[0]);
- if (s1 == NULL)
- SOCKETCLOSE(sv[1]);
- }
- Py_XDECREF(s0);
- Py_XDECREF(s1);
- return res;
+ if (res == NULL) {
+ if (s0 == NULL)
+ SOCKETCLOSE(sv[0]);
+ if (s1 == NULL)
+ SOCKETCLOSE(sv[1]);
+ }
+ Py_XDECREF(s0);
+ Py_XDECREF(s1);
+ return res;
}
PyDoc_STRVAR(socketpair_doc,
@@ -3473,18 +3473,18 @@ AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
static PyObject *
socket_ntohs(PyObject *self, PyObject *args)
{
- int x1, x2;
-
- if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
- return NULL;
- }
- if (x1 < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- x2 = (unsigned int)ntohs((unsigned short)x1);
- return PyLong_FromLong(x2);
+ int x1, x2;
+
+ if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
+ return NULL;
+ }
+ if (x1 < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ x2 = (unsigned int)ntohs((unsigned short)x1);
+ return PyLong_FromLong(x2);
}
PyDoc_STRVAR(ntohs_doc,
@@ -3496,31 +3496,31 @@ Convert a 16-bit integer from network to host byte order.");
static PyObject *
socket_ntohl(PyObject *self, PyObject *arg)
{
- unsigned long x;
+ unsigned long x;
- if (PyLong_Check(arg)) {
- x = PyLong_AsUnsignedLong(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
+ if (PyLong_Check(arg)) {
+ x = PyLong_AsUnsignedLong(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
#if SIZEOF_LONG > 4
- {
- unsigned long y;
- /* only want the trailing 32 bits */
- y = x & 0xFFFFFFFFUL;
- if (y ^ x)
- return PyErr_Format(PyExc_OverflowError,
- "long int larger than 32 bits");
- x = y;
- }
-#endif
- }
- else
- return PyErr_Format(PyExc_TypeError,
- "expected int/long, %s found",
- Py_TYPE(arg)->tp_name);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- return PyLong_FromUnsignedLong(ntohl(x));
+ {
+ unsigned long y;
+ /* only want the trailing 32 bits */
+ y = x & 0xFFFFFFFFUL;
+ if (y ^ x)
+ return PyErr_Format(PyExc_OverflowError,
+ "long int larger than 32 bits");
+ x = y;
+ }
+#endif
+ }
+ else
+ return PyErr_Format(PyExc_TypeError,
+ "expected int/long, %s found",
+ Py_TYPE(arg)->tp_name);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
+ return PyLong_FromUnsignedLong(ntohl(x));
}
PyDoc_STRVAR(ntohl_doc,
@@ -3532,18 +3532,18 @@ Convert a 32-bit integer from network to host byte order.");
static PyObject *
socket_htons(PyObject *self, PyObject *args)
{
- int x1, x2;
-
- if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
- return NULL;
- }
- if (x1 < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- x2 = (unsigned int)htons((unsigned short)x1);
- return PyLong_FromLong(x2);
+ int x1, x2;
+
+ if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
+ return NULL;
+ }
+ if (x1 < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ x2 = (unsigned int)htons((unsigned short)x1);
+ return PyLong_FromLong(x2);
}
PyDoc_STRVAR(htons_doc,
@@ -3555,29 +3555,29 @@ Convert a 16-bit integer from host to network byte order.");
static PyObject *
socket_htonl(PyObject *self, PyObject *arg)
{
- unsigned long x;
+ unsigned long x;
- if (PyLong_Check(arg)) {
- x = PyLong_AsUnsignedLong(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
+ if (PyLong_Check(arg)) {
+ x = PyLong_AsUnsignedLong(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
#if SIZEOF_LONG > 4
- {
- unsigned long y;
- /* only want the trailing 32 bits */
- y = x & 0xFFFFFFFFUL;
- if (y ^ x)
- return PyErr_Format(PyExc_OverflowError,
- "long int larger than 32 bits");
- x = y;
- }
-#endif
- }
- else
- return PyErr_Format(PyExc_TypeError,
- "expected int/long, %s found",
- Py_TYPE(arg)->tp_name);
- return PyLong_FromUnsignedLong(htonl((unsigned long)x));
+ {
+ unsigned long y;
+ /* only want the trailing 32 bits */
+ y = x & 0xFFFFFFFFUL;
+ if (y ^ x)
+ return PyErr_Format(PyExc_OverflowError,
+ "long int larger than 32 bits");
+ x = y;
+ }
+#endif
+ }
+ else
+ return PyErr_Format(PyExc_TypeError,
+ "expected int/long, %s found",
+ Py_TYPE(arg)->tp_name);
+ return PyLong_FromUnsignedLong(htonl((unsigned long)x));
}
PyDoc_STRVAR(htonl_doc,
@@ -3600,20 +3600,20 @@ socket_inet_aton(PyObject *self, PyObject *args)
#define INADDR_NONE (-1)
#endif
#ifdef HAVE_INET_ATON
- struct in_addr buf;
+ struct in_addr buf;
#endif
#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
#if (SIZEOF_INT != 4)
#error "Not sure if in_addr_t exists and int is not 32-bits."
#endif
- /* Have to use inet_addr() instead */
- unsigned int packed_addr;
+ /* Have to use inet_addr() instead */
+ unsigned int packed_addr;
#endif
- char *ip_addr;
+ char *ip_addr;
- if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
+ return NULL;
#ifdef HAVE_INET_ATON
@@ -3621,13 +3621,13 @@ socket_inet_aton(PyObject *self, PyObject *args)
#ifdef USE_INET_ATON_WEAKLINK
if (inet_aton != NULL) {
#endif
- if (inet_aton(ip_addr, &buf))
- return PyBytes_FromStringAndSize((char *)(&buf),
- sizeof(buf));
+ if (inet_aton(ip_addr, &buf))
+ return PyBytes_FromStringAndSize((char *)(&buf),
+ sizeof(buf));
- PyErr_SetString(socket_error,
- "illegal IP address string passed to inet_aton");
- return NULL;
+ PyErr_SetString(socket_error,
+ "illegal IP address string passed to inet_aton");
+ return NULL;
#ifdef USE_INET_ATON_WEAKLINK
} else {
@@ -3637,22 +3637,22 @@ socket_inet_aton(PyObject *self, PyObject *args)
#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
- /* special-case this address as inet_addr might return INADDR_NONE
- * for this */
- if (strcmp(ip_addr, "255.255.255.255") == 0) {
- packed_addr = 0xFFFFFFFF;
- } else {
+ /* special-case this address as inet_addr might return INADDR_NONE
+ * for this */
+ if (strcmp(ip_addr, "255.255.255.255") == 0) {
+ packed_addr = 0xFFFFFFFF;
+ } else {
- packed_addr = inet_addr(ip_addr);
+ packed_addr = inet_addr(ip_addr);
- if (packed_addr == INADDR_NONE) { /* invalid address */
- PyErr_SetString(socket_error,
- "illegal IP address string passed to inet_aton");
- return NULL;
- }
- }
- return PyBytes_FromStringAndSize((char *) &packed_addr,
- sizeof(packed_addr));
+ if (packed_addr == INADDR_NONE) { /* invalid address */
+ PyErr_SetString(socket_error,
+ "illegal IP address string passed to inet_aton");
+ return NULL;
+ }
+ }
+ return PyBytes_FromStringAndSize((char *) &packed_addr,
+ sizeof(packed_addr));
#ifdef USE_INET_ATON_WEAKLINK
}
@@ -3669,23 +3669,23 @@ Convert an IP address from 32-bit packed binary format to string format");
static PyObject*
socket_inet_ntoa(PyObject *self, PyObject *args)
{
- char *packed_str;
- int addr_len;
- struct in_addr packed_addr;
+ char *packed_str;
+ int addr_len;
+ struct in_addr packed_addr;
- if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) {
+ return NULL;
+ }
- if (addr_len != sizeof(packed_addr)) {
- PyErr_SetString(socket_error,
- "packed IP wrong length for inet_ntoa");
- return NULL;
- }
+ if (addr_len != sizeof(packed_addr)) {
+ PyErr_SetString(socket_error,
+ "packed IP wrong length for inet_ntoa");
+ return NULL;
+ }
- memcpy(&packed_addr, packed_str, addr_len);
+ memcpy(&packed_addr, packed_str, addr_len);
- return PyUnicode_FromString(inet_ntoa(packed_addr));
+ return PyUnicode_FromString(inet_ntoa(packed_addr));
}
#ifdef HAVE_INET_PTON
@@ -3699,46 +3699,46 @@ for use with low-level network functions.");
static PyObject *
socket_inet_pton(PyObject *self, PyObject *args)
{
- int af;
- char* ip;
- int retval;
+ int af;
+ char* ip;
+ int retval;
#ifdef ENABLE_IPV6
- char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
+ char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
#else
- char packed[sizeof(struct in_addr)];
+ char packed[sizeof(struct in_addr)];
#endif
- if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
+ return NULL;
+ }
#if !defined(ENABLE_IPV6) && defined(AF_INET6)
- if(af == AF_INET6) {
- PyErr_SetString(socket_error,
- "can't use AF_INET6, IPv6 is disabled");
- return NULL;
- }
-#endif
-
- retval = inet_pton(af, ip, packed);
- if (retval < 0) {
- PyErr_SetFromErrno(socket_error);
- return NULL;
- } else if (retval == 0) {
- PyErr_SetString(socket_error,
- "illegal IP address string passed to inet_pton");
- return NULL;
- } else if (af == AF_INET) {
- return PyBytes_FromStringAndSize(packed,
- sizeof(struct in_addr));
+ if(af == AF_INET6) {
+ PyErr_SetString(socket_error,
+ "can't use AF_INET6, IPv6 is disabled");
+ return NULL;
+ }
+#endif
+
+ retval = inet_pton(af, ip, packed);
+ if (retval < 0) {
+ PyErr_SetFromErrno(socket_error);
+ return NULL;
+ } else if (retval == 0) {
+ PyErr_SetString(socket_error,
+ "illegal IP address string passed to inet_pton");
+ return NULL;
+ } else if (af == AF_INET) {
+ return PyBytes_FromStringAndSize(packed,
+ sizeof(struct in_addr));
#ifdef ENABLE_IPV6
- } else if (af == AF_INET6) {
- return PyBytes_FromStringAndSize(packed,
- sizeof(struct in6_addr));
-#endif
- } else {
- PyErr_SetString(socket_error, "unknown address family");
- return NULL;
- }
+ } else if (af == AF_INET6) {
+ return PyBytes_FromStringAndSize(packed,
+ sizeof(struct in6_addr));
+#endif
+ } else {
+ PyErr_SetString(socket_error, "unknown address family");
+ return NULL;
+ }
}
PyDoc_STRVAR(inet_ntop_doc,
@@ -3749,54 +3749,54 @@ Convert a packed IP address of the given family to string format.");
static PyObject *
socket_inet_ntop(PyObject *self, PyObject *args)
{
- int af;
- char* packed;
- int len;
- const char* retval;
+ int af;
+ char* packed;
+ int len;
+ const char* retval;
#ifdef ENABLE_IPV6
- char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
+ char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
#else
- char ip[INET_ADDRSTRLEN + 1];
+ char ip[INET_ADDRSTRLEN + 1];
#endif
- /* Guarantee NUL-termination for PyUnicode_FromString() below */
- memset((void *) &ip[0], '\0', sizeof(ip));
+ /* Guarantee NUL-termination for PyUnicode_FromString() below */
+ memset((void *) &ip[0], '\0', sizeof(ip));
- if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) {
+ return NULL;
+ }
- if (af == AF_INET) {
- if (len != sizeof(struct in_addr)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid length of packed IP address string");
- return NULL;
- }
+ if (af == AF_INET) {
+ if (len != sizeof(struct in_addr)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid length of packed IP address string");
+ return NULL;
+ }
#ifdef ENABLE_IPV6
- } else if (af == AF_INET6) {
- if (len != sizeof(struct in6_addr)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid length of packed IP address string");
- return NULL;
- }
-#endif
- } else {
- PyErr_Format(PyExc_ValueError,
- "unknown address family %d", af);
- return NULL;
- }
-
- retval = inet_ntop(af, packed, ip, sizeof(ip));
- if (!retval) {
- PyErr_SetFromErrno(socket_error);
- return NULL;
- } else {
- return PyUnicode_FromString(retval);
- }
-
- /* NOTREACHED */
- PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
- return NULL;
+ } else if (af == AF_INET6) {
+ if (len != sizeof(struct in6_addr)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid length of packed IP address string");
+ return NULL;
+ }
+#endif
+ } else {
+ PyErr_Format(PyExc_ValueError,
+ "unknown address family %d", af);
+ return NULL;
+ }
+
+ retval = inet_ntop(af, packed, ip, sizeof(ip));
+ if (!retval) {
+ PyErr_SetFromErrno(socket_error);
+ return NULL;
+ } else {
+ return PyUnicode_FromString(retval);
+ }
+
+ /* NOTREACHED */
+ PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
+ return NULL;
}
#endif /* HAVE_INET_PTON */
@@ -3807,100 +3807,100 @@ socket_inet_ntop(PyObject *self, PyObject *args)
static PyObject *
socket_getaddrinfo(PyObject *self, PyObject *args)
{
- struct addrinfo hints, *res;
- struct addrinfo *res0 = NULL;
- PyObject *hobj = NULL;
- PyObject *pobj = (PyObject *)NULL;
- char pbuf[30];
- char *hptr, *pptr;
- int family, socktype, protocol, flags;
- int error;
- PyObject *all = (PyObject *)NULL;
- PyObject *idna = NULL;
-
- family = socktype = protocol = flags = 0;
- family = AF_UNSPEC;
- if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
- &hobj, &pobj, &family, &socktype,
- &protocol, &flags)) {
- return NULL;
- }
- if (hobj == Py_None) {
- hptr = NULL;
- } else if (PyUnicode_Check(hobj)) {
- idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
- if (!idna)
- return NULL;
- assert(PyBytes_Check(idna));
- hptr = PyBytes_AS_STRING(idna);
- } else if (PyBytes_Check(hobj)) {
- hptr = PyBytes_AsString(hobj);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "getaddrinfo() argument 1 must be string or None");
- return NULL;
- }
- if (PyLong_CheckExact(pobj)) {
- long value = PyLong_AsLong(pobj);
- if (value == -1 && PyErr_Occurred())
- goto err;
- PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value);
- pptr = pbuf;
- } else if (PyUnicode_Check(pobj)) {
- pptr = _PyUnicode_AsString(pobj);
- } else if (PyBytes_Check(pobj)) {
- pptr = PyBytes_AsString(pobj);
- } else if (pobj == Py_None) {
- pptr = (char *)NULL;
- } else {
- PyErr_SetString(socket_error, "Int or String expected");
- goto err;
- }
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = family;
- hints.ai_socktype = socktype;
- hints.ai_protocol = protocol;
- hints.ai_flags = flags;
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(hptr, pptr, &hints, &res0);
- Py_END_ALLOW_THREADS
- RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
- if (error) {
- set_gaierror(error);
- goto err;
- }
-
- if ((all = PyList_New(0)) == NULL)
- goto err;
- for (res = res0; res; res = res->ai_next) {
- PyObject *single;
- PyObject *addr =
- makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
- if (addr == NULL)
- goto err;
- single = Py_BuildValue("iiisO", res->ai_family,
- res->ai_socktype, res->ai_protocol,
- res->ai_canonname ? res->ai_canonname : "",
- addr);
- Py_DECREF(addr);
- if (single == NULL)
- goto err;
-
- if (PyList_Append(all, single))
- goto err;
- Py_XDECREF(single);
- }
- Py_XDECREF(idna);
- if (res0)
- freeaddrinfo(res0);
- return all;
+ struct addrinfo hints, *res;
+ struct addrinfo *res0 = NULL;
+ PyObject *hobj = NULL;
+ PyObject *pobj = (PyObject *)NULL;
+ char pbuf[30];
+ char *hptr, *pptr;
+ int family, socktype, protocol, flags;
+ int error;
+ PyObject *all = (PyObject *)NULL;
+ PyObject *idna = NULL;
+
+ family = socktype = protocol = flags = 0;
+ family = AF_UNSPEC;
+ if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
+ &hobj, &pobj, &family, &socktype,
+ &protocol, &flags)) {
+ return NULL;
+ }
+ if (hobj == Py_None) {
+ hptr = NULL;
+ } else if (PyUnicode_Check(hobj)) {
+ idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
+ if (!idna)
+ return NULL;
+ assert(PyBytes_Check(idna));
+ hptr = PyBytes_AS_STRING(idna);
+ } else if (PyBytes_Check(hobj)) {
+ hptr = PyBytes_AsString(hobj);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "getaddrinfo() argument 1 must be string or None");
+ return NULL;
+ }
+ if (PyLong_CheckExact(pobj)) {
+ long value = PyLong_AsLong(pobj);
+ if (value == -1 && PyErr_Occurred())
+ goto err;
+ PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value);
+ pptr = pbuf;
+ } else if (PyUnicode_Check(pobj)) {
+ pptr = _PyUnicode_AsString(pobj);
+ } else if (PyBytes_Check(pobj)) {
+ pptr = PyBytes_AsString(pobj);
+ } else if (pobj == Py_None) {
+ pptr = (char *)NULL;
+ } else {
+ PyErr_SetString(socket_error, "Int or String expected");
+ goto err;
+ }
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = family;
+ hints.ai_socktype = socktype;
+ hints.ai_protocol = protocol;
+ hints.ai_flags = flags;
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(hptr, pptr, &hints, &res0);
+ Py_END_ALLOW_THREADS
+ RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
+ if (error) {
+ set_gaierror(error);
+ goto err;
+ }
+
+ if ((all = PyList_New(0)) == NULL)
+ goto err;
+ for (res = res0; res; res = res->ai_next) {
+ PyObject *single;
+ PyObject *addr =
+ makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
+ if (addr == NULL)
+ goto err;
+ single = Py_BuildValue("iiisO", res->ai_family,
+ res->ai_socktype, res->ai_protocol,
+ res->ai_canonname ? res->ai_canonname : "",
+ addr);
+ Py_DECREF(addr);
+ if (single == NULL)
+ goto err;
+
+ if (PyList_Append(all, single))
+ goto err;
+ Py_XDECREF(single);
+ }
+ Py_XDECREF(idna);
+ if (res0)
+ freeaddrinfo(res0);
+ return all;
err:
- Py_XDECREF(all);
- Py_XDECREF(idna);
- if (res0)
- freeaddrinfo(res0);
- return (PyObject *)NULL;
+ Py_XDECREF(all);
+ Py_XDECREF(idna);
+ if (res0)
+ freeaddrinfo(res0);
+ return (PyObject *)NULL;
}
PyDoc_STRVAR(getaddrinfo_doc,
@@ -3915,77 +3915,77 @@ Resolve host and port into addrinfo struct.");
static PyObject *
socket_getnameinfo(PyObject *self, PyObject *args)
{
- PyObject *sa = (PyObject *)NULL;
- int flags;
- char *hostp;
- int port, flowinfo, scope_id;
- char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
- struct addrinfo hints, *res = NULL;
- int error;
- PyObject *ret = (PyObject *)NULL;
-
- flags = flowinfo = scope_id = 0;
- if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
- return NULL;
- if (!PyTuple_Check(sa)) {
- PyErr_SetString(PyExc_TypeError,
- "getnameinfo() argument 1 must be a tuple");
- return NULL;
- }
- if (!PyArg_ParseTuple(sa, "si|ii",
- &hostp, &port, &flowinfo, &scope_id))
- return NULL;
- PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(hostp, pbuf, &hints, &res);
- Py_END_ALLOW_THREADS
- RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
- if (error) {
- set_gaierror(error);
- goto fail;
- }
- if (res->ai_next) {
- PyErr_SetString(socket_error,
- "sockaddr resolved to multiple addresses");
- goto fail;
- }
- switch (res->ai_family) {
- case AF_INET:
- {
- if (PyTuple_GET_SIZE(sa) != 2) {
- PyErr_SetString(socket_error,
- "IPv4 sockaddr must be 2 tuple");
- goto fail;
- }
- break;
- }
+ PyObject *sa = (PyObject *)NULL;
+ int flags;
+ char *hostp;
+ int port, flowinfo, scope_id;
+ char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
+ struct addrinfo hints, *res = NULL;
+ int error;
+ PyObject *ret = (PyObject *)NULL;
+
+ flags = flowinfo = scope_id = 0;
+ if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
+ return NULL;
+ if (!PyTuple_Check(sa)) {
+ PyErr_SetString(PyExc_TypeError,
+ "getnameinfo() argument 1 must be a tuple");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(sa, "si|ii",
+ &hostp, &port, &flowinfo, &scope_id))
+ return NULL;
+ PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(hostp, pbuf, &hints, &res);
+ Py_END_ALLOW_THREADS
+ RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
+ if (error) {
+ set_gaierror(error);
+ goto fail;
+ }
+ if (res->ai_next) {
+ PyErr_SetString(socket_error,
+ "sockaddr resolved to multiple addresses");
+ goto fail;
+ }
+ switch (res->ai_family) {
+ case AF_INET:
+ {
+ if (PyTuple_GET_SIZE(sa) != 2) {
+ PyErr_SetString(socket_error,
+ "IPv4 sockaddr must be 2 tuple");
+ goto fail;
+ }
+ break;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6 *sin6;
- sin6 = (struct sockaddr_in6 *)res->ai_addr;
- sin6->sin6_flowinfo = flowinfo;
- sin6->sin6_scope_id = scope_id;
- break;
- }
-#endif
- }
- error = getnameinfo(res->ai_addr, res->ai_addrlen,
- hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
- if (error) {
- set_gaierror(error);
- goto fail;
- }
- ret = Py_BuildValue("ss", hbuf, pbuf);
+ case AF_INET6:
+ {
+ struct sockaddr_in6 *sin6;
+ sin6 = (struct sockaddr_in6 *)res->ai_addr;
+ sin6->sin6_flowinfo = flowinfo;
+ sin6->sin6_scope_id = scope_id;
+ break;
+ }
+#endif
+ }
+ error = getnameinfo(res->ai_addr, res->ai_addrlen,
+ hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
+ if (error) {
+ set_gaierror(error);
+ goto fail;
+ }
+ ret = Py_BuildValue("ss", hbuf, pbuf);
fail:
- if (res)
- freeaddrinfo(res);
- return ret;
+ if (res)
+ freeaddrinfo(res);
+ return ret;
}
PyDoc_STRVAR(getnameinfo_doc,
@@ -3999,12 +3999,12 @@ Get host and port for a sockaddr.");
static PyObject *
socket_getdefaulttimeout(PyObject *self)
{
- if (defaulttimeout < 0.0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyFloat_FromDouble(defaulttimeout);
+ if (defaulttimeout < 0.0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyFloat_FromDouble(defaulttimeout);
}
PyDoc_STRVAR(getdefaulttimeout_doc,
@@ -4017,24 +4017,24 @@ When the socket module is first imported, the default is None.");
static PyObject *
socket_setdefaulttimeout(PyObject *self, PyObject *arg)
{
- double timeout;
-
- if (arg == Py_None)
- timeout = -1.0;
- else {
- timeout = PyFloat_AsDouble(arg);
- if (timeout < 0.0) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_ValueError,
- "Timeout value out of range");
- return NULL;
- }
- }
-
- defaulttimeout = timeout;
-
- Py_INCREF(Py_None);
- return Py_None;
+ double timeout;
+
+ if (arg == Py_None)
+ timeout = -1.0;
+ else {
+ timeout = PyFloat_AsDouble(arg);
+ if (timeout < 0.0) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_ValueError,
+ "Timeout value out of range");
+ return NULL;
+ }
+ }
+
+ defaulttimeout = timeout;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setdefaulttimeout_doc,
@@ -4048,55 +4048,55 @@ When the socket module is first imported, the default is None.");
/* List of functions exported by this module. */
static PyMethodDef socket_methods[] = {
- {"gethostbyname", socket_gethostbyname,
- METH_VARARGS, gethostbyname_doc},
- {"gethostbyname_ex", socket_gethostbyname_ex,
- METH_VARARGS, ghbn_ex_doc},
- {"gethostbyaddr", socket_gethostbyaddr,
- METH_VARARGS, gethostbyaddr_doc},
- {"gethostname", socket_gethostname,
- METH_NOARGS, gethostname_doc},
- {"getservbyname", socket_getservbyname,
- METH_VARARGS, getservbyname_doc},
- {"getservbyport", socket_getservbyport,
- METH_VARARGS, getservbyport_doc},
- {"getprotobyname", socket_getprotobyname,
- METH_VARARGS, getprotobyname_doc},
+ {"gethostbyname", socket_gethostbyname,
+ METH_VARARGS, gethostbyname_doc},
+ {"gethostbyname_ex", socket_gethostbyname_ex,
+ METH_VARARGS, ghbn_ex_doc},
+ {"gethostbyaddr", socket_gethostbyaddr,
+ METH_VARARGS, gethostbyaddr_doc},
+ {"gethostname", socket_gethostname,
+ METH_NOARGS, gethostname_doc},
+ {"getservbyname", socket_getservbyname,
+ METH_VARARGS, getservbyname_doc},
+ {"getservbyport", socket_getservbyport,
+ METH_VARARGS, getservbyport_doc},
+ {"getprotobyname", socket_getprotobyname,
+ METH_VARARGS, getprotobyname_doc},
#ifndef NO_DUP
- {"dup", socket_dup,
- METH_O, dup_doc},
+ {"dup", socket_dup,
+ METH_O, dup_doc},
#endif
#ifdef HAVE_SOCKETPAIR
- {"socketpair", socket_socketpair,
- METH_VARARGS, socketpair_doc},
-#endif
- {"ntohs", socket_ntohs,
- METH_VARARGS, ntohs_doc},
- {"ntohl", socket_ntohl,
- METH_O, ntohl_doc},
- {"htons", socket_htons,
- METH_VARARGS, htons_doc},
- {"htonl", socket_htonl,
- METH_O, htonl_doc},
- {"inet_aton", socket_inet_aton,
- METH_VARARGS, inet_aton_doc},
- {"inet_ntoa", socket_inet_ntoa,
- METH_VARARGS, inet_ntoa_doc},
+ {"socketpair", socket_socketpair,
+ METH_VARARGS, socketpair_doc},
+#endif
+ {"ntohs", socket_ntohs,
+ METH_VARARGS, ntohs_doc},
+ {"ntohl", socket_ntohl,
+ METH_O, ntohl_doc},
+ {"htons", socket_htons,
+ METH_VARARGS, htons_doc},
+ {"htonl", socket_htonl,
+ METH_O, htonl_doc},
+ {"inet_aton", socket_inet_aton,
+ METH_VARARGS, inet_aton_doc},
+ {"inet_ntoa", socket_inet_ntoa,
+ METH_VARARGS, inet_ntoa_doc},
#ifdef HAVE_INET_PTON
- {"inet_pton", socket_inet_pton,
- METH_VARARGS, inet_pton_doc},
- {"inet_ntop", socket_inet_ntop,
- METH_VARARGS, inet_ntop_doc},
-#endif
- {"getaddrinfo", socket_getaddrinfo,
- METH_VARARGS, getaddrinfo_doc},
- {"getnameinfo", socket_getnameinfo,
- METH_VARARGS, getnameinfo_doc},
- {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
- METH_NOARGS, getdefaulttimeout_doc},
- {"setdefaulttimeout", socket_setdefaulttimeout,
- METH_O, setdefaulttimeout_doc},
- {NULL, NULL} /* Sentinel */
+ {"inet_pton", socket_inet_pton,
+ METH_VARARGS, inet_pton_doc},
+ {"inet_ntop", socket_inet_ntop,
+ METH_VARARGS, inet_ntop_doc},
+#endif
+ {"getaddrinfo", socket_getaddrinfo,
+ METH_VARARGS, getaddrinfo_doc},
+ {"getnameinfo", socket_getnameinfo,
+ METH_VARARGS, getnameinfo_doc},
+ {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
+ METH_NOARGS, getdefaulttimeout_doc},
+ {"setdefaulttimeout", socket_setdefaulttimeout,
+ METH_O, setdefaulttimeout_doc},
+ {NULL, NULL} /* Sentinel */
};
@@ -4108,34 +4108,34 @@ static PyMethodDef socket_methods[] = {
static void
os_cleanup(void)
{
- WSACleanup();
+ WSACleanup();
}
static int
os_init(void)
{
- WSADATA WSAData;
- int ret;
- ret = WSAStartup(0x0101, &WSAData);
- switch (ret) {
- case 0: /* No error */
- Py_AtExit(os_cleanup);
- return 1; /* Success */
- case WSASYSNOTREADY:
- PyErr_SetString(PyExc_ImportError,
- "WSAStartup failed: network not ready");
- break;
- case WSAVERNOTSUPPORTED:
- case WSAEINVAL:
- PyErr_SetString(
- PyExc_ImportError,
- "WSAStartup failed: requested version not supported");
- break;
- default:
- PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
- break;
- }
- return 0; /* Failure */
+ WSADATA WSAData;
+ int ret;
+ ret = WSAStartup(0x0101, &WSAData);
+ switch (ret) {
+ case 0: /* No error */
+ Py_AtExit(os_cleanup);
+ return 1; /* Success */
+ case WSASYSNOTREADY:
+ PyErr_SetString(PyExc_ImportError,
+ "WSAStartup failed: network not ready");
+ break;
+ case WSAVERNOTSUPPORTED:
+ case WSAEINVAL:
+ PyErr_SetString(
+ PyExc_ImportError,
+ "WSAStartup failed: requested version not supported");
+ break;
+ default:
+ PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
+ break;
+ }
+ return 0; /* Failure */
}
#endif /* MS_WINDOWS */
@@ -4150,18 +4150,18 @@ static int
os_init(void)
{
#ifndef PYCC_GCC
- int rc = sock_init();
+ int rc = sock_init();
- if (rc == 0) {
- return 1; /* Success */
- }
+ if (rc == 0) {
+ return 1; /* Success */
+ }
- PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno());
+ PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno());
- return 0; /* Failure */
+ return 0; /* Failure */
#else
- /* No need to initialise sockets with GCC/EMX */
- return 1; /* Success */
+ /* No need to initialise sockets with GCC/EMX */
+ return 1; /* Success */
#endif
}
@@ -4172,7 +4172,7 @@ os_init(void)
static int
os_init(void)
{
- return 1; /* Success */
+ return 1; /* Success */
}
#endif
@@ -4182,8 +4182,8 @@ os_init(void)
static
PySocketModule_APIObject PySocketModuleAPI =
{
- &sock_type,
- NULL
+ &sock_type,
+ NULL
};
@@ -4203,931 +4203,931 @@ PyDoc_STRVAR(socket_doc,
See the socket module for documentation.");
static struct PyModuleDef socketmodule = {
- PyModuleDef_HEAD_INIT,
- PySocket_MODULE_NAME,
- socket_doc,
- -1,
- socket_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ PySocket_MODULE_NAME,
+ socket_doc,
+ -1,
+ socket_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__socket(void)
{
- PyObject *m, *has_ipv6;
-
- if (!os_init())
- return NULL;
-
- Py_TYPE(&sock_type) = &PyType_Type;
- m = PyModule_Create(&socketmodule);
- if (m == NULL)
- return NULL;
-
- socket_error = PyErr_NewException("socket.error",
- PyExc_IOError, NULL);
- if (socket_error == NULL)
- return NULL;
- PySocketModuleAPI.error = socket_error;
- Py_INCREF(socket_error);
- PyModule_AddObject(m, "error", socket_error);
- socket_herror = PyErr_NewException("socket.herror",
- socket_error, NULL);
- if (socket_herror == NULL)
- return NULL;
- Py_INCREF(socket_herror);
- PyModule_AddObject(m, "herror", socket_herror);
- socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
- NULL);
- if (socket_gaierror == NULL)
- return NULL;
- Py_INCREF(socket_gaierror);
- PyModule_AddObject(m, "gaierror", socket_gaierror);
- socket_timeout = PyErr_NewException("socket.timeout",
- socket_error, NULL);
- if (socket_timeout == NULL)
- return NULL;
- Py_INCREF(socket_timeout);
- PyModule_AddObject(m, "timeout", socket_timeout);
- Py_INCREF((PyObject *)&sock_type);
- if (PyModule_AddObject(m, "SocketType",
- (PyObject *)&sock_type) != 0)
- return NULL;
- Py_INCREF((PyObject *)&sock_type);
- if (PyModule_AddObject(m, "socket",
- (PyObject *)&sock_type) != 0)
- return NULL;
+ PyObject *m, *has_ipv6;
+
+ if (!os_init())
+ return NULL;
+
+ Py_TYPE(&sock_type) = &PyType_Type;
+ m = PyModule_Create(&socketmodule);
+ if (m == NULL)
+ return NULL;
+
+ socket_error = PyErr_NewException("socket.error",
+ PyExc_IOError, NULL);
+ if (socket_error == NULL)
+ return NULL;
+ PySocketModuleAPI.error = socket_error;
+ Py_INCREF(socket_error);
+ PyModule_AddObject(m, "error", socket_error);
+ socket_herror = PyErr_NewException("socket.herror",
+ socket_error, NULL);
+ if (socket_herror == NULL)
+ return NULL;
+ Py_INCREF(socket_herror);
+ PyModule_AddObject(m, "herror", socket_herror);
+ socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
+ NULL);
+ if (socket_gaierror == NULL)
+ return NULL;
+ Py_INCREF(socket_gaierror);
+ PyModule_AddObject(m, "gaierror", socket_gaierror);
+ socket_timeout = PyErr_NewException("socket.timeout",
+ socket_error, NULL);
+ if (socket_timeout == NULL)
+ return NULL;
+ Py_INCREF(socket_timeout);
+ PyModule_AddObject(m, "timeout", socket_timeout);
+ Py_INCREF((PyObject *)&sock_type);
+ if (PyModule_AddObject(m, "SocketType",
+ (PyObject *)&sock_type) != 0)
+ return NULL;
+ Py_INCREF((PyObject *)&sock_type);
+ if (PyModule_AddObject(m, "socket",
+ (PyObject *)&sock_type) != 0)
+ return NULL;
#ifdef ENABLE_IPV6
- has_ipv6 = Py_True;
+ has_ipv6 = Py_True;
#else
- has_ipv6 = Py_False;
+ has_ipv6 = Py_False;
#endif
- Py_INCREF(has_ipv6);
- PyModule_AddObject(m, "has_ipv6", has_ipv6);
+ Py_INCREF(has_ipv6);
+ PyModule_AddObject(m, "has_ipv6", has_ipv6);
- /* Export C API */
- if (PyModule_AddObject(m, PySocket_CAPI_NAME,
- PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
- ) != 0)
- return NULL;
+ /* Export C API */
+ if (PyModule_AddObject(m, PySocket_CAPI_NAME,
+ PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
+ ) != 0)
+ return NULL;
- /* Address families (we only support AF_INET and AF_UNIX) */
+ /* Address families (we only support AF_INET and AF_UNIX) */
#ifdef AF_UNSPEC
- PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
+ PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
#endif
- PyModule_AddIntConstant(m, "AF_INET", AF_INET);
+ PyModule_AddIntConstant(m, "AF_INET", AF_INET);
#ifdef AF_INET6
- PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
+ PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
#endif /* AF_INET6 */
#if defined(AF_UNIX)
- PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
+ PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
#endif /* AF_UNIX */
#ifdef AF_AX25
- /* Amateur Radio AX.25 */
- PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
+ /* Amateur Radio AX.25 */
+ PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
#endif
#ifdef AF_IPX
- PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
+ PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
#endif
#ifdef AF_APPLETALK
- /* Appletalk DDP */
- PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
+ /* Appletalk DDP */
+ PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
#endif
#ifdef AF_NETROM
- /* Amateur radio NetROM */
- PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
+ /* Amateur radio NetROM */
+ PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
#endif
#ifdef AF_BRIDGE
- /* Multiprotocol bridge */
- PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
+ /* Multiprotocol bridge */
+ PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
#endif
#ifdef AF_ATMPVC
- /* ATM PVCs */
- PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
+ /* ATM PVCs */
+ PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
#endif
#ifdef AF_AAL5
- /* Reserved for Werner's ATM */
- PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
+ /* Reserved for Werner's ATM */
+ PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
#endif
#ifdef AF_X25
- /* Reserved for X.25 project */
- PyModule_AddIntConstant(m, "AF_X25", AF_X25);
+ /* Reserved for X.25 project */
+ PyModule_AddIntConstant(m, "AF_X25", AF_X25);
#endif
#ifdef AF_INET6
- PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
+ PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
#endif
#ifdef AF_ROSE
- /* Amateur Radio X.25 PLP */
- PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
+ /* Amateur Radio X.25 PLP */
+ PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
#endif
#ifdef AF_DECnet
- /* Reserved for DECnet project */
- PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
+ /* Reserved for DECnet project */
+ PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
#endif
#ifdef AF_NETBEUI
- /* Reserved for 802.2LLC project */
- PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
+ /* Reserved for 802.2LLC project */
+ PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
#endif
#ifdef AF_SECURITY
- /* Security callback pseudo AF */
- PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
+ /* Security callback pseudo AF */
+ PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
#endif
#ifdef AF_KEY
- /* PF_KEY key management API */
- PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
+ /* PF_KEY key management API */
+ PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
#endif
#ifdef AF_NETLINK
- /* */
- PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
- PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
+ /* */
+ PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
+ PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
#ifdef NETLINK_SKIP
- PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
+ PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
#endif
#ifdef NETLINK_W1
- PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
+ PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
#endif
- PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
- PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
+ PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
+ PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
#ifdef NETLINK_TCPDIAG
- PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
+ PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
#endif
#ifdef NETLINK_NFLOG
- PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
+ PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
#endif
#ifdef NETLINK_XFRM
- PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
+ PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
#endif
#ifdef NETLINK_ARPD
- PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
+ PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
#endif
#ifdef NETLINK_ROUTE6
- PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
+ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
#endif
- PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
+ PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
#ifdef NETLINK_DNRTMSG
- PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
+ PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
#endif
#ifdef NETLINK_TAPBASE
- PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
+ PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
#endif
#endif /* AF_NETLINK */
#ifdef AF_ROUTE
- /* Alias to emulate 4.4BSD */
- PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
+ /* Alias to emulate 4.4BSD */
+ PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
#endif
#ifdef AF_ASH
- /* Ash */
- PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
+ /* Ash */
+ PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
#endif
#ifdef AF_ECONET
- /* Acorn Econet */
- PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
+ /* Acorn Econet */
+ PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
#endif
#ifdef AF_ATMSVC
- /* ATM SVCs */
- PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
+ /* ATM SVCs */
+ PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
#endif
#ifdef AF_SNA
- /* Linux SNA Project (nutters!) */
- PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
+ /* Linux SNA Project (nutters!) */
+ PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
#endif
#ifdef AF_IRDA
- /* IRDA sockets */
- PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
+ /* IRDA sockets */
+ PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
#endif
#ifdef AF_PPPOX
- /* PPPoX sockets */
- PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
+ /* PPPoX sockets */
+ PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
#endif
#ifdef AF_WANPIPE
- /* Wanpipe API Sockets */
- PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
+ /* Wanpipe API Sockets */
+ PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
#endif
#ifdef AF_LLC
- /* Linux LLC */
- PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
+ /* Linux LLC */
+ PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
#endif
#ifdef USE_BLUETOOTH
- PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
- PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
- PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
- PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
- PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
+ PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
+ PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
+ PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
+ PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
+ PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
#if !defined(__FreeBSD__)
- PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
- PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
- PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
+ PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
+ PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
+ PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
#endif
- PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
- PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
- PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
+ PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
+ PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
+ PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
- PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
- PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
- PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
- PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
- PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
- PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
- PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
- PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
+ PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
+ PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
+ PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
+ PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
+ PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
+ PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
+ PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
+ PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
+ PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
#endif
#ifdef HAVE_LINUX_TIPC_H
- PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
-
- /* for addresses */
- PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
- PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
- PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
-
- PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
- PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
- PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
-
- /* for setsockopt() */
- PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
- PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
- PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
- TIPC_DEST_DROPPABLE);
- PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
-
- PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
- TIPC_LOW_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
- TIPC_MEDIUM_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
- TIPC_HIGH_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
- TIPC_CRITICAL_IMPORTANCE);
-
- /* for subscriptions */
- PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
- PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
+ PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
+
+ /* for addresses */
+ PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
+ PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
+ PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
+
+ PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
+ PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
+ PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
+
+ /* for setsockopt() */
+ PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
+ PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
+ PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
+ TIPC_DEST_DROPPABLE);
+ PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
+
+ PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
+ TIPC_LOW_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
+ TIPC_MEDIUM_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
+ TIPC_HIGH_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
+ TIPC_CRITICAL_IMPORTANCE);
+
+ /* for subscriptions */
+ PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
+ PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
#ifdef TIPC_SUB_CANCEL
- /* doesn't seem to be available everywhere */
- PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
+ /* doesn't seem to be available everywhere */
+ PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
#endif
- PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
- PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
- PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
- PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
- PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
- PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
+ PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
+ PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
+ PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
+ PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
+ PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
+ PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
#endif
- /* Socket types */
- PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
- PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
+ /* Socket types */
+ PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
+ PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
/* We have incomplete socket support. */
- PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
- PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
+ PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
+ PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
#if defined(SOCK_RDM)
- PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
+ PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
#endif
-#ifdef SO_DEBUG
- PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
+#ifdef SO_DEBUG
+ PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
#endif
-#ifdef SO_ACCEPTCONN
- PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
+#ifdef SO_ACCEPTCONN
+ PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
#endif
-#ifdef SO_REUSEADDR
- PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
+#ifdef SO_REUSEADDR
+ PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
#endif
#ifdef SO_EXCLUSIVEADDRUSE
- PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
+ PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
#endif
-#ifdef SO_KEEPALIVE
- PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
+#ifdef SO_KEEPALIVE
+ PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
#endif
-#ifdef SO_DONTROUTE
- PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
+#ifdef SO_DONTROUTE
+ PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
#endif
-#ifdef SO_BROADCAST
- PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
+#ifdef SO_BROADCAST
+ PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
#endif
-#ifdef SO_USELOOPBACK
- PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
+#ifdef SO_USELOOPBACK
+ PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
#endif
-#ifdef SO_LINGER
- PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
+#ifdef SO_LINGER
+ PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
#endif
-#ifdef SO_OOBINLINE
- PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
+#ifdef SO_OOBINLINE
+ PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
#endif
-#ifdef SO_REUSEPORT
- PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
+#ifdef SO_REUSEPORT
+ PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
#endif
-#ifdef SO_SNDBUF
- PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
+#ifdef SO_SNDBUF
+ PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
#endif
-#ifdef SO_RCVBUF
- PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
+#ifdef SO_RCVBUF
+ PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
#endif
-#ifdef SO_SNDLOWAT
- PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
+#ifdef SO_SNDLOWAT
+ PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
#endif
-#ifdef SO_RCVLOWAT
- PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
+#ifdef SO_RCVLOWAT
+ PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
#endif
-#ifdef SO_SNDTIMEO
- PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
+#ifdef SO_SNDTIMEO
+ PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
#endif
-#ifdef SO_RCVTIMEO
- PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
+#ifdef SO_RCVTIMEO
+ PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
#endif
-#ifdef SO_ERROR
- PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
+#ifdef SO_ERROR
+ PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
#endif
-#ifdef SO_TYPE
- PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
+#ifdef SO_TYPE
+ PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
#endif
-#ifdef SO_SETFIB
- PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
+#ifdef SO_SETFIB
+ PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
#endif
- /* Maximum number of connections for "listen" */
-#ifdef SOMAXCONN
- PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
+ /* Maximum number of connections for "listen" */
+#ifdef SOMAXCONN
+ PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
#else
- PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
+ PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
#endif
- /* Flags for send, recv */
-#ifdef MSG_OOB
- PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
+ /* Flags for send, recv */
+#ifdef MSG_OOB
+ PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
#endif
-#ifdef MSG_PEEK
- PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
+#ifdef MSG_PEEK
+ PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
#endif
-#ifdef MSG_DONTROUTE
- PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
+#ifdef MSG_DONTROUTE
+ PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
#endif
-#ifdef MSG_DONTWAIT
- PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
+#ifdef MSG_DONTWAIT
+ PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
#endif
-#ifdef MSG_EOR
- PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
+#ifdef MSG_EOR
+ PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
#endif
-#ifdef MSG_TRUNC
- PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
+#ifdef MSG_TRUNC
+ PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
#endif
-#ifdef MSG_CTRUNC
- PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
+#ifdef MSG_CTRUNC
+ PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
#endif
-#ifdef MSG_WAITALL
- PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
+#ifdef MSG_WAITALL
+ PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
#endif
-#ifdef MSG_BTAG
- PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
+#ifdef MSG_BTAG
+ PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
#endif
-#ifdef MSG_ETAG
- PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
+#ifdef MSG_ETAG
+ PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
#endif
- /* Protocol level and numbers, usable for [gs]etsockopt */
-#ifdef SOL_SOCKET
- PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
+ /* Protocol level and numbers, usable for [gs]etsockopt */
+#ifdef SOL_SOCKET
+ PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
#endif
-#ifdef SOL_IP
- PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
+#ifdef SOL_IP
+ PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
#else
- PyModule_AddIntConstant(m, "SOL_IP", 0);
+ PyModule_AddIntConstant(m, "SOL_IP", 0);
#endif
-#ifdef SOL_IPX
- PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
+#ifdef SOL_IPX
+ PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
#endif
-#ifdef SOL_AX25
- PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
+#ifdef SOL_AX25
+ PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
#endif
-#ifdef SOL_ATALK
- PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
+#ifdef SOL_ATALK
+ PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
#endif
-#ifdef SOL_NETROM
- PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
+#ifdef SOL_NETROM
+ PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
#endif
-#ifdef SOL_ROSE
- PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
+#ifdef SOL_ROSE
+ PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
#endif
-#ifdef SOL_TCP
- PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
+#ifdef SOL_TCP
+ PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
#else
- PyModule_AddIntConstant(m, "SOL_TCP", 6);
+ PyModule_AddIntConstant(m, "SOL_TCP", 6);
#endif
-#ifdef SOL_UDP
- PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
+#ifdef SOL_UDP
+ PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
#else
- PyModule_AddIntConstant(m, "SOL_UDP", 17);
+ PyModule_AddIntConstant(m, "SOL_UDP", 17);
#endif
-#ifdef IPPROTO_IP
- PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
+#ifdef IPPROTO_IP
+ PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
+ PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
#endif
-#ifdef IPPROTO_HOPOPTS
- PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
+#ifdef IPPROTO_HOPOPTS
+ PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
#endif
-#ifdef IPPROTO_ICMP
- PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
+#ifdef IPPROTO_ICMP
+ PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
+ PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
#endif
-#ifdef IPPROTO_IGMP
- PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
+#ifdef IPPROTO_IGMP
+ PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
#endif
-#ifdef IPPROTO_GGP
- PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
+#ifdef IPPROTO_GGP
+ PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
#endif
-#ifdef IPPROTO_IPV4
- PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
+#ifdef IPPROTO_IPV4
+ PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
#endif
-#ifdef IPPROTO_IPV6
- PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
+#ifdef IPPROTO_IPV6
+ PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
#endif
-#ifdef IPPROTO_IPIP
- PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
+#ifdef IPPROTO_IPIP
+ PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
#endif
-#ifdef IPPROTO_TCP
- PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
+#ifdef IPPROTO_TCP
+ PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
+ PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
#endif
-#ifdef IPPROTO_EGP
- PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
+#ifdef IPPROTO_EGP
+ PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
#endif
-#ifdef IPPROTO_PUP
- PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
+#ifdef IPPROTO_PUP
+ PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
#endif
-#ifdef IPPROTO_UDP
- PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
+#ifdef IPPROTO_UDP
+ PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
+ PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
#endif
-#ifdef IPPROTO_IDP
- PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
+#ifdef IPPROTO_IDP
+ PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
#endif
-#ifdef IPPROTO_HELLO
- PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
+#ifdef IPPROTO_HELLO
+ PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
#endif
-#ifdef IPPROTO_ND
- PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
+#ifdef IPPROTO_ND
+ PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
#endif
-#ifdef IPPROTO_TP
- PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
+#ifdef IPPROTO_TP
+ PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
#endif
-#ifdef IPPROTO_IPV6
- PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
+#ifdef IPPROTO_IPV6
+ PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
#endif
-#ifdef IPPROTO_ROUTING
- PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
+#ifdef IPPROTO_ROUTING
+ PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
#endif
-#ifdef IPPROTO_FRAGMENT
- PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
+#ifdef IPPROTO_FRAGMENT
+ PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
#endif
-#ifdef IPPROTO_RSVP
- PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
+#ifdef IPPROTO_RSVP
+ PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
#endif
-#ifdef IPPROTO_GRE
- PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
+#ifdef IPPROTO_GRE
+ PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
#endif
-#ifdef IPPROTO_ESP
- PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
+#ifdef IPPROTO_ESP
+ PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
#endif
-#ifdef IPPROTO_AH
- PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
+#ifdef IPPROTO_AH
+ PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
#endif
-#ifdef IPPROTO_MOBILE
- PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
+#ifdef IPPROTO_MOBILE
+ PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
#endif
-#ifdef IPPROTO_ICMPV6
- PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
+#ifdef IPPROTO_ICMPV6
+ PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
#endif
-#ifdef IPPROTO_NONE
- PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
+#ifdef IPPROTO_NONE
+ PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
#endif
-#ifdef IPPROTO_DSTOPTS
- PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
+#ifdef IPPROTO_DSTOPTS
+ PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
#endif
-#ifdef IPPROTO_XTP
- PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
+#ifdef IPPROTO_XTP
+ PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
#endif
-#ifdef IPPROTO_EON
- PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
+#ifdef IPPROTO_EON
+ PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
#endif
-#ifdef IPPROTO_PIM
- PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
+#ifdef IPPROTO_PIM
+ PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
#endif
-#ifdef IPPROTO_IPCOMP
- PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
+#ifdef IPPROTO_IPCOMP
+ PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
#endif
-#ifdef IPPROTO_VRRP
- PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
+#ifdef IPPROTO_VRRP
+ PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
#endif
-#ifdef IPPROTO_BIP
- PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
+#ifdef IPPROTO_BIP
+ PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
#endif
/**/
-#ifdef IPPROTO_RAW
- PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
+#ifdef IPPROTO_RAW
+ PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
#else
- PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
+ PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
#endif
-#ifdef IPPROTO_MAX
- PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
+#ifdef IPPROTO_MAX
+ PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
#endif
- /* Some port configuration */
-#ifdef IPPORT_RESERVED
- PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
+ /* Some port configuration */
+#ifdef IPPORT_RESERVED
+ PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
#else
- PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
+ PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
#endif
-#ifdef IPPORT_USERRESERVED
- PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
+#ifdef IPPORT_USERRESERVED
+ PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
#else
- PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
+ PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
#endif
- /* Some reserved IP v.4 addresses */
-#ifdef INADDR_ANY
- PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
+ /* Some reserved IP v.4 addresses */
+#ifdef INADDR_ANY
+ PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
#else
- PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
+ PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
#endif
-#ifdef INADDR_BROADCAST
- PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
+#ifdef INADDR_BROADCAST
+ PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
#else
- PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
+ PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
#endif
-#ifdef INADDR_LOOPBACK
- PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
+#ifdef INADDR_LOOPBACK
+ PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
#else
- PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
+ PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
#endif
-#ifdef INADDR_UNSPEC_GROUP
- PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
+#ifdef INADDR_UNSPEC_GROUP
+ PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
#else
- PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
+ PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
#endif
-#ifdef INADDR_ALLHOSTS_GROUP
- PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
- INADDR_ALLHOSTS_GROUP);
+#ifdef INADDR_ALLHOSTS_GROUP
+ PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
+ INADDR_ALLHOSTS_GROUP);
#else
- PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
+ PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
#endif
-#ifdef INADDR_MAX_LOCAL_GROUP
- PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
- INADDR_MAX_LOCAL_GROUP);
+#ifdef INADDR_MAX_LOCAL_GROUP
+ PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
+ INADDR_MAX_LOCAL_GROUP);
#else
- PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
+ PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
#endif
-#ifdef INADDR_NONE
- PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
+#ifdef INADDR_NONE
+ PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
#else
- PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
+ PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
#endif
- /* IPv4 [gs]etsockopt options */
-#ifdef IP_OPTIONS
- PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
+ /* IPv4 [gs]etsockopt options */
+#ifdef IP_OPTIONS
+ PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
#endif
-#ifdef IP_HDRINCL
- PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
+#ifdef IP_HDRINCL
+ PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
#endif
-#ifdef IP_TOS
- PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
+#ifdef IP_TOS
+ PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
#endif
-#ifdef IP_TTL
- PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
+#ifdef IP_TTL
+ PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
#endif
-#ifdef IP_RECVOPTS
- PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
+#ifdef IP_RECVOPTS
+ PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
#endif
-#ifdef IP_RECVRETOPTS
- PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
+#ifdef IP_RECVRETOPTS
+ PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
#endif
-#ifdef IP_RECVDSTADDR
- PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
+#ifdef IP_RECVDSTADDR
+ PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
#endif
-#ifdef IP_RETOPTS
- PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
+#ifdef IP_RETOPTS
+ PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
#endif
-#ifdef IP_MULTICAST_IF
- PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
+#ifdef IP_MULTICAST_IF
+ PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
#endif
-#ifdef IP_MULTICAST_TTL
- PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
+#ifdef IP_MULTICAST_TTL
+ PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
#endif
-#ifdef IP_MULTICAST_LOOP
- PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
+#ifdef IP_MULTICAST_LOOP
+ PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
#endif
-#ifdef IP_ADD_MEMBERSHIP
- PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
+#ifdef IP_ADD_MEMBERSHIP
+ PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
#endif
-#ifdef IP_DROP_MEMBERSHIP
- PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
+#ifdef IP_DROP_MEMBERSHIP
+ PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
#endif
-#ifdef IP_DEFAULT_MULTICAST_TTL
- PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
- IP_DEFAULT_MULTICAST_TTL);
+#ifdef IP_DEFAULT_MULTICAST_TTL
+ PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
+ IP_DEFAULT_MULTICAST_TTL);
#endif
-#ifdef IP_DEFAULT_MULTICAST_LOOP
- PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
- IP_DEFAULT_MULTICAST_LOOP);
+#ifdef IP_DEFAULT_MULTICAST_LOOP
+ PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
+ IP_DEFAULT_MULTICAST_LOOP);
#endif
-#ifdef IP_MAX_MEMBERSHIPS
- PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
+#ifdef IP_MAX_MEMBERSHIPS
+ PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
#endif
- /* IPv6 [gs]etsockopt options, defined in RFC2553 */
-#ifdef IPV6_JOIN_GROUP
- PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
+ /* IPv6 [gs]etsockopt options, defined in RFC2553 */
+#ifdef IPV6_JOIN_GROUP
+ PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
#endif
-#ifdef IPV6_LEAVE_GROUP
- PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
+#ifdef IPV6_LEAVE_GROUP
+ PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
#endif
-#ifdef IPV6_MULTICAST_HOPS
- PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
+#ifdef IPV6_MULTICAST_HOPS
+ PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
#endif
-#ifdef IPV6_MULTICAST_IF
- PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
+#ifdef IPV6_MULTICAST_IF
+ PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
#endif
-#ifdef IPV6_MULTICAST_LOOP
- PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
+#ifdef IPV6_MULTICAST_LOOP
+ PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
#endif
-#ifdef IPV6_UNICAST_HOPS
- PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
+#ifdef IPV6_UNICAST_HOPS
+ PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
#endif
- /* Additional IPV6 socket options, defined in RFC 3493 */
+ /* Additional IPV6 socket options, defined in RFC 3493 */
#ifdef IPV6_V6ONLY
- PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
+ PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
#endif
- /* Advanced IPV6 socket options, from RFC 3542 */
+ /* Advanced IPV6 socket options, from RFC 3542 */
#ifdef IPV6_CHECKSUM
- PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
+ PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
#endif
#ifdef IPV6_DONTFRAG
- PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
+ PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
#endif
#ifdef IPV6_DSTOPTS
- PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
+ PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
#endif
#ifdef IPV6_HOPLIMIT
- PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
+ PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
#endif
#ifdef IPV6_HOPOPTS
- PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
+ PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
#endif
#ifdef IPV6_NEXTHOP
- PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
+ PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
#endif
#ifdef IPV6_PATHMTU
- PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
+ PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
#endif
#ifdef IPV6_PKTINFO
- PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
+ PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
#endif
#ifdef IPV6_RECVDSTOPTS
- PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
+ PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
#endif
#ifdef IPV6_RECVHOPLIMIT
- PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
+ PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
#endif
#ifdef IPV6_RECVHOPOPTS
- PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
+ PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
#endif
#ifdef IPV6_RECVPKTINFO
- PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
+ PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
#endif
#ifdef IPV6_RECVRTHDR
- PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
+ PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
#endif
#ifdef IPV6_RECVTCLASS
- PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
+ PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
#endif
#ifdef IPV6_RTHDR
- PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
+ PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
#endif
#ifdef IPV6_RTHDRDSTOPTS
- PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
+ PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
#endif
#ifdef IPV6_RTHDR_TYPE_0
- PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
+ PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
#endif
#ifdef IPV6_RECVPATHMTU
- PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
+ PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
#endif
#ifdef IPV6_TCLASS
- PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
+ PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
#endif
#ifdef IPV6_USE_MIN_MTU
- PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
+ PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
#endif
- /* TCP options */
-#ifdef TCP_NODELAY
- PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
+ /* TCP options */
+#ifdef TCP_NODELAY
+ PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
#endif
-#ifdef TCP_MAXSEG
- PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
+#ifdef TCP_MAXSEG
+ PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
#endif
-#ifdef TCP_CORK
- PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
+#ifdef TCP_CORK
+ PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
#endif
-#ifdef TCP_KEEPIDLE
- PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
+#ifdef TCP_KEEPIDLE
+ PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
#endif
-#ifdef TCP_KEEPINTVL
- PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
+#ifdef TCP_KEEPINTVL
+ PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
#endif
-#ifdef TCP_KEEPCNT
- PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
+#ifdef TCP_KEEPCNT
+ PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
#endif
-#ifdef TCP_SYNCNT
- PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
+#ifdef TCP_SYNCNT
+ PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
#endif
-#ifdef TCP_LINGER2
- PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
+#ifdef TCP_LINGER2
+ PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
#endif
-#ifdef TCP_DEFER_ACCEPT
- PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
+#ifdef TCP_DEFER_ACCEPT
+ PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
#endif
-#ifdef TCP_WINDOW_CLAMP
- PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
+#ifdef TCP_WINDOW_CLAMP
+ PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
#endif
-#ifdef TCP_INFO
- PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
+#ifdef TCP_INFO
+ PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
#endif
-#ifdef TCP_QUICKACK
- PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
+#ifdef TCP_QUICKACK
+ PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
#endif
- /* IPX options */
-#ifdef IPX_TYPE
- PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
+ /* IPX options */
+#ifdef IPX_TYPE
+ PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
#endif
- /* get{addr,name}info parameters */
+ /* get{addr,name}info parameters */
#ifdef EAI_ADDRFAMILY
- PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
+ PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
#endif
#ifdef EAI_AGAIN
- PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
+ PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
#endif
#ifdef EAI_BADFLAGS
- PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
+ PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
#endif
#ifdef EAI_FAIL
- PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
+ PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
#endif
#ifdef EAI_FAMILY
- PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
+ PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
#endif
#ifdef EAI_MEMORY
- PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
+ PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
#endif
#ifdef EAI_NODATA
- PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
+ PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
#endif
#ifdef EAI_NONAME
- PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
+ PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
#endif
#ifdef EAI_OVERFLOW
- PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
+ PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
#endif
#ifdef EAI_SERVICE
- PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
+ PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
#endif
#ifdef EAI_SOCKTYPE
- PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
+ PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
#endif
#ifdef EAI_SYSTEM
- PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
+ PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
#endif
#ifdef EAI_BADHINTS
- PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
+ PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
#endif
#ifdef EAI_PROTOCOL
- PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
+ PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
#endif
#ifdef EAI_MAX
- PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
+ PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
#endif
#ifdef AI_PASSIVE
- PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
+ PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
#endif
#ifdef AI_CANONNAME
- PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
+ PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
#endif
#ifdef AI_NUMERICHOST
- PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
+ PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
#endif
#ifdef AI_NUMERICSERV
- PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
+ PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
#endif
#ifdef AI_MASK
- PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
+ PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
#endif
#ifdef AI_ALL
- PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
+ PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
#endif
#ifdef AI_V4MAPPED_CFG
- PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
+ PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
#endif
#ifdef AI_ADDRCONFIG
- PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
+ PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
#endif
#ifdef AI_V4MAPPED
- PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
+ PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
#endif
#ifdef AI_DEFAULT
- PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
+ PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
#endif
#ifdef NI_MAXHOST
- PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
+ PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
#endif
#ifdef NI_MAXSERV
- PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
+ PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
#endif
#ifdef NI_NOFQDN
- PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
+ PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
#endif
#ifdef NI_NUMERICHOST
- PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
+ PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
#endif
#ifdef NI_NAMEREQD
- PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
+ PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
#endif
#ifdef NI_NUMERICSERV
- PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
+ PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
#endif
#ifdef NI_DGRAM
- PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
+ PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
#endif
- /* shutdown() parameters */
+ /* shutdown() parameters */
#ifdef SHUT_RD
- PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
+ PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
#elif defined(SD_RECEIVE)
- PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
+ PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
#else
- PyModule_AddIntConstant(m, "SHUT_RD", 0);
+ PyModule_AddIntConstant(m, "SHUT_RD", 0);
#endif
#ifdef SHUT_WR
- PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
+ PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
#elif defined(SD_SEND)
- PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
+ PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
#else
- PyModule_AddIntConstant(m, "SHUT_WR", 1);
+ PyModule_AddIntConstant(m, "SHUT_WR", 1);
#endif
#ifdef SHUT_RDWR
- PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
+ PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
#elif defined(SD_BOTH)
- PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
+ PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
#else
- PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
+ PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
#endif
#ifdef SIO_RCVALL
- {
- DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
- const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
- int i;
- for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
- PyObject *tmp;
- tmp = PyLong_FromUnsignedLong(codes[i]);
- if (tmp == NULL)
- return NULL;
- PyModule_AddObject(m, names[i], tmp);
- }
- }
- PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
- PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
- PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
+ {
+ DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
+ const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
+ int i;
+ for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
+ PyObject *tmp;
+ tmp = PyLong_FromUnsignedLong(codes[i]);
+ if (tmp == NULL)
+ return NULL;
+ PyModule_AddObject(m, names[i], tmp);
+ }
+ }
+ PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
+ PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
+ PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
#ifdef RCVALL_IPLEVEL
- PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
+ PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
#endif
#ifdef RCVALL_MAX
- PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
+ PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
#endif
#endif /* _MSTCPIP_ */
- /* Initialize gethostbyname lock */
+ /* Initialize gethostbyname lock */
#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
- netdb_lock = PyThread_allocate_lock();
+ netdb_lock = PyThread_allocate_lock();
#endif
- return m;
+ return m;
}
@@ -5140,34 +5140,34 @@ PyInit__socket(void)
int
inet_pton(int af, const char *src, void *dst)
{
- if (af == AF_INET) {
+ if (af == AF_INET) {
#if (SIZEOF_INT != 4)
#error "Not sure if in_addr_t exists and int is not 32-bits."
#endif
- unsigned int packed_addr;
- packed_addr = inet_addr(src);
- if (packed_addr == INADDR_NONE)
- return 0;
- memcpy(dst, &packed_addr, 4);
- return 1;
- }
- /* Should set errno to EAFNOSUPPORT */
- return -1;
+ unsigned int packed_addr;
+ packed_addr = inet_addr(src);
+ if (packed_addr == INADDR_NONE)
+ return 0;
+ memcpy(dst, &packed_addr, 4);
+ return 1;
+ }
+ /* Should set errno to EAFNOSUPPORT */
+ return -1;
}
const char *
inet_ntop(int af, const void *src, char *dst, socklen_t size)
{
- if (af == AF_INET) {
- struct in_addr packed_addr;
- if (size < 16)
- /* Should set errno to ENOSPC. */
- return NULL;
- memcpy(&packed_addr, src, sizeof(packed_addr));
- return strncpy(dst, inet_ntoa(packed_addr), size);
- }
- /* Should set errno to EAFNOSUPPORT */
- return NULL;
+ if (af == AF_INET) {
+ struct in_addr packed_addr;
+ if (size < 16)
+ /* Should set errno to ENOSPC. */
+ return NULL;
+ memcpy(&packed_addr, src, sizeof(packed_addr));
+ return strncpy(dst, inet_ntoa(packed_addr), size);
+ }
+ /* Should set errno to EAFNOSUPPORT */
+ return NULL;
}
#endif
diff --git a/Modules/socketmodule.h b/Modules/socketmodule.h
index 65bc8ad..49ac9d0 100644
--- a/Modules/socketmodule.h
+++ b/Modules/socketmodule.h
@@ -17,7 +17,7 @@
# include <ws2tcpip.h>
/* VC6 is shipped with old platform headers, and does not have MSTcpIP.h
* Separate SDKs have all the functions we want, but older ones don't have
- * any version information.
+ * any version information.
* I use SIO_GET_MULTICAST_FILTER to detect a decent SDK.
*/
# ifdef SIO_GET_MULTICAST_FILTER
@@ -76,44 +76,44 @@ extern "C" {
#endif
/* Python module and C API name */
-#define PySocket_MODULE_NAME "_socket"
-#define PySocket_CAPI_NAME "CAPI"
-#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME
+#define PySocket_MODULE_NAME "_socket"
+#define PySocket_CAPI_NAME "CAPI"
+#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME
/* Abstract the socket file descriptor type */
#ifdef MS_WINDOWS
typedef SOCKET SOCKET_T;
-# ifdef MS_WIN64
-# define SIZEOF_SOCKET_T 8
-# else
-# define SIZEOF_SOCKET_T 4
-# endif
+# ifdef MS_WIN64
+# define SIZEOF_SOCKET_T 8
+# else
+# define SIZEOF_SOCKET_T 4
+# endif
#else
typedef int SOCKET_T;
-# define SIZEOF_SOCKET_T SIZEOF_INT
+# define SIZEOF_SOCKET_T SIZEOF_INT
#endif
/* Socket address */
typedef union sock_addr {
- struct sockaddr_in in;
+ struct sockaddr_in in;
#ifdef AF_UNIX
- struct sockaddr_un un;
+ struct sockaddr_un un;
#endif
#ifdef AF_NETLINK
- struct sockaddr_nl nl;
+ struct sockaddr_nl nl;
#endif
#ifdef ENABLE_IPV6
- struct sockaddr_in6 in6;
- struct sockaddr_storage storage;
+ struct sockaddr_in6 in6;
+ struct sockaddr_storage storage;
#endif
#ifdef HAVE_BLUETOOTH_BLUETOOTH_H
- struct sockaddr_l2 bt_l2;
- struct sockaddr_rc bt_rc;
- struct sockaddr_sco bt_sco;
- struct sockaddr_hci bt_hci;
+ struct sockaddr_l2 bt_l2;
+ struct sockaddr_rc bt_rc;
+ struct sockaddr_sco bt_sco;
+ struct sockaddr_hci bt_hci;
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- struct sockaddr_ll ll;
+ struct sockaddr_ll ll;
#endif
} sock_addr_t;
@@ -122,16 +122,16 @@ typedef union sock_addr {
arguments properly. */
typedef struct {
- PyObject_HEAD
- SOCKET_T sock_fd; /* Socket file descriptor */
- int sock_family; /* Address family, e.g., AF_INET */
- int sock_type; /* Socket type, e.g., SOCK_STREAM */
- int sock_proto; /* Protocol type, usually 0 */
- PyObject *(*errorhandler)(void); /* Error handler; checks
- errno, returns NULL and
- sets a Python exception */
- double sock_timeout; /* Operation timeout in seconds;
- 0.0 means non-blocking */
+ PyObject_HEAD
+ SOCKET_T sock_fd; /* Socket file descriptor */
+ int sock_family; /* Address family, e.g., AF_INET */
+ int sock_type; /* Socket type, e.g., SOCK_STREAM */
+ int sock_proto; /* Protocol type, usually 0 */
+ PyObject *(*errorhandler)(void); /* Error handler; checks
+ errno, returns NULL and
+ sets a Python exception */
+ double sock_timeout; /* Operation timeout in seconds;
+ 0.0 means non-blocking */
} PySocketSockObject;
/* --- C API ----------------------------------------------------*/
@@ -139,7 +139,7 @@ typedef struct {
/* Short explanation of what this C API export mechanism does
and how it works:
- The _ssl module needs access to the type object defined in
+ The _ssl module needs access to the type object defined in
the _socket module. Since cross-DLL linking introduces a lot of
problems on many platforms, the "trick" is to wrap the
C API of a module in a struct which then gets exported to
@@ -161,24 +161,24 @@ typedef struct {
Load _socket module and its C API; this sets up the global
PySocketModule:
-
- if (PySocketModule_ImportModuleAndAPI())
- return;
+
+ if (PySocketModule_ImportModuleAndAPI())
+ return;
Now use the C API as if it were defined in the using
module:
- if (!PyArg_ParseTuple(args, "O!|zz:ssl",
+ if (!PyArg_ParseTuple(args, "O!|zz:ssl",
- PySocketModule.Sock_Type,
+ PySocketModule.Sock_Type,
- (PyObject*)&Sock,
- &key_file, &cert_file))
- return NULL;
+ (PyObject*)&Sock,
+ &key_file, &cert_file))
+ return NULL;
Support could easily be extended to export more C APIs/symbols
- this way. Currently, only the type object is exported,
+ this way. Currently, only the type object is exported,
other candidates would be socket constructors and socket
access functions.
@@ -186,8 +186,8 @@ typedef struct {
/* C API for usage by other Python modules */
typedef struct {
- PyTypeObject *Sock_Type;
- PyObject *error;
+ PyTypeObject *Sock_Type;
+ PyObject *error;
} PySocketModule_APIObject;
#define PySocketModule_ImportModuleAndAPI() PyCapsule_Import(PySocket_CAPSULE_NAME, 1)
diff --git a/Modules/spwdmodule.c b/Modules/spwdmodule.c
index 422ab03..da452e9 100644
--- a/Modules/spwdmodule.c
+++ b/Modules/spwdmodule.c
@@ -27,16 +27,16 @@ You have to be root to be able to use this module.");
#if defined(HAVE_GETSPNAM) || defined(HAVE_GETSPENT)
static PyStructSequence_Field struct_spwd_type_fields[] = {
- {"sp_nam", "login name"},
- {"sp_pwd", "encrypted password"},
- {"sp_lstchg", "date of last change"},
- {"sp_min", "min #days between changes"},
- {"sp_max", "max #days between changes"},
- {"sp_warn", "#days before pw expires to warn user about it"},
- {"sp_inact", "#days after pw expires until account is blocked"},
- {"sp_expire", "#days since 1970-01-01 until account is disabled"},
- {"sp_flag", "reserved"},
- {0}
+ {"sp_nam", "login name"},
+ {"sp_pwd", "encrypted password"},
+ {"sp_lstchg", "date of last change"},
+ {"sp_min", "min #days between changes"},
+ {"sp_max", "max #days between changes"},
+ {"sp_warn", "#days before pw expires to warn user about it"},
+ {"sp_inact", "#days after pw expires until account is blocked"},
+ {"sp_expire", "#days since 1970-01-01 until account is disabled"},
+ {"sp_flag", "reserved"},
+ {0}
};
PyDoc_STRVAR(struct_spwd__doc__,
@@ -46,10 +46,10 @@ This object may be accessed either as a 9-tuple of\n\
or via the object attributes as named in the above tuple.");
static PyStructSequence_Desc struct_spwd_type_desc = {
- "spwd.struct_spwd",
- struct_spwd__doc__,
- struct_spwd_type_fields,
- 9,
+ "spwd.struct_spwd",
+ struct_spwd__doc__,
+ struct_spwd_type_fields,
+ 9,
};
static int initialized;
@@ -60,43 +60,43 @@ static void
sets(PyObject *v, int i, const char* val)
{
if (val) {
- PyObject *o = PyUnicode_DecodeFSDefault(val);
- PyStructSequence_SET_ITEM(v, i, o);
+ PyObject *o = PyUnicode_DecodeFSDefault(val);
+ PyStructSequence_SET_ITEM(v, i, o);
} else {
- PyStructSequence_SET_ITEM(v, i, Py_None);
- Py_INCREF(Py_None);
+ PyStructSequence_SET_ITEM(v, i, Py_None);
+ Py_INCREF(Py_None);
}
}
static PyObject *mkspent(struct spwd *p)
{
- int setIndex = 0;
- PyObject *v = PyStructSequence_New(&StructSpwdType);
- if (v == NULL)
- return NULL;
+ int setIndex = 0;
+ PyObject *v = PyStructSequence_New(&StructSpwdType);
+ if (v == NULL)
+ return NULL;
#define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
#define SETS(i,val) sets(v, i, val)
- SETS(setIndex++, p->sp_namp);
- SETS(setIndex++, p->sp_pwdp);
- SETI(setIndex++, p->sp_lstchg);
- SETI(setIndex++, p->sp_min);
- SETI(setIndex++, p->sp_max);
- SETI(setIndex++, p->sp_warn);
- SETI(setIndex++, p->sp_inact);
- SETI(setIndex++, p->sp_expire);
- SETI(setIndex++, p->sp_flag);
+ SETS(setIndex++, p->sp_namp);
+ SETS(setIndex++, p->sp_pwdp);
+ SETI(setIndex++, p->sp_lstchg);
+ SETI(setIndex++, p->sp_min);
+ SETI(setIndex++, p->sp_max);
+ SETI(setIndex++, p->sp_warn);
+ SETI(setIndex++, p->sp_inact);
+ SETI(setIndex++, p->sp_expire);
+ SETI(setIndex++, p->sp_flag);
#undef SETS
#undef SETI
- if (PyErr_Occurred()) {
- Py_DECREF(v);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_DECREF(v);
+ return NULL;
+ }
- return v;
+ return v;
}
#endif /* HAVE_GETSPNAM || HAVE_GETSPENT */
@@ -112,26 +112,26 @@ See spwd.__doc__ for more on shadow password database entries.");
static PyObject* spwd_getspnam(PyObject *self, PyObject *args)
{
- char *name;
- struct spwd *p;
- PyObject *arg, *bytes, *retval = NULL;
-
- if (!PyArg_ParseTuple(args, "U:getspnam", &arg))
- return NULL;
- if ((bytes = PyUnicode_AsEncodedString(arg,
- Py_FileSystemDefaultEncoding,
- "surrogateescape")) == NULL)
- return NULL;
- if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
- goto out;
- if ((p = getspnam(name)) == NULL) {
- PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
- goto out;
- }
- retval = mkspent(p);
+ char *name;
+ struct spwd *p;
+ PyObject *arg, *bytes, *retval = NULL;
+
+ if (!PyArg_ParseTuple(args, "U:getspnam", &arg))
+ return NULL;
+ if ((bytes = PyUnicode_AsEncodedString(arg,
+ Py_FileSystemDefaultEncoding,
+ "surrogateescape")) == NULL)
+ return NULL;
+ if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
+ goto out;
+ if ((p = getspnam(name)) == NULL) {
+ PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
+ goto out;
+ }
+ retval = mkspent(p);
out:
- Py_DECREF(bytes);
- return retval;
+ Py_DECREF(bytes);
+ return retval;
}
#endif /* HAVE_GETSPNAM */
@@ -147,63 +147,63 @@ See spwd.__doc__ for more on shadow password database entries.");
static PyObject *
spwd_getspall(PyObject *self, PyObject *args)
{
- PyObject *d;
- struct spwd *p;
- if ((d = PyList_New(0)) == NULL)
- return NULL;
- setspent();
- while ((p = getspent()) != NULL) {
- PyObject *v = mkspent(p);
- if (v == NULL || PyList_Append(d, v) != 0) {
- Py_XDECREF(v);
- Py_DECREF(d);
- endspent();
- return NULL;
- }
- Py_DECREF(v);
- }
- endspent();
- return d;
+ PyObject *d;
+ struct spwd *p;
+ if ((d = PyList_New(0)) == NULL)
+ return NULL;
+ setspent();
+ while ((p = getspent()) != NULL) {
+ PyObject *v = mkspent(p);
+ if (v == NULL || PyList_Append(d, v) != 0) {
+ Py_XDECREF(v);
+ Py_DECREF(d);
+ endspent();
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ endspent();
+ return d;
}
#endif /* HAVE_GETSPENT */
static PyMethodDef spwd_methods[] = {
-#ifdef HAVE_GETSPNAM
- {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__},
+#ifdef HAVE_GETSPNAM
+ {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__},
#endif
#ifdef HAVE_GETSPENT
- {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__},
+ {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef spwdmodule = {
- PyModuleDef_HEAD_INIT,
- "spwd",
- spwd__doc__,
- -1,
- spwd_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "spwd",
+ spwd__doc__,
+ -1,
+ spwd_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_spwd(void)
{
- PyObject *m;
- m=PyModule_Create(&spwdmodule);
- if (m == NULL)
- return NULL;
- if (!initialized)
- PyStructSequence_InitType(&StructSpwdType,
- &struct_spwd_type_desc);
- Py_INCREF((PyObject *) &StructSpwdType);
- PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType);
- initialized = 1;
- return m;
+ PyObject *m;
+ m=PyModule_Create(&spwdmodule);
+ if (m == NULL)
+ return NULL;
+ if (!initialized)
+ PyStructSequence_InitType(&StructSpwdType,
+ &struct_spwd_type_desc);
+ Py_INCREF((PyObject *) &StructSpwdType);
+ PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType);
+ initialized = 1;
+ return m;
}
diff --git a/Modules/symtablemodule.c b/Modules/symtablemodule.c
index f66b598..3f281d2 100644
--- a/Modules/symtablemodule.c
+++ b/Modules/symtablemodule.c
@@ -8,93 +8,93 @@
static PyObject *
symtable_symtable(PyObject *self, PyObject *args)
{
- struct symtable *st;
- PyObject *t;
+ struct symtable *st;
+ PyObject *t;
- char *str;
- char *filename;
- char *startstr;
- int start;
+ char *str;
+ char *filename;
+ char *startstr;
+ int start;
- if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename,
- &startstr))
- return NULL;
- if (strcmp(startstr, "exec") == 0)
- start = Py_file_input;
- else if (strcmp(startstr, "eval") == 0)
- start = Py_eval_input;
- else if (strcmp(startstr, "single") == 0)
- start = Py_single_input;
- else {
- PyErr_SetString(PyExc_ValueError,
- "symtable() arg 3 must be 'exec' or 'eval' or 'single'");
- return NULL;
- }
- st = Py_SymtableString(str, filename, start);
- if (st == NULL)
- return NULL;
- t = st->st_blocks;
- Py_INCREF(t);
- PyMem_Free((void *)st->st_future);
- PySymtable_Free(st);
- return t;
+ if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename,
+ &startstr))
+ return NULL;
+ if (strcmp(startstr, "exec") == 0)
+ start = Py_file_input;
+ else if (strcmp(startstr, "eval") == 0)
+ start = Py_eval_input;
+ else if (strcmp(startstr, "single") == 0)
+ start = Py_single_input;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "symtable() arg 3 must be 'exec' or 'eval' or 'single'");
+ return NULL;
+ }
+ st = Py_SymtableString(str, filename, start);
+ if (st == NULL)
+ return NULL;
+ t = st->st_blocks;
+ Py_INCREF(t);
+ PyMem_Free((void *)st->st_future);
+ PySymtable_Free(st);
+ return t;
}
static PyMethodDef symtable_methods[] = {
- {"symtable", symtable_symtable, METH_VARARGS,
- PyDoc_STR("Return symbol and scope dictionaries"
- " used internally by compiler.")},
- {NULL, NULL} /* sentinel */
+ {"symtable", symtable_symtable, METH_VARARGS,
+ PyDoc_STR("Return symbol and scope dictionaries"
+ " used internally by compiler.")},
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef symtablemodule = {
- PyModuleDef_HEAD_INIT,
- "_symtable",
- NULL,
- -1,
- symtable_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "_symtable",
+ NULL,
+ -1,
+ symtable_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit__symtable(void)
{
- PyObject *m;
+ PyObject *m;
- m = PyModule_Create(&symtablemodule);
- if (m == NULL)
- return NULL;
- PyModule_AddIntConstant(m, "USE", USE);
- PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL);
- PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL);
- PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM);
- PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE);
- PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS);
- PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT);
- PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND);
+ m = PyModule_Create(&symtablemodule);
+ if (m == NULL)
+ return NULL;
+ PyModule_AddIntConstant(m, "USE", USE);
+ PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL);
+ PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL);
+ PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM);
+ PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE);
+ PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS);
+ PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT);
+ PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND);
- PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock);
- PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock);
- PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock);
+ PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock);
+ PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock);
+ PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock);
- PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR);
- PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL);
+ PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR);
+ PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL);
- PyModule_AddIntConstant(m, "LOCAL", LOCAL);
- PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT);
- PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT);
- PyModule_AddIntConstant(m, "FREE", FREE);
- PyModule_AddIntConstant(m, "CELL", CELL);
+ PyModule_AddIntConstant(m, "LOCAL", LOCAL);
+ PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT);
+ PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT);
+ PyModule_AddIntConstant(m, "FREE", FREE);
+ PyModule_AddIntConstant(m, "CELL", CELL);
- PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET);
- PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK);
+ PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET);
+ PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK);
- if (PyErr_Occurred()) {
- Py_DECREF(m);
- m = 0;
- }
- return m;
+ if (PyErr_Occurred()) {
+ Py_DECREF(m);
+ m = 0;
+ }
+ return m;
}
diff --git a/Modules/syslogmodule.c b/Modules/syslogmodule.c
index e605df2..1842dc9 100644
--- a/Modules/syslogmodule.c
+++ b/Modules/syslogmodule.c
@@ -4,20 +4,20 @@ Cathedral City, California Republic, United States of America.
All Rights Reserved
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
+both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
-not be used in advertising or publicity pertaining to distribution
+not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE BE LIABLE FOR ANY SPECIAL,
-INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
-FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE BE LIABLE FOR ANY SPECIAL,
+INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/
@@ -55,272 +55,272 @@ Revision history:
#include <syslog.h>
/* only one instance, only one syslog, so globals should be ok */
-static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */
+static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */
static char S_log_open = 0;
static PyObject *
syslog_get_argv(void)
{
- /* Figure out what to use for as the program "ident" for openlog().
- * This swallows exceptions and continues rather than failing out,
- * because the syslog module can still be used because openlog(3)
- * is optional.
- */
-
- Py_ssize_t argv_len;
- PyObject *scriptobj;
- char *atslash;
- PyObject *argv = PySys_GetObject("argv");
-
- if (argv == NULL) {
- return(NULL);
- }
-
- argv_len = PyList_Size(argv);
- if (argv_len == -1) {
- PyErr_Clear();
- return(NULL);
- }
- if (argv_len == 0) {
- return(NULL);
- }
-
- scriptobj = PyList_GetItem(argv, 0);
- if (!PyUnicode_Check(scriptobj)) {
- return(NULL);
- }
- if (PyUnicode_GET_SIZE(scriptobj) == 0) {
- return(NULL);
- }
-
- atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP);
- if (atslash) {
- return(PyUnicode_FromString(atslash + 1));
- } else {
- Py_INCREF(scriptobj);
- return(scriptobj);
- }
-
- return(NULL);
+ /* Figure out what to use for as the program "ident" for openlog().
+ * This swallows exceptions and continues rather than failing out,
+ * because the syslog module can still be used because openlog(3)
+ * is optional.
+ */
+
+ Py_ssize_t argv_len;
+ PyObject *scriptobj;
+ char *atslash;
+ PyObject *argv = PySys_GetObject("argv");
+
+ if (argv == NULL) {
+ return(NULL);
+ }
+
+ argv_len = PyList_Size(argv);
+ if (argv_len == -1) {
+ PyErr_Clear();
+ return(NULL);
+ }
+ if (argv_len == 0) {
+ return(NULL);
+ }
+
+ scriptobj = PyList_GetItem(argv, 0);
+ if (!PyUnicode_Check(scriptobj)) {
+ return(NULL);
+ }
+ if (PyUnicode_GET_SIZE(scriptobj) == 0) {
+ return(NULL);
+ }
+
+ atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP);
+ if (atslash) {
+ return(PyUnicode_FromString(atslash + 1));
+ } else {
+ Py_INCREF(scriptobj);
+ return(scriptobj);
+ }
+
+ return(NULL);
}
-static PyObject *
+static PyObject *
syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds)
{
- long logopt = 0;
- long facility = LOG_USER;
- PyObject *new_S_ident_o = NULL;
- static char *keywords[] = {"ident", "logoption", "facility", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds,
- "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility))
- return NULL;
-
- if (new_S_ident_o) {
- Py_INCREF(new_S_ident_o);
- }
-
- /* get sys.argv[0] or NULL if we can't for some reason */
- if (!new_S_ident_o) {
- new_S_ident_o = syslog_get_argv();
- }
-
- Py_XDECREF(S_ident_o);
- S_ident_o = new_S_ident_o;
-
- /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not
- * make a copy, and syslog(3) later uses it. We can't garbagecollect it
- * If NULL, just let openlog figure it out (probably using C argv[0]).
- */
-
- openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility);
- S_log_open = 1;
-
- Py_INCREF(Py_None);
- return Py_None;
+ long logopt = 0;
+ long facility = LOG_USER;
+ PyObject *new_S_ident_o = NULL;
+ static char *keywords[] = {"ident", "logoption", "facility", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds,
+ "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility))
+ return NULL;
+
+ if (new_S_ident_o) {
+ Py_INCREF(new_S_ident_o);
+ }
+
+ /* get sys.argv[0] or NULL if we can't for some reason */
+ if (!new_S_ident_o) {
+ new_S_ident_o = syslog_get_argv();
+ }
+
+ Py_XDECREF(S_ident_o);
+ S_ident_o = new_S_ident_o;
+
+ /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not
+ * make a copy, and syslog(3) later uses it. We can't garbagecollect it
+ * If NULL, just let openlog figure it out (probably using C argv[0]).
+ */
+
+ openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility);
+ S_log_open = 1;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_syslog(PyObject * self, PyObject * args)
{
- PyObject *message_object;
- const char *message;
- int priority = LOG_INFO;
-
- if (!PyArg_ParseTuple(args, "iU;[priority,] message string",
- &priority, &message_object)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "U;[priority,] message string",
- &message_object))
- return NULL;
- }
-
- message = _PyUnicode_AsString(message_object);
- if (message == NULL)
- return NULL;
-
- /* if log is not opened, open it now */
- if (!S_log_open) {
- PyObject *openargs;
-
- /* Continue even if PyTuple_New fails, because openlog(3) is optional.
- * So, we can still do loggin in the unlikely event things are so hosed
- * that we can't do this tuple.
- */
- if ((openargs = PyTuple_New(0))) {
- PyObject *openlog_ret = syslog_openlog(self, openargs, NULL);
- Py_XDECREF(openlog_ret);
- Py_DECREF(openargs);
- }
- }
-
- Py_BEGIN_ALLOW_THREADS;
- syslog(priority, "%s", message);
- Py_END_ALLOW_THREADS;
- Py_RETURN_NONE;
+ PyObject *message_object;
+ const char *message;
+ int priority = LOG_INFO;
+
+ if (!PyArg_ParseTuple(args, "iU;[priority,] message string",
+ &priority, &message_object)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "U;[priority,] message string",
+ &message_object))
+ return NULL;
+ }
+
+ message = _PyUnicode_AsString(message_object);
+ if (message == NULL)
+ return NULL;
+
+ /* if log is not opened, open it now */
+ if (!S_log_open) {
+ PyObject *openargs;
+
+ /* Continue even if PyTuple_New fails, because openlog(3) is optional.
+ * So, we can still do loggin in the unlikely event things are so hosed
+ * that we can't do this tuple.
+ */
+ if ((openargs = PyTuple_New(0))) {
+ PyObject *openlog_ret = syslog_openlog(self, openargs, NULL);
+ Py_XDECREF(openlog_ret);
+ Py_DECREF(openargs);
+ }
+ }
+
+ Py_BEGIN_ALLOW_THREADS;
+ syslog(priority, "%s", message);
+ Py_END_ALLOW_THREADS;
+ Py_RETURN_NONE;
}
-static PyObject *
+static PyObject *
syslog_closelog(PyObject *self, PyObject *unused)
{
- if (S_log_open) {
- closelog();
- Py_XDECREF(S_ident_o);
- S_ident_o = NULL;
- S_log_open = 0;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (S_log_open) {
+ closelog();
+ Py_XDECREF(S_ident_o);
+ S_ident_o = NULL;
+ S_log_open = 0;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_setlogmask(PyObject *self, PyObject *args)
{
- long maskpri, omaskpri;
+ long maskpri, omaskpri;
- if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
- return NULL;
- omaskpri = setlogmask(maskpri);
- return PyLong_FromLong(omaskpri);
+ if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
+ return NULL;
+ omaskpri = setlogmask(maskpri);
+ return PyLong_FromLong(omaskpri);
}
-static PyObject *
+static PyObject *
syslog_log_mask(PyObject *self, PyObject *args)
{
- long mask;
- long pri;
- if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri))
- return NULL;
- mask = LOG_MASK(pri);
- return PyLong_FromLong(mask);
+ long mask;
+ long pri;
+ if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri))
+ return NULL;
+ mask = LOG_MASK(pri);
+ return PyLong_FromLong(mask);
}
-static PyObject *
+static PyObject *
syslog_log_upto(PyObject *self, PyObject *args)
{
- long mask;
- long pri;
- if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri))
- return NULL;
- mask = LOG_UPTO(pri);
- return PyLong_FromLong(mask);
+ long mask;
+ long pri;
+ if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri))
+ return NULL;
+ mask = LOG_UPTO(pri);
+ return PyLong_FromLong(mask);
}
/* List of functions defined in the module */
static PyMethodDef syslog_methods[] = {
- {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS},
- {"closelog", syslog_closelog, METH_NOARGS},
- {"syslog", syslog_syslog, METH_VARARGS},
- {"setlogmask", syslog_setlogmask, METH_VARARGS},
- {"LOG_MASK", syslog_log_mask, METH_VARARGS},
- {"LOG_UPTO", syslog_log_upto, METH_VARARGS},
- {NULL, NULL, 0}
+ {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS},
+ {"closelog", syslog_closelog, METH_NOARGS},
+ {"syslog", syslog_syslog, METH_VARARGS},
+ {"setlogmask", syslog_setlogmask, METH_VARARGS},
+ {"LOG_MASK", syslog_log_mask, METH_VARARGS},
+ {"LOG_UPTO", syslog_log_upto, METH_VARARGS},
+ {NULL, NULL, 0}
};
/* Initialization function for the module */
static struct PyModuleDef syslogmodule = {
- PyModuleDef_HEAD_INIT,
- "syslog",
- NULL,
- -1,
- syslog_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "syslog",
+ NULL,
+ -1,
+ syslog_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_syslog(void)
{
- PyObject *m;
-
- /* Create the module and add the functions */
- m = PyModule_Create(&syslogmodule);
- if (m == NULL)
- return NULL;
-
- /* Add some symbolic constants to the module */
-
- /* Priorities */
- PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG);
- PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT);
- PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT);
- PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR);
- PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING);
- PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE);
- PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO);
- PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG);
-
- /* openlog() option flags */
- PyModule_AddIntConstant(m, "LOG_PID", LOG_PID);
- PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS);
- PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY);
+ PyObject *m;
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&syslogmodule);
+ if (m == NULL)
+ return NULL;
+
+ /* Add some symbolic constants to the module */
+
+ /* Priorities */
+ PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG);
+ PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT);
+ PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT);
+ PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR);
+ PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING);
+ PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE);
+ PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO);
+ PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG);
+
+ /* openlog() option flags */
+ PyModule_AddIntConstant(m, "LOG_PID", LOG_PID);
+ PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS);
+ PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY);
#ifdef LOG_NOWAIT
- PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT);
+ PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT);
#endif
#ifdef LOG_PERROR
- PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR);
+ PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR);
#endif
- /* Facilities */
- PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN);
- PyModule_AddIntConstant(m, "LOG_USER", LOG_USER);
- PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL);
- PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON);
- PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH);
- PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR);
- PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0);
- PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1);
- PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2);
- PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3);
- PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4);
- PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5);
- PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6);
- PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7);
+ /* Facilities */
+ PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN);
+ PyModule_AddIntConstant(m, "LOG_USER", LOG_USER);
+ PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL);
+ PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON);
+ PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH);
+ PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR);
+ PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0);
+ PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1);
+ PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2);
+ PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3);
+ PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4);
+ PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5);
+ PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6);
+ PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7);
#ifndef LOG_SYSLOG
-#define LOG_SYSLOG LOG_DAEMON
+#define LOG_SYSLOG LOG_DAEMON
#endif
#ifndef LOG_NEWS
-#define LOG_NEWS LOG_MAIL
+#define LOG_NEWS LOG_MAIL
#endif
#ifndef LOG_UUCP
-#define LOG_UUCP LOG_MAIL
+#define LOG_UUCP LOG_MAIL
#endif
#ifndef LOG_CRON
-#define LOG_CRON LOG_DAEMON
+#define LOG_CRON LOG_DAEMON
#endif
- PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG);
- PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON);
- PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP);
- PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS);
- return m;
+ PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG);
+ PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON);
+ PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP);
+ PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS);
+ return m;
}
diff --git a/Modules/termios.c b/Modules/termios.c
index efdeeaa..f370c46 100644
--- a/Modules/termios.c
+++ b/Modules/termios.c
@@ -42,14 +42,14 @@ static PyObject *TermiosError;
static int fdconv(PyObject* obj, void* p)
{
- int fd;
-
- fd = PyObject_AsFileDescriptor(obj);
- if (fd >= 0) {
- *(int*)p = fd;
- return 1;
- }
- return 0;
+ int fd;
+
+ fd = PyObject_AsFileDescriptor(obj);
+ if (fd >= 0) {
+ *(int*)p = fd;
+ return 1;
+ }
+ return 0;
}
PyDoc_STRVAR(termios_tcgetattr__doc__,
@@ -66,67 +66,67 @@ in this module.");
static PyObject *
termios_tcgetattr(PyObject *self, PyObject *args)
{
- int fd;
- struct termios mode;
- PyObject *cc;
- speed_t ispeed, ospeed;
- PyObject *v;
- int i;
- char ch;
-
- if (!PyArg_ParseTuple(args, "O&:tcgetattr",
- fdconv, (void*)&fd))
- return NULL;
-
- if (tcgetattr(fd, &mode) == -1)
- return PyErr_SetFromErrno(TermiosError);
-
- ispeed = cfgetispeed(&mode);
- ospeed = cfgetospeed(&mode);
-
- cc = PyList_New(NCCS);
- if (cc == NULL)
- return NULL;
- for (i = 0; i < NCCS; i++) {
- ch = (char)mode.c_cc[i];
- v = PyBytes_FromStringAndSize(&ch, 1);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, i, v);
- }
-
- /* Convert the MIN and TIME slots to integer. On some systems, the
- MIN and TIME slots are the same as the EOF and EOL slots. So we
- only do this in noncanonical input mode. */
- if ((mode.c_lflag & ICANON) == 0) {
- v = PyLong_FromLong((long)mode.c_cc[VMIN]);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, VMIN, v);
- v = PyLong_FromLong((long)mode.c_cc[VTIME]);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, VTIME, v);
- }
-
- if (!(v = PyList_New(7)))
- goto err;
-
- PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag));
- PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag));
- PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag));
- PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag));
- PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed));
- PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed));
- PyList_SetItem(v, 6, cc);
- if (PyErr_Occurred()){
- Py_DECREF(v);
- goto err;
- }
- return v;
+ int fd;
+ struct termios mode;
+ PyObject *cc;
+ speed_t ispeed, ospeed;
+ PyObject *v;
+ int i;
+ char ch;
+
+ if (!PyArg_ParseTuple(args, "O&:tcgetattr",
+ fdconv, (void*)&fd))
+ return NULL;
+
+ if (tcgetattr(fd, &mode) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+
+ ispeed = cfgetispeed(&mode);
+ ospeed = cfgetospeed(&mode);
+
+ cc = PyList_New(NCCS);
+ if (cc == NULL)
+ return NULL;
+ for (i = 0; i < NCCS; i++) {
+ ch = (char)mode.c_cc[i];
+ v = PyBytes_FromStringAndSize(&ch, 1);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, i, v);
+ }
+
+ /* Convert the MIN and TIME slots to integer. On some systems, the
+ MIN and TIME slots are the same as the EOF and EOL slots. So we
+ only do this in noncanonical input mode. */
+ if ((mode.c_lflag & ICANON) == 0) {
+ v = PyLong_FromLong((long)mode.c_cc[VMIN]);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, VMIN, v);
+ v = PyLong_FromLong((long)mode.c_cc[VTIME]);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, VTIME, v);
+ }
+
+ if (!(v = PyList_New(7)))
+ goto err;
+
+ PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag));
+ PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag));
+ PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag));
+ PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag));
+ PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed));
+ PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed));
+ PyList_SetItem(v, 6, cc);
+ if (PyErr_Occurred()){
+ Py_DECREF(v);
+ goto err;
+ }
+ return v;
err:
- Py_DECREF(cc);
- return NULL;
+ Py_DECREF(cc);
+ return NULL;
}
PyDoc_STRVAR(termios_tcsetattr__doc__,
@@ -143,64 +143,64 @@ queued output and discarding all queued input. ");
static PyObject *
termios_tcsetattr(PyObject *self, PyObject *args)
{
- int fd, when;
- struct termios mode;
- speed_t ispeed, ospeed;
- PyObject *term, *cc, *v;
- int i;
-
- if (!PyArg_ParseTuple(args, "O&iO:tcsetattr",
- fdconv, &fd, &when, &term))
- return NULL;
- if (!PyList_Check(term) || PyList_Size(term) != 7) {
- PyErr_SetString(PyExc_TypeError,
- "tcsetattr, arg 3: must be 7 element list");
- return NULL;
- }
-
- /* Get the old mode, in case there are any hidden fields... */
- if (tcgetattr(fd, &mode) == -1)
- return PyErr_SetFromErrno(TermiosError);
- mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0));
- mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1));
- mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2));
- mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3));
- ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4));
- ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5));
- cc = PyList_GetItem(term, 6);
- if (PyErr_Occurred())
- return NULL;
-
- if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) {
- PyErr_Format(PyExc_TypeError,
- "tcsetattr: attributes[6] must be %d element list",
- NCCS);
- return NULL;
- }
-
- for (i = 0; i < NCCS; i++) {
- v = PyList_GetItem(cc, i);
-
- if (PyBytes_Check(v) && PyBytes_Size(v) == 1)
- mode.c_cc[i] = (cc_t) * PyBytes_AsString(v);
- else if (PyLong_Check(v))
- mode.c_cc[i] = (cc_t) PyLong_AsLong(v);
- else {
- PyErr_SetString(PyExc_TypeError,
+ int fd, when;
+ struct termios mode;
+ speed_t ispeed, ospeed;
+ PyObject *term, *cc, *v;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "O&iO:tcsetattr",
+ fdconv, &fd, &when, &term))
+ return NULL;
+ if (!PyList_Check(term) || PyList_Size(term) != 7) {
+ PyErr_SetString(PyExc_TypeError,
+ "tcsetattr, arg 3: must be 7 element list");
+ return NULL;
+ }
+
+ /* Get the old mode, in case there are any hidden fields... */
+ if (tcgetattr(fd, &mode) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+ mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0));
+ mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1));
+ mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2));
+ mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3));
+ ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4));
+ ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5));
+ cc = PyList_GetItem(term, 6);
+ if (PyErr_Occurred())
+ return NULL;
+
+ if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) {
+ PyErr_Format(PyExc_TypeError,
+ "tcsetattr: attributes[6] must be %d element list",
+ NCCS);
+ return NULL;
+ }
+
+ for (i = 0; i < NCCS; i++) {
+ v = PyList_GetItem(cc, i);
+
+ if (PyBytes_Check(v) && PyBytes_Size(v) == 1)
+ mode.c_cc[i] = (cc_t) * PyBytes_AsString(v);
+ else if (PyLong_Check(v))
+ mode.c_cc[i] = (cc_t) PyLong_AsLong(v);
+ else {
+ PyErr_SetString(PyExc_TypeError,
"tcsetattr: elements of attributes must be characters or integers");
- return NULL;
- }
- }
-
- if (cfsetispeed(&mode, (speed_t) ispeed) == -1)
- return PyErr_SetFromErrno(TermiosError);
- if (cfsetospeed(&mode, (speed_t) ospeed) == -1)
- return PyErr_SetFromErrno(TermiosError);
- if (tcsetattr(fd, when, &mode) == -1)
- return PyErr_SetFromErrno(TermiosError);
-
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
+ }
+ }
+
+ if (cfsetispeed(&mode, (speed_t) ispeed) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+ if (cfsetospeed(&mode, (speed_t) ospeed) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+ if (tcsetattr(fd, when, &mode) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcsendbreak__doc__,
@@ -213,16 +213,16 @@ has a system dependent meaning.");
static PyObject *
termios_tcsendbreak(PyObject *self, PyObject *args)
{
- int fd, duration;
+ int fd, duration;
- if (!PyArg_ParseTuple(args, "O&i:tcsendbreak",
- fdconv, &fd, &duration))
- return NULL;
- if (tcsendbreak(fd, duration) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&i:tcsendbreak",
+ fdconv, &fd, &duration))
+ return NULL;
+ if (tcsendbreak(fd, duration) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcdrain__doc__,
@@ -233,16 +233,16 @@ Wait until all output written to file descriptor fd has been transmitted.");
static PyObject *
termios_tcdrain(PyObject *self, PyObject *args)
{
- int fd;
+ int fd;
- if (!PyArg_ParseTuple(args, "O&:tcdrain",
- fdconv, &fd))
- return NULL;
- if (tcdrain(fd) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&:tcdrain",
+ fdconv, &fd))
+ return NULL;
+ if (tcdrain(fd) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcflush__doc__,
@@ -256,16 +256,16 @@ both queues. ");
static PyObject *
termios_tcflush(PyObject *self, PyObject *args)
{
- int fd, queue;
+ int fd, queue;
- if (!PyArg_ParseTuple(args, "O&i:tcflush",
- fdconv, &fd, &queue))
- return NULL;
- if (tcflush(fd, queue) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&i:tcflush",
+ fdconv, &fd, &queue))
+ return NULL;
+ if (tcflush(fd, queue) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcflow__doc__,
@@ -279,33 +279,33 @@ or termios.TCION to restart input.");
static PyObject *
termios_tcflow(PyObject *self, PyObject *args)
{
- int fd, action;
+ int fd, action;
- if (!PyArg_ParseTuple(args, "O&i:tcflow",
- fdconv, &fd, &action))
- return NULL;
- if (tcflow(fd, action) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&i:tcflow",
+ fdconv, &fd, &action))
+ return NULL;
+ if (tcflow(fd, action) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef termios_methods[] =
{
- {"tcgetattr", termios_tcgetattr,
- METH_VARARGS, termios_tcgetattr__doc__},
- {"tcsetattr", termios_tcsetattr,
- METH_VARARGS, termios_tcsetattr__doc__},
- {"tcsendbreak", termios_tcsendbreak,
- METH_VARARGS, termios_tcsendbreak__doc__},
- {"tcdrain", termios_tcdrain,
- METH_VARARGS, termios_tcdrain__doc__},
- {"tcflush", termios_tcflush,
- METH_VARARGS, termios_tcflush__doc__},
- {"tcflow", termios_tcflow,
- METH_VARARGS, termios_tcflow__doc__},
- {NULL, NULL}
+ {"tcgetattr", termios_tcgetattr,
+ METH_VARARGS, termios_tcgetattr__doc__},
+ {"tcsetattr", termios_tcsetattr,
+ METH_VARARGS, termios_tcsetattr__doc__},
+ {"tcsendbreak", termios_tcsendbreak,
+ METH_VARARGS, termios_tcsendbreak__doc__},
+ {"tcdrain", termios_tcdrain,
+ METH_VARARGS, termios_tcdrain__doc__},
+ {"tcflush", termios_tcflush,
+ METH_VARARGS, termios_tcflush__doc__},
+ {"tcflow", termios_tcflow,
+ METH_VARARGS, termios_tcflow__doc__},
+ {NULL, NULL}
};
@@ -318,622 +318,622 @@ static PyMethodDef termios_methods[] =
#endif
static struct constant {
- char *name;
- long value;
+ char *name;
+ long value;
} termios_constants[] = {
- /* cfgetospeed(), cfsetospeed() constants */
- {"B0", B0},
- {"B50", B50},
- {"B75", B75},
- {"B110", B110},
- {"B134", B134},
- {"B150", B150},
- {"B200", B200},
- {"B300", B300},
- {"B600", B600},
- {"B1200", B1200},
- {"B1800", B1800},
- {"B2400", B2400},
- {"B4800", B4800},
- {"B9600", B9600},
- {"B19200", B19200},
- {"B38400", B38400},
+ /* cfgetospeed(), cfsetospeed() constants */
+ {"B0", B0},
+ {"B50", B50},
+ {"B75", B75},
+ {"B110", B110},
+ {"B134", B134},
+ {"B150", B150},
+ {"B200", B200},
+ {"B300", B300},
+ {"B600", B600},
+ {"B1200", B1200},
+ {"B1800", B1800},
+ {"B2400", B2400},
+ {"B4800", B4800},
+ {"B9600", B9600},
+ {"B19200", B19200},
+ {"B38400", B38400},
#ifdef B57600
- {"B57600", B57600},
+ {"B57600", B57600},
#endif
#ifdef B115200
- {"B115200", B115200},
+ {"B115200", B115200},
#endif
#ifdef B230400
- {"B230400", B230400},
+ {"B230400", B230400},
#endif
#ifdef CBAUDEX
- {"CBAUDEX", CBAUDEX},
+ {"CBAUDEX", CBAUDEX},
#endif
- /* tcsetattr() constants */
- {"TCSANOW", TCSANOW},
- {"TCSADRAIN", TCSADRAIN},
- {"TCSAFLUSH", TCSAFLUSH},
+ /* tcsetattr() constants */
+ {"TCSANOW", TCSANOW},
+ {"TCSADRAIN", TCSADRAIN},
+ {"TCSAFLUSH", TCSAFLUSH},
#ifdef TCSASOFT
- {"TCSASOFT", TCSASOFT},
-#endif
-
- /* tcflush() constants */
- {"TCIFLUSH", TCIFLUSH},
- {"TCOFLUSH", TCOFLUSH},
- {"TCIOFLUSH", TCIOFLUSH},
-
- /* tcflow() constants */
- {"TCOOFF", TCOOFF},
- {"TCOON", TCOON},
- {"TCIOFF", TCIOFF},
- {"TCION", TCION},
-
- /* struct termios.c_iflag constants */
- {"IGNBRK", IGNBRK},
- {"BRKINT", BRKINT},
- {"IGNPAR", IGNPAR},
- {"PARMRK", PARMRK},
- {"INPCK", INPCK},
- {"ISTRIP", ISTRIP},
- {"INLCR", INLCR},
- {"IGNCR", IGNCR},
- {"ICRNL", ICRNL},
+ {"TCSASOFT", TCSASOFT},
+#endif
+
+ /* tcflush() constants */
+ {"TCIFLUSH", TCIFLUSH},
+ {"TCOFLUSH", TCOFLUSH},
+ {"TCIOFLUSH", TCIOFLUSH},
+
+ /* tcflow() constants */
+ {"TCOOFF", TCOOFF},
+ {"TCOON", TCOON},
+ {"TCIOFF", TCIOFF},
+ {"TCION", TCION},
+
+ /* struct termios.c_iflag constants */
+ {"IGNBRK", IGNBRK},
+ {"BRKINT", BRKINT},
+ {"IGNPAR", IGNPAR},
+ {"PARMRK", PARMRK},
+ {"INPCK", INPCK},
+ {"ISTRIP", ISTRIP},
+ {"INLCR", INLCR},
+ {"IGNCR", IGNCR},
+ {"ICRNL", ICRNL},
#ifdef IUCLC
- {"IUCLC", IUCLC},
+ {"IUCLC", IUCLC},
#endif
- {"IXON", IXON},
- {"IXANY", IXANY},
- {"IXOFF", IXOFF},
+ {"IXON", IXON},
+ {"IXANY", IXANY},
+ {"IXOFF", IXOFF},
#ifdef IMAXBEL
- {"IMAXBEL", IMAXBEL},
+ {"IMAXBEL", IMAXBEL},
#endif
- /* struct termios.c_oflag constants */
- {"OPOST", OPOST},
+ /* struct termios.c_oflag constants */
+ {"OPOST", OPOST},
#ifdef OLCUC
- {"OLCUC", OLCUC},
+ {"OLCUC", OLCUC},
#endif
#ifdef ONLCR
- {"ONLCR", ONLCR},
+ {"ONLCR", ONLCR},
#endif
#ifdef OCRNL
- {"OCRNL", OCRNL},
+ {"OCRNL", OCRNL},
#endif
#ifdef ONOCR
- {"ONOCR", ONOCR},
+ {"ONOCR", ONOCR},
#endif
#ifdef ONLRET
- {"ONLRET", ONLRET},
+ {"ONLRET", ONLRET},
#endif
#ifdef OFILL
- {"OFILL", OFILL},
+ {"OFILL", OFILL},
#endif
#ifdef OFDEL
- {"OFDEL", OFDEL},
+ {"OFDEL", OFDEL},
#endif
#ifdef NLDLY
- {"NLDLY", NLDLY},
+ {"NLDLY", NLDLY},
#endif
#ifdef CRDLY
- {"CRDLY", CRDLY},
+ {"CRDLY", CRDLY},
#endif
#ifdef TABDLY
- {"TABDLY", TABDLY},
+ {"TABDLY", TABDLY},
#endif
#ifdef BSDLY
- {"BSDLY", BSDLY},
+ {"BSDLY", BSDLY},
#endif
#ifdef VTDLY
- {"VTDLY", VTDLY},
+ {"VTDLY", VTDLY},
#endif
#ifdef FFDLY
- {"FFDLY", FFDLY},
+ {"FFDLY", FFDLY},
#endif
- /* struct termios.c_oflag-related values (delay mask) */
+ /* struct termios.c_oflag-related values (delay mask) */
#ifdef NL0
- {"NL0", NL0},
+ {"NL0", NL0},
#endif
#ifdef NL1
- {"NL1", NL1},
+ {"NL1", NL1},
#endif
#ifdef CR0
- {"CR0", CR0},
+ {"CR0", CR0},
#endif
#ifdef CR1
- {"CR1", CR1},
+ {"CR1", CR1},
#endif
#ifdef CR2
- {"CR2", CR2},
+ {"CR2", CR2},
#endif
#ifdef CR3
- {"CR3", CR3},
+ {"CR3", CR3},
#endif
#ifdef TAB0
- {"TAB0", TAB0},
+ {"TAB0", TAB0},
#endif
#ifdef TAB1
- {"TAB1", TAB1},
+ {"TAB1", TAB1},
#endif
#ifdef TAB2
- {"TAB2", TAB2},
+ {"TAB2", TAB2},
#endif
#ifdef TAB3
- {"TAB3", TAB3},
+ {"TAB3", TAB3},
#endif
#ifdef XTABS
- {"XTABS", XTABS},
+ {"XTABS", XTABS},
#endif
#ifdef BS0
- {"BS0", BS0},
+ {"BS0", BS0},
#endif
#ifdef BS1
- {"BS1", BS1},
+ {"BS1", BS1},
#endif
#ifdef VT0
- {"VT0", VT0},
+ {"VT0", VT0},
#endif
#ifdef VT1
- {"VT1", VT1},
+ {"VT1", VT1},
#endif
#ifdef FF0
- {"FF0", FF0},
+ {"FF0", FF0},
#endif
#ifdef FF1
- {"FF1", FF1},
+ {"FF1", FF1},
#endif
- /* struct termios.c_cflag constants */
- {"CSIZE", CSIZE},
- {"CSTOPB", CSTOPB},
- {"CREAD", CREAD},
- {"PARENB", PARENB},
- {"PARODD", PARODD},
- {"HUPCL", HUPCL},
- {"CLOCAL", CLOCAL},
+ /* struct termios.c_cflag constants */
+ {"CSIZE", CSIZE},
+ {"CSTOPB", CSTOPB},
+ {"CREAD", CREAD},
+ {"PARENB", PARENB},
+ {"PARODD", PARODD},
+ {"HUPCL", HUPCL},
+ {"CLOCAL", CLOCAL},
#ifdef CIBAUD
- {"CIBAUD", CIBAUD},
+ {"CIBAUD", CIBAUD},
#endif
#ifdef CRTSCTS
- {"CRTSCTS", (long)CRTSCTS},
+ {"CRTSCTS", (long)CRTSCTS},
#endif
- /* struct termios.c_cflag-related values (character size) */
- {"CS5", CS5},
- {"CS6", CS6},
- {"CS7", CS7},
- {"CS8", CS8},
+ /* struct termios.c_cflag-related values (character size) */
+ {"CS5", CS5},
+ {"CS6", CS6},
+ {"CS7", CS7},
+ {"CS8", CS8},
- /* struct termios.c_lflag constants */
- {"ISIG", ISIG},
- {"ICANON", ICANON},
+ /* struct termios.c_lflag constants */
+ {"ISIG", ISIG},
+ {"ICANON", ICANON},
#ifdef XCASE
- {"XCASE", XCASE},
+ {"XCASE", XCASE},
#endif
- {"ECHO", ECHO},
- {"ECHOE", ECHOE},
- {"ECHOK", ECHOK},
- {"ECHONL", ECHONL},
+ {"ECHO", ECHO},
+ {"ECHOE", ECHOE},
+ {"ECHOK", ECHOK},
+ {"ECHONL", ECHONL},
#ifdef ECHOCTL
- {"ECHOCTL", ECHOCTL},
+ {"ECHOCTL", ECHOCTL},
#endif
#ifdef ECHOPRT
- {"ECHOPRT", ECHOPRT},
+ {"ECHOPRT", ECHOPRT},
#endif
#ifdef ECHOKE
- {"ECHOKE", ECHOKE},
+ {"ECHOKE", ECHOKE},
#endif
#ifdef FLUSHO
- {"FLUSHO", FLUSHO},
+ {"FLUSHO", FLUSHO},
#endif
- {"NOFLSH", NOFLSH},
- {"TOSTOP", TOSTOP},
+ {"NOFLSH", NOFLSH},
+ {"TOSTOP", TOSTOP},
#ifdef PENDIN
- {"PENDIN", PENDIN},
-#endif
- {"IEXTEN", IEXTEN},
-
- /* indexes into the control chars array returned by tcgetattr() */
- {"VINTR", VINTR},
- {"VQUIT", VQUIT},
- {"VERASE", VERASE},
- {"VKILL", VKILL},
- {"VEOF", VEOF},
- {"VTIME", VTIME},
- {"VMIN", VMIN},
+ {"PENDIN", PENDIN},
+#endif
+ {"IEXTEN", IEXTEN},
+
+ /* indexes into the control chars array returned by tcgetattr() */
+ {"VINTR", VINTR},
+ {"VQUIT", VQUIT},
+ {"VERASE", VERASE},
+ {"VKILL", VKILL},
+ {"VEOF", VEOF},
+ {"VTIME", VTIME},
+ {"VMIN", VMIN},
#ifdef VSWTC
- /* The #defines above ensure that if either is defined, both are,
- * but both may be omitted by the system headers. ;-( */
- {"VSWTC", VSWTC},
- {"VSWTCH", VSWTCH},
-#endif
- {"VSTART", VSTART},
- {"VSTOP", VSTOP},
- {"VSUSP", VSUSP},
- {"VEOL", VEOL},
+ /* The #defines above ensure that if either is defined, both are,
+ * but both may be omitted by the system headers. ;-( */
+ {"VSWTC", VSWTC},
+ {"VSWTCH", VSWTCH},
+#endif
+ {"VSTART", VSTART},
+ {"VSTOP", VSTOP},
+ {"VSUSP", VSUSP},
+ {"VEOL", VEOL},
#ifdef VREPRINT
- {"VREPRINT", VREPRINT},
+ {"VREPRINT", VREPRINT},
#endif
#ifdef VDISCARD
- {"VDISCARD", VDISCARD},
+ {"VDISCARD", VDISCARD},
#endif
#ifdef VWERASE
- {"VWERASE", VWERASE},
+ {"VWERASE", VWERASE},
#endif
#ifdef VLNEXT
- {"VLNEXT", VLNEXT},
+ {"VLNEXT", VLNEXT},
#endif
#ifdef VEOL2
- {"VEOL2", VEOL2},
+ {"VEOL2", VEOL2},
#endif
#ifdef B460800
- {"B460800", B460800},
+ {"B460800", B460800},
#endif
#ifdef CBAUD
- {"CBAUD", CBAUD},
+ {"CBAUD", CBAUD},
#endif
#ifdef CDEL
- {"CDEL", CDEL},
+ {"CDEL", CDEL},
#endif
#ifdef CDSUSP
- {"CDSUSP", CDSUSP},
+ {"CDSUSP", CDSUSP},
#endif
#ifdef CEOF
- {"CEOF", CEOF},
+ {"CEOF", CEOF},
#endif
#ifdef CEOL
- {"CEOL", CEOL},
+ {"CEOL", CEOL},
#endif
#ifdef CEOL2
- {"CEOL2", CEOL2},
+ {"CEOL2", CEOL2},
#endif
#ifdef CEOT
- {"CEOT", CEOT},
+ {"CEOT", CEOT},
#endif
#ifdef CERASE
- {"CERASE", CERASE},
+ {"CERASE", CERASE},
#endif
#ifdef CESC
- {"CESC", CESC},
+ {"CESC", CESC},
#endif
#ifdef CFLUSH
- {"CFLUSH", CFLUSH},
+ {"CFLUSH", CFLUSH},
#endif
#ifdef CINTR
- {"CINTR", CINTR},
+ {"CINTR", CINTR},
#endif
#ifdef CKILL
- {"CKILL", CKILL},
+ {"CKILL", CKILL},
#endif
#ifdef CLNEXT
- {"CLNEXT", CLNEXT},
+ {"CLNEXT", CLNEXT},
#endif
#ifdef CNUL
- {"CNUL", CNUL},
+ {"CNUL", CNUL},
#endif
#ifdef COMMON
- {"COMMON", COMMON},
+ {"COMMON", COMMON},
#endif
#ifdef CQUIT
- {"CQUIT", CQUIT},
+ {"CQUIT", CQUIT},
#endif
#ifdef CRPRNT
- {"CRPRNT", CRPRNT},
+ {"CRPRNT", CRPRNT},
#endif
#ifdef CSTART
- {"CSTART", CSTART},
+ {"CSTART", CSTART},
#endif
#ifdef CSTOP
- {"CSTOP", CSTOP},
+ {"CSTOP", CSTOP},
#endif
#ifdef CSUSP
- {"CSUSP", CSUSP},
+ {"CSUSP", CSUSP},
#endif
#ifdef CSWTCH
- {"CSWTCH", CSWTCH},
+ {"CSWTCH", CSWTCH},
#endif
#ifdef CWERASE
- {"CWERASE", CWERASE},
+ {"CWERASE", CWERASE},
#endif
#ifdef EXTA
- {"EXTA", EXTA},
+ {"EXTA", EXTA},
#endif
#ifdef EXTB
- {"EXTB", EXTB},
+ {"EXTB", EXTB},
#endif
#ifdef FIOASYNC
- {"FIOASYNC", FIOASYNC},
+ {"FIOASYNC", FIOASYNC},
#endif
#ifdef FIOCLEX
- {"FIOCLEX", FIOCLEX},
+ {"FIOCLEX", FIOCLEX},
#endif
#ifdef FIONBIO
- {"FIONBIO", FIONBIO},
+ {"FIONBIO", FIONBIO},
#endif
#ifdef FIONCLEX
- {"FIONCLEX", FIONCLEX},
+ {"FIONCLEX", FIONCLEX},
#endif
#ifdef FIONREAD
- {"FIONREAD", FIONREAD},
+ {"FIONREAD", FIONREAD},
#endif
#ifdef IBSHIFT
- {"IBSHIFT", IBSHIFT},
+ {"IBSHIFT", IBSHIFT},
#endif
#ifdef INIT_C_CC
- {"INIT_C_CC", INIT_C_CC},
+ {"INIT_C_CC", INIT_C_CC},
#endif
#ifdef IOCSIZE_MASK
- {"IOCSIZE_MASK", IOCSIZE_MASK},
+ {"IOCSIZE_MASK", IOCSIZE_MASK},
#endif
#ifdef IOCSIZE_SHIFT
- {"IOCSIZE_SHIFT", IOCSIZE_SHIFT},
+ {"IOCSIZE_SHIFT", IOCSIZE_SHIFT},
#endif
#ifdef NCC
- {"NCC", NCC},
+ {"NCC", NCC},
#endif
#ifdef NCCS
- {"NCCS", NCCS},
+ {"NCCS", NCCS},
#endif
#ifdef NSWTCH
- {"NSWTCH", NSWTCH},
+ {"NSWTCH", NSWTCH},
#endif
#ifdef N_MOUSE
- {"N_MOUSE", N_MOUSE},
+ {"N_MOUSE", N_MOUSE},
#endif
#ifdef N_PPP
- {"N_PPP", N_PPP},
+ {"N_PPP", N_PPP},
#endif
#ifdef N_SLIP
- {"N_SLIP", N_SLIP},
+ {"N_SLIP", N_SLIP},
#endif
#ifdef N_STRIP
- {"N_STRIP", N_STRIP},
+ {"N_STRIP", N_STRIP},
#endif
#ifdef N_TTY
- {"N_TTY", N_TTY},
+ {"N_TTY", N_TTY},
#endif
#ifdef TCFLSH
- {"TCFLSH", TCFLSH},
+ {"TCFLSH", TCFLSH},
#endif
#ifdef TCGETA
- {"TCGETA", TCGETA},
+ {"TCGETA", TCGETA},
#endif
#ifdef TCGETS
- {"TCGETS", TCGETS},
+ {"TCGETS", TCGETS},
#endif
#ifdef TCSBRK
- {"TCSBRK", TCSBRK},
+ {"TCSBRK", TCSBRK},
#endif
#ifdef TCSBRKP
- {"TCSBRKP", TCSBRKP},
+ {"TCSBRKP", TCSBRKP},
#endif
#ifdef TCSETA
- {"TCSETA", TCSETA},
+ {"TCSETA", TCSETA},
#endif
#ifdef TCSETAF
- {"TCSETAF", TCSETAF},
+ {"TCSETAF", TCSETAF},
#endif
#ifdef TCSETAW
- {"TCSETAW", TCSETAW},
+ {"TCSETAW", TCSETAW},
#endif
#ifdef TCSETS
- {"TCSETS", TCSETS},
+ {"TCSETS", TCSETS},
#endif
#ifdef TCSETSF
- {"TCSETSF", TCSETSF},
+ {"TCSETSF", TCSETSF},
#endif
#ifdef TCSETSW
- {"TCSETSW", TCSETSW},
+ {"TCSETSW", TCSETSW},
#endif
#ifdef TCXONC
- {"TCXONC", TCXONC},
+ {"TCXONC", TCXONC},
#endif
#ifdef TIOCCONS
- {"TIOCCONS", TIOCCONS},
+ {"TIOCCONS", TIOCCONS},
#endif
#ifdef TIOCEXCL
- {"TIOCEXCL", TIOCEXCL},
+ {"TIOCEXCL", TIOCEXCL},
#endif
#ifdef TIOCGETD
- {"TIOCGETD", TIOCGETD},
+ {"TIOCGETD", TIOCGETD},
#endif
#ifdef TIOCGICOUNT
- {"TIOCGICOUNT", TIOCGICOUNT},
+ {"TIOCGICOUNT", TIOCGICOUNT},
#endif
#ifdef TIOCGLCKTRMIOS
- {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS},
+ {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS},
#endif
#ifdef TIOCGPGRP
- {"TIOCGPGRP", TIOCGPGRP},
+ {"TIOCGPGRP", TIOCGPGRP},
#endif
#ifdef TIOCGSERIAL
- {"TIOCGSERIAL", TIOCGSERIAL},
+ {"TIOCGSERIAL", TIOCGSERIAL},
#endif
#ifdef TIOCGSOFTCAR
- {"TIOCGSOFTCAR", TIOCGSOFTCAR},
+ {"TIOCGSOFTCAR", TIOCGSOFTCAR},
#endif
#ifdef TIOCGWINSZ
- {"TIOCGWINSZ", TIOCGWINSZ},
+ {"TIOCGWINSZ", TIOCGWINSZ},
#endif
#ifdef TIOCINQ
- {"TIOCINQ", TIOCINQ},
+ {"TIOCINQ", TIOCINQ},
#endif
#ifdef TIOCLINUX
- {"TIOCLINUX", TIOCLINUX},
+ {"TIOCLINUX", TIOCLINUX},
#endif
#ifdef TIOCMBIC
- {"TIOCMBIC", TIOCMBIC},
+ {"TIOCMBIC", TIOCMBIC},
#endif
#ifdef TIOCMBIS
- {"TIOCMBIS", TIOCMBIS},
+ {"TIOCMBIS", TIOCMBIS},
#endif
#ifdef TIOCMGET
- {"TIOCMGET", TIOCMGET},
+ {"TIOCMGET", TIOCMGET},
#endif
#ifdef TIOCMIWAIT
- {"TIOCMIWAIT", TIOCMIWAIT},
+ {"TIOCMIWAIT", TIOCMIWAIT},
#endif
#ifdef TIOCMSET
- {"TIOCMSET", TIOCMSET},
+ {"TIOCMSET", TIOCMSET},
#endif
#ifdef TIOCM_CAR
- {"TIOCM_CAR", TIOCM_CAR},
+ {"TIOCM_CAR", TIOCM_CAR},
#endif
#ifdef TIOCM_CD
- {"TIOCM_CD", TIOCM_CD},
+ {"TIOCM_CD", TIOCM_CD},
#endif
#ifdef TIOCM_CTS
- {"TIOCM_CTS", TIOCM_CTS},
+ {"TIOCM_CTS", TIOCM_CTS},
#endif
#ifdef TIOCM_DSR
- {"TIOCM_DSR", TIOCM_DSR},
+ {"TIOCM_DSR", TIOCM_DSR},
#endif
#ifdef TIOCM_DTR
- {"TIOCM_DTR", TIOCM_DTR},
+ {"TIOCM_DTR", TIOCM_DTR},
#endif
#ifdef TIOCM_LE
- {"TIOCM_LE", TIOCM_LE},
+ {"TIOCM_LE", TIOCM_LE},
#endif
#ifdef TIOCM_RI
- {"TIOCM_RI", TIOCM_RI},
+ {"TIOCM_RI", TIOCM_RI},
#endif
#ifdef TIOCM_RNG
- {"TIOCM_RNG", TIOCM_RNG},
+ {"TIOCM_RNG", TIOCM_RNG},
#endif
#ifdef TIOCM_RTS
- {"TIOCM_RTS", TIOCM_RTS},
+ {"TIOCM_RTS", TIOCM_RTS},
#endif
#ifdef TIOCM_SR
- {"TIOCM_SR", TIOCM_SR},
+ {"TIOCM_SR", TIOCM_SR},
#endif
#ifdef TIOCM_ST
- {"TIOCM_ST", TIOCM_ST},
+ {"TIOCM_ST", TIOCM_ST},
#endif
#ifdef TIOCNOTTY
- {"TIOCNOTTY", TIOCNOTTY},
+ {"TIOCNOTTY", TIOCNOTTY},
#endif
#ifdef TIOCNXCL
- {"TIOCNXCL", TIOCNXCL},
+ {"TIOCNXCL", TIOCNXCL},
#endif
#ifdef TIOCOUTQ
- {"TIOCOUTQ", TIOCOUTQ},
+ {"TIOCOUTQ", TIOCOUTQ},
#endif
#ifdef TIOCPKT
- {"TIOCPKT", TIOCPKT},
+ {"TIOCPKT", TIOCPKT},
#endif
#ifdef TIOCPKT_DATA
- {"TIOCPKT_DATA", TIOCPKT_DATA},
+ {"TIOCPKT_DATA", TIOCPKT_DATA},
#endif
#ifdef TIOCPKT_DOSTOP
- {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP},
+ {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP},
#endif
#ifdef TIOCPKT_FLUSHREAD
- {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD},
+ {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD},
#endif
#ifdef TIOCPKT_FLUSHWRITE
- {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE},
+ {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE},
#endif
#ifdef TIOCPKT_NOSTOP
- {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP},
+ {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP},
#endif
#ifdef TIOCPKT_START
- {"TIOCPKT_START", TIOCPKT_START},
+ {"TIOCPKT_START", TIOCPKT_START},
#endif
#ifdef TIOCPKT_STOP
- {"TIOCPKT_STOP", TIOCPKT_STOP},
+ {"TIOCPKT_STOP", TIOCPKT_STOP},
#endif
#ifdef TIOCSCTTY
- {"TIOCSCTTY", TIOCSCTTY},
+ {"TIOCSCTTY", TIOCSCTTY},
#endif
#ifdef TIOCSERCONFIG
- {"TIOCSERCONFIG", TIOCSERCONFIG},
+ {"TIOCSERCONFIG", TIOCSERCONFIG},
#endif
#ifdef TIOCSERGETLSR
- {"TIOCSERGETLSR", TIOCSERGETLSR},
+ {"TIOCSERGETLSR", TIOCSERGETLSR},
#endif
#ifdef TIOCSERGETMULTI
- {"TIOCSERGETMULTI", TIOCSERGETMULTI},
+ {"TIOCSERGETMULTI", TIOCSERGETMULTI},
#endif
#ifdef TIOCSERGSTRUCT
- {"TIOCSERGSTRUCT", TIOCSERGSTRUCT},
+ {"TIOCSERGSTRUCT", TIOCSERGSTRUCT},
#endif
#ifdef TIOCSERGWILD
- {"TIOCSERGWILD", TIOCSERGWILD},
+ {"TIOCSERGWILD", TIOCSERGWILD},
#endif
#ifdef TIOCSERSETMULTI
- {"TIOCSERSETMULTI", TIOCSERSETMULTI},
+ {"TIOCSERSETMULTI", TIOCSERSETMULTI},
#endif
#ifdef TIOCSERSWILD
- {"TIOCSERSWILD", TIOCSERSWILD},
+ {"TIOCSERSWILD", TIOCSERSWILD},
#endif
#ifdef TIOCSER_TEMT
- {"TIOCSER_TEMT", TIOCSER_TEMT},
+ {"TIOCSER_TEMT", TIOCSER_TEMT},
#endif
#ifdef TIOCSETD
- {"TIOCSETD", TIOCSETD},
+ {"TIOCSETD", TIOCSETD},
#endif
#ifdef TIOCSLCKTRMIOS
- {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS},
+ {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS},
#endif
#ifdef TIOCSPGRP
- {"TIOCSPGRP", TIOCSPGRP},
+ {"TIOCSPGRP", TIOCSPGRP},
#endif
#ifdef TIOCSSERIAL
- {"TIOCSSERIAL", TIOCSSERIAL},
+ {"TIOCSSERIAL", TIOCSSERIAL},
#endif
#ifdef TIOCSSOFTCAR
- {"TIOCSSOFTCAR", TIOCSSOFTCAR},
+ {"TIOCSSOFTCAR", TIOCSSOFTCAR},
#endif
#ifdef TIOCSTI
- {"TIOCSTI", TIOCSTI},
+ {"TIOCSTI", TIOCSTI},
#endif
#ifdef TIOCSWINSZ
- {"TIOCSWINSZ", TIOCSWINSZ},
+ {"TIOCSWINSZ", TIOCSWINSZ},
#endif
#ifdef TIOCTTYGSTRUCT
- {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT},
+ {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT},
#endif
- /* sentinel */
- {NULL, 0}
+ /* sentinel */
+ {NULL, 0}
};
static struct PyModuleDef termiosmodule = {
- PyModuleDef_HEAD_INIT,
- "termios",
- termios__doc__,
- -1,
- termios_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "termios",
+ termios__doc__,
+ -1,
+ termios_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_termios(void)
{
- PyObject *m;
- struct constant *constant = termios_constants;
-
- m = PyModule_Create(&termiosmodule);
- if (m == NULL)
- return NULL;
-
- if (TermiosError == NULL) {
- TermiosError = PyErr_NewException("termios.error", NULL, NULL);
- }
- Py_INCREF(TermiosError);
- PyModule_AddObject(m, "error", TermiosError);
-
- while (constant->name != NULL) {
- PyModule_AddIntConstant(m, constant->name, constant->value);
- ++constant;
- }
- return m;
+ PyObject *m;
+ struct constant *constant = termios_constants;
+
+ m = PyModule_Create(&termiosmodule);
+ if (m == NULL)
+ return NULL;
+
+ if (TermiosError == NULL) {
+ TermiosError = PyErr_NewException("termios.error", NULL, NULL);
+ }
+ Py_INCREF(TermiosError);
+ PyModule_AddObject(m, "error", TermiosError);
+
+ while (constant->name != NULL) {
+ PyModule_AddIntConstant(m, constant->name, constant->value);
+ ++constant;
+ }
+ return m;
}
diff --git a/Modules/testcapi_long.h b/Modules/testcapi_long.h
index 60ca326..fa94fd6 100644
--- a/Modules/testcapi_long.h
+++ b/Modules/testcapi_long.h
@@ -1,182 +1,182 @@
/* Poor-man's template. Macros used:
- TESTNAME name of the test (like test_long_api_inner)
- TYPENAME the signed type (like long)
- F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject*
- F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME
- F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject*
+ TESTNAME name of the test (like test_long_api_inner)
+ TYPENAME the signed type (like long)
+ F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject*
+ F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME
+ F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject*
F_PY_TO_U convert pylong to unsigned; PyObject* -> unsigned TYPENAME
*/
static PyObject *
TESTNAME(PyObject *error(const char*))
{
- const int NBITS = sizeof(TYPENAME) * 8;
- unsigned TYPENAME base;
- PyObject *pyresult;
- int i;
-
- /* Note: This test lets PyObjects leak if an error is raised. Since
- an error should never be raised, leaks are impossible <wink>. */
-
- /* Test native -> PyLong -> native roundtrip identity.
- * Generate all powers of 2, and test them and their negations,
- * plus the numbers +-1 off from them.
- */
- base = 1;
- for (i = 0;
- i < NBITS + 1; /* on last, base overflows to 0 */
- ++i, base <<= 1)
- {
- int j;
- for (j = 0; j < 6; ++j) {
- TYPENAME in, out;
- unsigned TYPENAME uin, uout;
-
- /* For 0, 1, 2 use base; for 3, 4, 5 use -base */
- uin = j < 3 ? base
- : (unsigned TYPENAME)(-(TYPENAME)base);
-
- /* For 0 & 3, subtract 1.
- * For 1 & 4, leave alone.
- * For 2 & 5, add 1.
- */
- uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1);
-
- pyresult = F_U_TO_PY(uin);
- if (pyresult == NULL)
- return error(
- "unsigned unexpected null result");
-
- uout = F_PY_TO_U(pyresult);
- if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred())
- return error(
- "unsigned unexpected -1 result");
- if (uout != uin)
- return error(
- "unsigned output != input");
- UNBIND(pyresult);
-
- in = (TYPENAME)uin;
- pyresult = F_S_TO_PY(in);
- if (pyresult == NULL)
- return error(
- "signed unexpected null result");
-
- out = F_PY_TO_S(pyresult);
- if (out == (TYPENAME)-1 && PyErr_Occurred())
- return error(
- "signed unexpected -1 result");
- if (out != in)
- return error(
- "signed output != input");
- UNBIND(pyresult);
- }
- }
-
- /* Overflow tests. The loop above ensured that all limit cases that
- * should not overflow don't overflow, so all we need to do here is
- * provoke one-over-the-limit cases (not exhaustive, but sharp).
- */
- {
- PyObject *one, *x, *y;
- TYPENAME out;
- unsigned TYPENAME uout;
-
- one = PyLong_FromLong(1);
- if (one == NULL)
- return error(
- "unexpected NULL from PyLong_FromLong");
-
- /* Unsigned complains about -1? */
- x = PyNumber_Negative(one);
- if (x == NULL)
- return error(
- "unexpected NULL from PyNumber_Negative");
-
- uout = F_PY_TO_U(x);
- if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsUnsignedXXX(-1) didn't complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsUnsignedXXX(-1) raised "
- "something other than OverflowError");
- PyErr_Clear();
- UNBIND(x);
-
- /* Unsigned complains about 2**NBITS? */
- y = PyLong_FromLong((long)NBITS);
- if (y == NULL)
- return error(
- "unexpected NULL from PyLong_FromLong");
-
- x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */
- UNBIND(y);
- if (x == NULL)
- return error(
- "unexpected NULL from PyNumber_Lshift");
-
- uout = F_PY_TO_U(x);
- if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsUnsignedXXX(2**NBITS) didn't "
- "complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsUnsignedXXX(2**NBITS) raised "
- "something other than OverflowError");
- PyErr_Clear();
-
- /* Signed complains about 2**(NBITS-1)?
- x still has 2**NBITS. */
- y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */
- UNBIND(x);
- if (y == NULL)
- return error(
- "unexpected NULL from PyNumber_Rshift");
-
- out = F_PY_TO_S(y);
- if (out != (TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsXXX(2**(NBITS-1)) didn't "
- "complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsXXX(2**(NBITS-1)) raised "
- "something other than OverflowError");
- PyErr_Clear();
-
- /* Signed complains about -2**(NBITS-1)-1?;
- y still has 2**(NBITS-1). */
- x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */
- UNBIND(y);
- if (x == NULL)
- return error(
- "unexpected NULL from PyNumber_Negative");
-
- y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */
- UNBIND(x);
- if (y == NULL)
- return error(
- "unexpected NULL from PyNumber_Subtract");
-
- out = F_PY_TO_S(y);
- if (out != (TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsXXX(-2**(NBITS-1)-1) didn't "
- "complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsXXX(-2**(NBITS-1)-1) raised "
- "something other than OverflowError");
- PyErr_Clear();
- UNBIND(y);
-
- Py_XDECREF(x);
- Py_XDECREF(y);
- Py_DECREF(one);
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ const int NBITS = sizeof(TYPENAME) * 8;
+ unsigned TYPENAME base;
+ PyObject *pyresult;
+ int i;
+
+ /* Note: This test lets PyObjects leak if an error is raised. Since
+ an error should never be raised, leaks are impossible <wink>. */
+
+ /* Test native -> PyLong -> native roundtrip identity.
+ * Generate all powers of 2, and test them and their negations,
+ * plus the numbers +-1 off from them.
+ */
+ base = 1;
+ for (i = 0;
+ i < NBITS + 1; /* on last, base overflows to 0 */
+ ++i, base <<= 1)
+ {
+ int j;
+ for (j = 0; j < 6; ++j) {
+ TYPENAME in, out;
+ unsigned TYPENAME uin, uout;
+
+ /* For 0, 1, 2 use base; for 3, 4, 5 use -base */
+ uin = j < 3 ? base
+ : (unsigned TYPENAME)(-(TYPENAME)base);
+
+ /* For 0 & 3, subtract 1.
+ * For 1 & 4, leave alone.
+ * For 2 & 5, add 1.
+ */
+ uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1);
+
+ pyresult = F_U_TO_PY(uin);
+ if (pyresult == NULL)
+ return error(
+ "unsigned unexpected null result");
+
+ uout = F_PY_TO_U(pyresult);
+ if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred())
+ return error(
+ "unsigned unexpected -1 result");
+ if (uout != uin)
+ return error(
+ "unsigned output != input");
+ UNBIND(pyresult);
+
+ in = (TYPENAME)uin;
+ pyresult = F_S_TO_PY(in);
+ if (pyresult == NULL)
+ return error(
+ "signed unexpected null result");
+
+ out = F_PY_TO_S(pyresult);
+ if (out == (TYPENAME)-1 && PyErr_Occurred())
+ return error(
+ "signed unexpected -1 result");
+ if (out != in)
+ return error(
+ "signed output != input");
+ UNBIND(pyresult);
+ }
+ }
+
+ /* Overflow tests. The loop above ensured that all limit cases that
+ * should not overflow don't overflow, so all we need to do here is
+ * provoke one-over-the-limit cases (not exhaustive, but sharp).
+ */
+ {
+ PyObject *one, *x, *y;
+ TYPENAME out;
+ unsigned TYPENAME uout;
+
+ one = PyLong_FromLong(1);
+ if (one == NULL)
+ return error(
+ "unexpected NULL from PyLong_FromLong");
+
+ /* Unsigned complains about -1? */
+ x = PyNumber_Negative(one);
+ if (x == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Negative");
+
+ uout = F_PY_TO_U(x);
+ if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsUnsignedXXX(-1) didn't complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsUnsignedXXX(-1) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+ UNBIND(x);
+
+ /* Unsigned complains about 2**NBITS? */
+ y = PyLong_FromLong((long)NBITS);
+ if (y == NULL)
+ return error(
+ "unexpected NULL from PyLong_FromLong");
+
+ x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */
+ UNBIND(y);
+ if (x == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Lshift");
+
+ uout = F_PY_TO_U(x);
+ if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsUnsignedXXX(2**NBITS) didn't "
+ "complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsUnsignedXXX(2**NBITS) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+
+ /* Signed complains about 2**(NBITS-1)?
+ x still has 2**NBITS. */
+ y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */
+ UNBIND(x);
+ if (y == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Rshift");
+
+ out = F_PY_TO_S(y);
+ if (out != (TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsXXX(2**(NBITS-1)) didn't "
+ "complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsXXX(2**(NBITS-1)) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+
+ /* Signed complains about -2**(NBITS-1)-1?;
+ y still has 2**(NBITS-1). */
+ x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */
+ UNBIND(y);
+ if (x == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Negative");
+
+ y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */
+ UNBIND(x);
+ if (y == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Subtract");
+
+ out = F_PY_TO_S(y);
+ if (out != (TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsXXX(-2**(NBITS-1)-1) didn't "
+ "complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsXXX(-2**(NBITS-1)-1) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+ UNBIND(y);
+
+ Py_XDECREF(x);
+ Py_XDECREF(y);
+ Py_DECREF(one);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
diff --git a/Modules/timemodule.c b/Modules/timemodule.c
index 0161ac0..20acacf 100644
--- a/Modules/timemodule.c
+++ b/Modules/timemodule.c
@@ -48,12 +48,12 @@ extern int ftime(struct timeb *);
static HANDLE hInterruptEvent = NULL;
static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
{
- SetEvent(hInterruptEvent);
- /* allow other default handlers to be called.
- Default Python handler will setup the
- KeyboardInterrupt exception.
- */
- return FALSE;
+ SetEvent(hInterruptEvent);
+ /* allow other default handlers to be called.
+ Default Python handler will setup the
+ KeyboardInterrupt exception.
+ */
+ return FALSE;
}
static long main_thread;
@@ -94,38 +94,38 @@ static PyObject *moddict;
time_t
_PyTime_DoubleToTimet(double x)
{
- time_t result;
- double diff;
-
- result = (time_t)x;
- /* How much info did we lose? time_t may be an integral or
- * floating type, and we don't know which. If it's integral,
- * we don't know whether C truncates, rounds, returns the floor,
- * etc. If we lost a second or more, the C rounding is
- * unreasonable, or the input just doesn't fit in a time_t;
- * call it an error regardless. Note that the original cast to
- * time_t can cause a C error too, but nothing we can do to
- * worm around that.
- */
- diff = x - (double)result;
- if (diff <= -1.0 || diff >= 1.0) {
- PyErr_SetString(PyExc_ValueError,
- "timestamp out of range for platform time_t");
- result = (time_t)-1;
- }
- return result;
+ time_t result;
+ double diff;
+
+ result = (time_t)x;
+ /* How much info did we lose? time_t may be an integral or
+ * floating type, and we don't know which. If it's integral,
+ * we don't know whether C truncates, rounds, returns the floor,
+ * etc. If we lost a second or more, the C rounding is
+ * unreasonable, or the input just doesn't fit in a time_t;
+ * call it an error regardless. Note that the original cast to
+ * time_t can cause a C error too, but nothing we can do to
+ * worm around that.
+ */
+ diff = x - (double)result;
+ if (diff <= -1.0 || diff >= 1.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "timestamp out of range for platform time_t");
+ result = (time_t)-1;
+ }
+ return result;
}
static PyObject *
time_time(PyObject *self, PyObject *unused)
{
- double secs;
- secs = floattime();
- if (secs == 0.0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyFloat_FromDouble(secs);
+ double secs;
+ secs = floattime();
+ if (secs == 0.0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyFloat_FromDouble(secs);
}
PyDoc_STRVAR(time_doc,
@@ -147,7 +147,7 @@ Fractions of a second may be present if the system clock provides them.");
static PyObject *
time_clock(PyObject *self, PyObject *unused)
{
- return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
+ return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
}
#endif /* HAVE_CLOCK */
@@ -156,25 +156,25 @@ time_clock(PyObject *self, PyObject *unused)
static PyObject *
time_clock(PyObject *self, PyObject *unused)
{
- static LARGE_INTEGER ctrStart;
- static double divisor = 0.0;
- LARGE_INTEGER now;
- double diff;
-
- if (divisor == 0.0) {
- LARGE_INTEGER freq;
- QueryPerformanceCounter(&ctrStart);
- if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
- /* Unlikely to happen - this works on all intel
- machines at least! Revert to clock() */
- return PyFloat_FromDouble(((double)clock()) /
- CLOCKS_PER_SEC);
- }
- divisor = (double)freq.QuadPart;
- }
- QueryPerformanceCounter(&now);
- diff = (double)(now.QuadPart - ctrStart.QuadPart);
- return PyFloat_FromDouble(diff / divisor);
+ static LARGE_INTEGER ctrStart;
+ static double divisor = 0.0;
+ LARGE_INTEGER now;
+ double diff;
+
+ if (divisor == 0.0) {
+ LARGE_INTEGER freq;
+ QueryPerformanceCounter(&ctrStart);
+ if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
+ /* Unlikely to happen - this works on all intel
+ machines at least! Revert to clock() */
+ return PyFloat_FromDouble(((double)clock()) /
+ CLOCKS_PER_SEC);
+ }
+ divisor = (double)freq.QuadPart;
+ }
+ QueryPerformanceCounter(&now);
+ diff = (double)(now.QuadPart - ctrStart.QuadPart);
+ return PyFloat_FromDouble(diff / divisor);
}
#define HAVE_CLOCK /* So it gets included in the methods */
@@ -192,13 +192,13 @@ records.");
static PyObject *
time_sleep(PyObject *self, PyObject *args)
{
- double secs;
- if (!PyArg_ParseTuple(args, "d:sleep", &secs))
- return NULL;
- if (floatsleep(secs) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ double secs;
+ if (!PyArg_ParseTuple(args, "d:sleep", &secs))
+ return NULL;
+ if (floatsleep(secs) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(sleep_doc,
@@ -208,23 +208,23 @@ Delay execution for a given number of seconds. The argument may be\n\
a floating point number for subsecond precision.");
static PyStructSequence_Field struct_time_type_fields[] = {
- {"tm_year", NULL},
- {"tm_mon", NULL},
- {"tm_mday", NULL},
- {"tm_hour", NULL},
- {"tm_min", NULL},
- {"tm_sec", NULL},
- {"tm_wday", NULL},
- {"tm_yday", NULL},
- {"tm_isdst", NULL},
- {0}
+ {"tm_year", NULL},
+ {"tm_mon", NULL},
+ {"tm_mday", NULL},
+ {"tm_hour", NULL},
+ {"tm_min", NULL},
+ {"tm_sec", NULL},
+ {"tm_wday", NULL},
+ {"tm_yday", NULL},
+ {"tm_isdst", NULL},
+ {0}
};
static PyStructSequence_Desc struct_time_type_desc = {
- "time.struct_time",
- NULL,
- struct_time_type_fields,
- 9,
+ "time.struct_time",
+ NULL,
+ struct_time_type_fields,
+ 9,
};
static int initialized;
@@ -233,71 +233,71 @@ static PyTypeObject StructTimeType;
static PyObject *
tmtotuple(struct tm *p)
{
- PyObject *v = PyStructSequence_New(&StructTimeType);
- if (v == NULL)
- return NULL;
+ PyObject *v = PyStructSequence_New(&StructTimeType);
+ if (v == NULL)
+ return NULL;
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
- SET(0, p->tm_year + 1900);
- SET(1, p->tm_mon + 1); /* Want January == 1 */
- SET(2, p->tm_mday);
- SET(3, p->tm_hour);
- SET(4, p->tm_min);
- SET(5, p->tm_sec);
- SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
- SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
- SET(8, p->tm_isdst);
+ SET(0, p->tm_year + 1900);
+ SET(1, p->tm_mon + 1); /* Want January == 1 */
+ SET(2, p->tm_mday);
+ SET(3, p->tm_hour);
+ SET(4, p->tm_min);
+ SET(5, p->tm_sec);
+ SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
+ SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
+ SET(8, p->tm_isdst);
#undef SET
- if (PyErr_Occurred()) {
- Py_XDECREF(v);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v);
+ return NULL;
+ }
- return v;
+ return v;
}
static PyObject *
structtime_totuple(PyObject *t)
{
- PyObject *x = NULL;
- unsigned int i;
- PyObject *v = PyTuple_New(9);
- if (v == NULL)
- return NULL;
-
- for (i=0; i<9; i++) {
- x = PyStructSequence_GET_ITEM(t, i);
- Py_INCREF(x);
- PyTuple_SET_ITEM(v, i, x);
- }
-
- if (PyErr_Occurred()) {
- Py_XDECREF(v);
- return NULL;
- }
-
- return v;
+ PyObject *x = NULL;
+ unsigned int i;
+ PyObject *v = PyTuple_New(9);
+ if (v == NULL)
+ return NULL;
+
+ for (i=0; i<9; i++) {
+ x = PyStructSequence_GET_ITEM(t, i);
+ Py_INCREF(x);
+ PyTuple_SET_ITEM(v, i, x);
+ }
+
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v);
+ return NULL;
+ }
+
+ return v;
}
static PyObject *
time_convert(double when, struct tm * (*function)(const time_t *))
{
- struct tm *p;
- time_t whent = _PyTime_DoubleToTimet(when);
-
- if (whent == (time_t)-1 && PyErr_Occurred())
- return NULL;
- errno = 0;
- p = function(&whent);
- if (p == NULL) {
+ struct tm *p;
+ time_t whent = _PyTime_DoubleToTimet(when);
+
+ if (whent == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ p = function(&whent);
+ if (p == NULL) {
#ifdef EINVAL
- if (errno == 0)
- errno = EINVAL;
+ if (errno == 0)
+ errno = EINVAL;
#endif
- return PyErr_SetFromErrno(PyExc_ValueError);
- }
- return tmtotuple(p);
+ return PyErr_SetFromErrno(PyExc_ValueError);
+ }
+ return tmtotuple(p);
}
/* Parse arg tuple that can contain an optional float-or-None value;
@@ -307,28 +307,28 @@ time_convert(double when, struct tm * (*function)(const time_t *))
static int
parse_time_double_args(PyObject *args, char *format, double *pwhen)
{
- PyObject *ot = NULL;
-
- if (!PyArg_ParseTuple(args, format, &ot))
- return 0;
- if (ot == NULL || ot == Py_None)
- *pwhen = floattime();
- else {
- double when = PyFloat_AsDouble(ot);
- if (PyErr_Occurred())
- return 0;
- *pwhen = when;
- }
- return 1;
+ PyObject *ot = NULL;
+
+ if (!PyArg_ParseTuple(args, format, &ot))
+ return 0;
+ if (ot == NULL || ot == Py_None)
+ *pwhen = floattime();
+ else {
+ double when = PyFloat_AsDouble(ot);
+ if (PyErr_Occurred())
+ return 0;
+ *pwhen = when;
+ }
+ return 1;
}
static PyObject *
time_gmtime(PyObject *self, PyObject *args)
{
- double when;
- if (!parse_time_double_args(args, "|O:gmtime", &when))
- return NULL;
- return time_convert(when, gmtime);
+ double when;
+ if (!parse_time_double_args(args, "|O:gmtime", &when))
+ return NULL;
+ return time_convert(when, gmtime);
}
PyDoc_STRVAR(gmtime_doc,
@@ -341,15 +341,15 @@ GMT). When 'seconds' is not passed in, convert the current time instead.");
static PyObject *
time_localtime(PyObject *self, PyObject *args)
{
- double when;
- if (!parse_time_double_args(args, "|O:localtime", &when))
- return NULL;
- return time_convert(when, localtime);
+ double when;
+ if (!parse_time_double_args(args, "|O:localtime", &when))
+ return NULL;
+ return time_convert(when, localtime);
}
PyDoc_STRVAR(localtime_doc,
"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
- tm_sec,tm_wday,tm_yday,tm_isdst)\n\
+ tm_sec,tm_wday,tm_yday,tm_isdst)\n\
\n\
Convert seconds since the Epoch to a time tuple expressing local time.\n\
When 'seconds' is not passed in, convert the current time instead.");
@@ -357,63 +357,63 @@ When 'seconds' is not passed in, convert the current time instead.");
static int
gettmarg(PyObject *args, struct tm *p)
{
- int y;
- PyObject *t = NULL;
-
- memset((void *) p, '\0', sizeof(struct tm));
-
- if (PyTuple_Check(args)) {
- t = args;
- Py_INCREF(t);
- }
- else if (Py_TYPE(args) == &StructTimeType) {
- t = structtime_totuple(args);
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "Tuple or struct_time argument required");
- return 0;
- }
-
- if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
- &y,
- &p->tm_mon,
- &p->tm_mday,
- &p->tm_hour,
- &p->tm_min,
- &p->tm_sec,
- &p->tm_wday,
- &p->tm_yday,
- &p->tm_isdst)) {
- Py_XDECREF(t);
- return 0;
- }
- Py_DECREF(t);
-
- if (y < 1900) {
- PyObject *accept = PyDict_GetItemString(moddict,
- "accept2dyear");
- if (accept == NULL || !PyLong_CheckExact(accept) ||
- !PyObject_IsTrue(accept)) {
- PyErr_SetString(PyExc_ValueError,
- "year >= 1900 required");
- return 0;
- }
- if (69 <= y && y <= 99)
- y += 1900;
- else if (0 <= y && y <= 68)
- y += 2000;
- else {
- PyErr_SetString(PyExc_ValueError,
- "year out of range");
- return 0;
- }
- }
- p->tm_year = y - 1900;
- p->tm_mon--;
- p->tm_wday = (p->tm_wday + 1) % 7;
- p->tm_yday--;
- return 1;
+ int y;
+ PyObject *t = NULL;
+
+ memset((void *) p, '\0', sizeof(struct tm));
+
+ if (PyTuple_Check(args)) {
+ t = args;
+ Py_INCREF(t);
+ }
+ else if (Py_TYPE(args) == &StructTimeType) {
+ t = structtime_totuple(args);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "Tuple or struct_time argument required");
+ return 0;
+ }
+
+ if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
+ &y,
+ &p->tm_mon,
+ &p->tm_mday,
+ &p->tm_hour,
+ &p->tm_min,
+ &p->tm_sec,
+ &p->tm_wday,
+ &p->tm_yday,
+ &p->tm_isdst)) {
+ Py_XDECREF(t);
+ return 0;
+ }
+ Py_DECREF(t);
+
+ if (y < 1900) {
+ PyObject *accept = PyDict_GetItemString(moddict,
+ "accept2dyear");
+ if (accept == NULL || !PyLong_CheckExact(accept) ||
+ !PyObject_IsTrue(accept)) {
+ PyErr_SetString(PyExc_ValueError,
+ "year >= 1900 required");
+ return 0;
+ }
+ if (69 <= y && y <= 99)
+ y += 1900;
+ else if (0 <= y && y <= 68)
+ y += 2000;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "year out of range");
+ return 0;
+ }
+ }
+ p->tm_year = y - 1900;
+ p->tm_mon--;
+ p->tm_wday = (p->tm_wday + 1) % 7;
+ p->tm_yday--;
+ return 1;
}
#ifdef HAVE_STRFTIME
@@ -430,174 +430,174 @@ gettmarg(PyObject *args, struct tm *p)
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
- PyObject *tup = NULL;
- struct tm buf;
- const time_char *fmt;
- PyObject *format, *tmpfmt;
- size_t fmtlen, buflen;
- time_char *outbuf = 0;
- size_t i;
-
- memset((void *) &buf, '\0', sizeof(buf));
-
- /* Will always expect a unicode string to be passed as format.
- Given that there's no str type anymore in py3k this seems safe.
- */
- if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
- return NULL;
-
- if (tup == NULL) {
- time_t tt = time(NULL);
- buf = *localtime(&tt);
- } else if (!gettmarg(tup, &buf))
- return NULL;
-
- /* Checks added to make sure strftime() does not crash Python by
- indexing blindly into some array for a textual representation
- by some bad index (fixes bug #897625).
-
- Also support values of zero from Python code for arguments in which
- that is out of range by forcing that value to the lowest value that
- is valid (fixed bug #1520914).
-
- Valid ranges based on what is allowed in struct tm:
-
- - tm_year: [0, max(int)] (1)
- - tm_mon: [0, 11] (2)
- - tm_mday: [1, 31]
- - tm_hour: [0, 23]
- - tm_min: [0, 59]
- - tm_sec: [0, 60]
- - tm_wday: [0, 6] (1)
- - tm_yday: [0, 365] (2)
- - tm_isdst: [-max(int), max(int)]
-
- (1) gettmarg() handles bounds-checking.
- (2) Python's acceptable range is one greater than the range in C,
- thus need to check against automatic decrement by gettmarg().
- */
- if (buf.tm_mon == -1)
- buf.tm_mon = 0;
- else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
- PyErr_SetString(PyExc_ValueError, "month out of range");
- return NULL;
- }
- if (buf.tm_mday == 0)
- buf.tm_mday = 1;
- else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
- PyErr_SetString(PyExc_ValueError, "day of month out of range");
- return NULL;
- }
- if (buf.tm_hour < 0 || buf.tm_hour > 23) {
- PyErr_SetString(PyExc_ValueError, "hour out of range");
- return NULL;
- }
- if (buf.tm_min < 0 || buf.tm_min > 59) {
- PyErr_SetString(PyExc_ValueError, "minute out of range");
- return NULL;
- }
- if (buf.tm_sec < 0 || buf.tm_sec > 61) {
- PyErr_SetString(PyExc_ValueError, "seconds out of range");
- return NULL;
- }
- /* tm_wday does not need checking of its upper-bound since taking
- ``% 7`` in gettmarg() automatically restricts the range. */
- if (buf.tm_wday < 0) {
- PyErr_SetString(PyExc_ValueError, "day of week out of range");
- return NULL;
- }
- if (buf.tm_yday == -1)
- buf.tm_yday = 0;
- else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
- PyErr_SetString(PyExc_ValueError, "day of year out of range");
- return NULL;
- }
- /* Normalize tm_isdst just in case someone foolishly implements %Z
- based on the assumption that tm_isdst falls within the range of
- [-1, 1] */
- if (buf.tm_isdst < -1)
- buf.tm_isdst = -1;
- else if (buf.tm_isdst > 1)
- buf.tm_isdst = 1;
+ PyObject *tup = NULL;
+ struct tm buf;
+ const time_char *fmt;
+ PyObject *format, *tmpfmt;
+ size_t fmtlen, buflen;
+ time_char *outbuf = 0;
+ size_t i;
+
+ memset((void *) &buf, '\0', sizeof(buf));
+
+ /* Will always expect a unicode string to be passed as format.
+ Given that there's no str type anymore in py3k this seems safe.
+ */
+ if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
+ return NULL;
+
+ if (tup == NULL) {
+ time_t tt = time(NULL);
+ buf = *localtime(&tt);
+ } else if (!gettmarg(tup, &buf))
+ return NULL;
+
+ /* Checks added to make sure strftime() does not crash Python by
+ indexing blindly into some array for a textual representation
+ by some bad index (fixes bug #897625).
+
+ Also support values of zero from Python code for arguments in which
+ that is out of range by forcing that value to the lowest value that
+ is valid (fixed bug #1520914).
+
+ Valid ranges based on what is allowed in struct tm:
+
+ - tm_year: [0, max(int)] (1)
+ - tm_mon: [0, 11] (2)
+ - tm_mday: [1, 31]
+ - tm_hour: [0, 23]
+ - tm_min: [0, 59]
+ - tm_sec: [0, 60]
+ - tm_wday: [0, 6] (1)
+ - tm_yday: [0, 365] (2)
+ - tm_isdst: [-max(int), max(int)]
+
+ (1) gettmarg() handles bounds-checking.
+ (2) Python's acceptable range is one greater than the range in C,
+ thus need to check against automatic decrement by gettmarg().
+ */
+ if (buf.tm_mon == -1)
+ buf.tm_mon = 0;
+ else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
+ PyErr_SetString(PyExc_ValueError, "month out of range");
+ return NULL;
+ }
+ if (buf.tm_mday == 0)
+ buf.tm_mday = 1;
+ else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
+ PyErr_SetString(PyExc_ValueError, "day of month out of range");
+ return NULL;
+ }
+ if (buf.tm_hour < 0 || buf.tm_hour > 23) {
+ PyErr_SetString(PyExc_ValueError, "hour out of range");
+ return NULL;
+ }
+ if (buf.tm_min < 0 || buf.tm_min > 59) {
+ PyErr_SetString(PyExc_ValueError, "minute out of range");
+ return NULL;
+ }
+ if (buf.tm_sec < 0 || buf.tm_sec > 61) {
+ PyErr_SetString(PyExc_ValueError, "seconds out of range");
+ return NULL;
+ }
+ /* tm_wday does not need checking of its upper-bound since taking
+ ``% 7`` in gettmarg() automatically restricts the range. */
+ if (buf.tm_wday < 0) {
+ PyErr_SetString(PyExc_ValueError, "day of week out of range");
+ return NULL;
+ }
+ if (buf.tm_yday == -1)
+ buf.tm_yday = 0;
+ else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
+ PyErr_SetString(PyExc_ValueError, "day of year out of range");
+ return NULL;
+ }
+ /* Normalize tm_isdst just in case someone foolishly implements %Z
+ based on the assumption that tm_isdst falls within the range of
+ [-1, 1] */
+ if (buf.tm_isdst < -1)
+ buf.tm_isdst = -1;
+ else if (buf.tm_isdst > 1)
+ buf.tm_isdst = 1;
#ifdef HAVE_WCSFTIME
- tmpfmt = PyBytes_FromStringAndSize(NULL,
- sizeof(wchar_t) * (PyUnicode_GetSize(format)+1));
- if (!tmpfmt)
- return NULL;
- /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16
- expansion. */
- if (PyUnicode_AsWideChar((PyUnicodeObject*)format,
- (wchar_t*)PyBytes_AS_STRING(tmpfmt),
- PyUnicode_GetSize(format)+1) == (size_t)-1)
- /* This shouldn't fail. */
- Py_FatalError("PyUnicode_AsWideChar failed");
- format = tmpfmt;
- fmt = (wchar_t*)PyBytes_AS_STRING(format);
+ tmpfmt = PyBytes_FromStringAndSize(NULL,
+ sizeof(wchar_t) * (PyUnicode_GetSize(format)+1));
+ if (!tmpfmt)
+ return NULL;
+ /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16
+ expansion. */
+ if (PyUnicode_AsWideChar((PyUnicodeObject*)format,
+ (wchar_t*)PyBytes_AS_STRING(tmpfmt),
+ PyUnicode_GetSize(format)+1) == (size_t)-1)
+ /* This shouldn't fail. */
+ Py_FatalError("PyUnicode_AsWideChar failed");
+ format = tmpfmt;
+ fmt = (wchar_t*)PyBytes_AS_STRING(format);
#else
- /* Convert the unicode string to an ascii one */
- format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
- if (format == NULL)
- return NULL;
- fmt = PyBytes_AS_STRING(format);
+ /* Convert the unicode string to an ascii one */
+ format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
+ if (format == NULL)
+ return NULL;
+ fmt = PyBytes_AS_STRING(format);
#endif
#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
- /* check that the format string contains only valid directives */
- for(outbuf = wcschr(fmt, L'%');
- outbuf != NULL;
- outbuf = wcschr(outbuf+2, L'%'))
- {
- if (outbuf[1]=='#')
- ++outbuf; /* not documented by python, */
- if (outbuf[1]=='\0' ||
- !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
- {
- PyErr_SetString(PyExc_ValueError, "Invalid format string");
- return 0;
- }
- }
+ /* check that the format string contains only valid directives */
+ for(outbuf = wcschr(fmt, L'%');
+ outbuf != NULL;
+ outbuf = wcschr(outbuf+2, L'%'))
+ {
+ if (outbuf[1]=='#')
+ ++outbuf; /* not documented by python, */
+ if (outbuf[1]=='\0' ||
+ !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
+ {
+ PyErr_SetString(PyExc_ValueError, "Invalid format string");
+ return 0;
+ }
+ }
#endif
- fmtlen = time_strlen(fmt);
-
- /* I hate these functions that presume you know how big the output
- * will be ahead of time...
- */
- for (i = 1024; ; i += i) {
- outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
- if (outbuf == NULL) {
- Py_DECREF(format);
- return PyErr_NoMemory();
- }
- buflen = format_time(outbuf, i, fmt, &buf);
- if (buflen > 0 || i >= 256 * fmtlen) {
- /* If the buffer is 256 times as long as the format,
- it's probably not failing for lack of room!
- More likely, the format yields an empty result,
- e.g. an empty format, or %Z when the timezone
- is unknown. */
- PyObject *ret;
+ fmtlen = time_strlen(fmt);
+
+ /* I hate these functions that presume you know how big the output
+ * will be ahead of time...
+ */
+ for (i = 1024; ; i += i) {
+ outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
+ if (outbuf == NULL) {
+ Py_DECREF(format);
+ return PyErr_NoMemory();
+ }
+ buflen = format_time(outbuf, i, fmt, &buf);
+ if (buflen > 0 || i >= 256 * fmtlen) {
+ /* If the buffer is 256 times as long as the format,
+ it's probably not failing for lack of room!
+ More likely, the format yields an empty result,
+ e.g. an empty format, or %Z when the timezone
+ is unknown. */
+ PyObject *ret;
#ifdef HAVE_WCSFTIME
- ret = PyUnicode_FromWideChar(outbuf, buflen);
+ ret = PyUnicode_FromWideChar(outbuf, buflen);
#else
- ret = PyUnicode_Decode(outbuf, buflen,
- TZNAME_ENCODING, NULL);
+ ret = PyUnicode_Decode(outbuf, buflen,
+ TZNAME_ENCODING, NULL);
#endif
- PyMem_Free(outbuf);
- Py_DECREF(format);
- return ret;
- }
- PyMem_Free(outbuf);
+ PyMem_Free(outbuf);
+ Py_DECREF(format);
+ return ret;
+ }
+ PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
- /* VisualStudio .NET 2005 does this properly */
- if (buflen == 0 && errno == EINVAL) {
- PyErr_SetString(PyExc_ValueError, "Invalid format string");
- Py_DECREF(format);
- return 0;
- }
+ /* VisualStudio .NET 2005 does this properly */
+ if (buflen == 0 && errno == EINVAL) {
+ PyErr_SetString(PyExc_ValueError, "Invalid format string");
+ Py_DECREF(format);
+ return 0;
+ }
#endif
- }
+ }
}
#undef time_char
@@ -614,15 +614,15 @@ is not present, current time as returned by localtime() is used.");
static PyObject *
time_strptime(PyObject *self, PyObject *args)
{
- PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
- PyObject *strptime_result;
-
- if (!strptime_module)
- return NULL;
- strptime_result = PyObject_CallMethod(strptime_module,
- "_strptime_time", "O", args);
- Py_DECREF(strptime_module);
- return strptime_result;
+ PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
+ PyObject *strptime_result;
+
+ if (!strptime_module)
+ return NULL;
+ strptime_result = PyObject_CallMethod(strptime_module,
+ "_strptime_time", "O", args);
+ Py_DECREF(strptime_module);
+ return strptime_result;
}
PyDoc_STRVAR(strptime_doc,
@@ -635,20 +635,20 @@ See the library reference manual for formatting codes (same as strftime()).");
static PyObject *
time_asctime(PyObject *self, PyObject *args)
{
- PyObject *tup = NULL;
- struct tm buf;
- char *p;
- if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
- return NULL;
- if (tup == NULL) {
- time_t tt = time(NULL);
- buf = *localtime(&tt);
- } else if (!gettmarg(tup, &buf))
- return NULL;
- p = asctime(&buf);
- if (p[24] == '\n')
- p[24] = '\0';
- return PyUnicode_FromString(p);
+ PyObject *tup = NULL;
+ struct tm buf;
+ char *p;
+ if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
+ return NULL;
+ if (tup == NULL) {
+ time_t tt = time(NULL);
+ buf = *localtime(&tt);
+ } else if (!gettmarg(tup, &buf))
+ return NULL;
+ p = asctime(&buf);
+ if (p[24] == '\n')
+ p[24] = '\0';
+ return PyUnicode_FromString(p);
}
PyDoc_STRVAR(asctime_doc,
@@ -661,30 +661,30 @@ is used.");
static PyObject *
time_ctime(PyObject *self, PyObject *args)
{
- PyObject *ot = NULL;
- time_t tt;
- char *p;
-
- if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
- return NULL;
- if (ot == NULL || ot == Py_None)
- tt = time(NULL);
- else {
- double dt = PyFloat_AsDouble(ot);
- if (PyErr_Occurred())
- return NULL;
- tt = _PyTime_DoubleToTimet(dt);
- if (tt == (time_t)-1 && PyErr_Occurred())
- return NULL;
- }
- p = ctime(&tt);
- if (p == NULL) {
- PyErr_SetString(PyExc_ValueError, "unconvertible time");
- return NULL;
- }
- if (p[24] == '\n')
- p[24] = '\0';
- return PyUnicode_FromString(p);
+ PyObject *ot = NULL;
+ time_t tt;
+ char *p;
+
+ if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
+ return NULL;
+ if (ot == NULL || ot == Py_None)
+ tt = time(NULL);
+ else {
+ double dt = PyFloat_AsDouble(ot);
+ if (PyErr_Occurred())
+ return NULL;
+ tt = _PyTime_DoubleToTimet(dt);
+ if (tt == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ }
+ p = ctime(&tt);
+ if (p == NULL) {
+ PyErr_SetString(PyExc_ValueError, "unconvertible time");
+ return NULL;
+ }
+ if (p[24] == '\n')
+ p[24] = '\0';
+ return PyUnicode_FromString(p);
}
PyDoc_STRVAR(ctime_doc,
@@ -698,17 +698,17 @@ not present, current time as returned by localtime() is used.");
static PyObject *
time_mktime(PyObject *self, PyObject *tup)
{
- struct tm buf;
- time_t tt;
- if (!gettmarg(tup, &buf))
- return NULL;
- tt = mktime(&buf);
- if (tt == (time_t)(-1)) {
- PyErr_SetString(PyExc_OverflowError,
- "mktime argument out of range");
- return NULL;
- }
- return PyFloat_FromDouble((double)tt);
+ struct tm buf;
+ time_t tt;
+ if (!gettmarg(tup, &buf))
+ return NULL;
+ tt = mktime(&buf);
+ if (tt == (time_t)(-1)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "mktime argument out of range");
+ return NULL;
+ }
+ return PyFloat_FromDouble((double)tt);
}
PyDoc_STRVAR(mktime_doc,
@@ -723,21 +723,21 @@ static void PyInit_timezone(PyObject *module);
static PyObject *
time_tzset(PyObject *self, PyObject *unused)
{
- PyObject* m;
+ PyObject* m;
- m = PyImport_ImportModuleNoBlock("time");
- if (m == NULL) {
- return NULL;
- }
+ m = PyImport_ImportModuleNoBlock("time");
+ if (m == NULL) {
+ return NULL;
+ }
- tzset();
+ tzset();
- /* Reset timezone, altzone, daylight and tzname */
- PyInit_timezone(m);
- Py_DECREF(m);
+ /* Reset timezone, altzone, daylight and tzname */
+ PyInit_timezone(m);
+ Py_DECREF(m);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(tzset_doc,
@@ -757,115 +757,115 @@ should not be relied on.");
static void
PyInit_timezone(PyObject *m) {
/* This code moved from PyInit_time wholesale to allow calling it from
- time_tzset. In the future, some parts of it can be moved back
- (for platforms that don't HAVE_WORKING_TZSET, when we know what they
- are), and the extraneous calls to tzset(3) should be removed.
- I haven't done this yet, as I don't want to change this code as
- little as possible when introducing the time.tzset and time.tzsetwall
- methods. This should simply be a method of doing the following once,
- at the top of this function and removing the call to tzset() from
- time_tzset():
-
- #ifdef HAVE_TZSET
- tzset()
- #endif
-
- And I'm lazy and hate C so nyer.
+ time_tzset. In the future, some parts of it can be moved back
+ (for platforms that don't HAVE_WORKING_TZSET, when we know what they
+ are), and the extraneous calls to tzset(3) should be removed.
+ I haven't done this yet, as I don't want to change this code as
+ little as possible when introducing the time.tzset and time.tzsetwall
+ methods. This should simply be a method of doing the following once,
+ at the top of this function and removing the call to tzset() from
+ time_tzset():
+
+ #ifdef HAVE_TZSET
+ tzset()
+ #endif
+
+ And I'm lazy and hate C so nyer.
*/
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
- PyObject *otz0, *otz1;
- tzset();
+ PyObject *otz0, *otz1;
+ tzset();
#ifdef PYOS_OS2
- PyModule_AddIntConstant(m, "timezone", _timezone);
+ PyModule_AddIntConstant(m, "timezone", _timezone);
#else /* !PYOS_OS2 */
- PyModule_AddIntConstant(m, "timezone", timezone);
+ PyModule_AddIntConstant(m, "timezone", timezone);
#endif /* PYOS_OS2 */
#ifdef HAVE_ALTZONE
- PyModule_AddIntConstant(m, "altzone", altzone);
+ PyModule_AddIntConstant(m, "altzone", altzone);
#else
#ifdef PYOS_OS2
- PyModule_AddIntConstant(m, "altzone", _timezone-3600);
+ PyModule_AddIntConstant(m, "altzone", _timezone-3600);
#else /* !PYOS_OS2 */
- PyModule_AddIntConstant(m, "altzone", timezone-3600);
+ PyModule_AddIntConstant(m, "altzone", timezone-3600);
#endif /* PYOS_OS2 */
#endif
- PyModule_AddIntConstant(m, "daylight", daylight);
- otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
- otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
- PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
+ PyModule_AddIntConstant(m, "daylight", daylight);
+ otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
+ otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
+ PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
#ifdef HAVE_STRUCT_TM_TM_ZONE
- {
+ {
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
- time_t t;
- struct tm *p;
- long janzone, julyzone;
- char janname[10], julyname[10];
- t = (time((time_t *)0) / YEAR) * YEAR;
- p = localtime(&t);
- janzone = -p->tm_gmtoff;
- strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
- janname[9] = '\0';
- t += YEAR/2;
- p = localtime(&t);
- julyzone = -p->tm_gmtoff;
- strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
- julyname[9] = '\0';
-
- if( janzone < julyzone ) {
- /* DST is reversed in the southern hemisphere */
- PyModule_AddIntConstant(m, "timezone", julyzone);
- PyModule_AddIntConstant(m, "altzone", janzone);
- PyModule_AddIntConstant(m, "daylight",
- janzone != julyzone);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)",
- julyname, janname));
- } else {
- PyModule_AddIntConstant(m, "timezone", janzone);
- PyModule_AddIntConstant(m, "altzone", julyzone);
- PyModule_AddIntConstant(m, "daylight",
- janzone != julyzone);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)",
- janname, julyname));
- }
- }
+ time_t t;
+ struct tm *p;
+ long janzone, julyzone;
+ char janname[10], julyname[10];
+ t = (time((time_t *)0) / YEAR) * YEAR;
+ p = localtime(&t);
+ janzone = -p->tm_gmtoff;
+ strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
+ janname[9] = '\0';
+ t += YEAR/2;
+ p = localtime(&t);
+ julyzone = -p->tm_gmtoff;
+ strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
+ julyname[9] = '\0';
+
+ if( janzone < julyzone ) {
+ /* DST is reversed in the southern hemisphere */
+ PyModule_AddIntConstant(m, "timezone", julyzone);
+ PyModule_AddIntConstant(m, "altzone", janzone);
+ PyModule_AddIntConstant(m, "daylight",
+ janzone != julyzone);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)",
+ julyname, janname));
+ } else {
+ PyModule_AddIntConstant(m, "timezone", janzone);
+ PyModule_AddIntConstant(m, "altzone", julyzone);
+ PyModule_AddIntConstant(m, "daylight",
+ janzone != julyzone);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)",
+ janname, julyname));
+ }
+ }
#else
#endif /* HAVE_STRUCT_TM_TM_ZONE */
#ifdef __CYGWIN__
- tzset();
- PyModule_AddIntConstant(m, "timezone", _timezone);
- PyModule_AddIntConstant(m, "altzone", _timezone-3600);
- PyModule_AddIntConstant(m, "daylight", _daylight);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
+ tzset();
+ PyModule_AddIntConstant(m, "timezone", _timezone);
+ PyModule_AddIntConstant(m, "altzone", _timezone-3600);
+ PyModule_AddIntConstant(m, "daylight", _daylight);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
#endif /* __CYGWIN__ */
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
}
static PyMethodDef time_methods[] = {
- {"time", time_time, METH_NOARGS, time_doc},
+ {"time", time_time, METH_NOARGS, time_doc},
#ifdef HAVE_CLOCK
- {"clock", time_clock, METH_NOARGS, clock_doc},
+ {"clock", time_clock, METH_NOARGS, clock_doc},
#endif
- {"sleep", time_sleep, METH_VARARGS, sleep_doc},
- {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
- {"localtime", time_localtime, METH_VARARGS, localtime_doc},
- {"asctime", time_asctime, METH_VARARGS, asctime_doc},
- {"ctime", time_ctime, METH_VARARGS, ctime_doc},
+ {"sleep", time_sleep, METH_VARARGS, sleep_doc},
+ {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
+ {"localtime", time_localtime, METH_VARARGS, localtime_doc},
+ {"asctime", time_asctime, METH_VARARGS, asctime_doc},
+ {"ctime", time_ctime, METH_VARARGS, ctime_doc},
#ifdef HAVE_MKTIME
- {"mktime", time_mktime, METH_O, mktime_doc},
+ {"mktime", time_mktime, METH_O, mktime_doc},
#endif
#ifdef HAVE_STRFTIME
- {"strftime", time_strftime, METH_VARARGS, strftime_doc},
+ {"strftime", time_strftime, METH_VARARGS, strftime_doc},
#endif
- {"strptime", time_strptime, METH_VARARGS, strptime_doc},
+ {"strptime", time_strptime, METH_VARARGS, strptime_doc},
#ifdef HAVE_WORKING_TZSET
- {"tzset", time_tzset, METH_NOARGS, tzset_doc},
+ {"tzset", time_tzset, METH_NOARGS, tzset_doc},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
@@ -917,53 +917,53 @@ tzset() -- change the local timezone");
static struct PyModuleDef timemodule = {
- PyModuleDef_HEAD_INIT,
- "time",
- module_doc,
- -1,
- time_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "time",
+ module_doc,
+ -1,
+ time_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_time(void)
{
- PyObject *m;
- char *p;
- m = PyModule_Create(&timemodule);
- if (m == NULL)
- return NULL;
-
- /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
- p = Py_GETENV("PYTHONY2K");
- PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
- /* Squirrel away the module's dictionary for the y2k check */
- moddict = PyModule_GetDict(m);
- Py_INCREF(moddict);
-
- /* Set, or reset, module variables like time.timezone */
- PyInit_timezone(m);
+ PyObject *m;
+ char *p;
+ m = PyModule_Create(&timemodule);
+ if (m == NULL)
+ return NULL;
+
+ /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
+ p = Py_GETENV("PYTHONY2K");
+ PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
+ /* Squirrel away the module's dictionary for the y2k check */
+ moddict = PyModule_GetDict(m);
+ Py_INCREF(moddict);
+
+ /* Set, or reset, module variables like time.timezone */
+ PyInit_timezone(m);
#ifdef MS_WINDOWS
- /* Helper to allow interrupts for Windows.
- If Ctrl+C event delivered while not sleeping
- it will be ignored.
- */
- main_thread = PyThread_get_thread_ident();
- hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
- SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
+ /* Helper to allow interrupts for Windows.
+ If Ctrl+C event delivered while not sleeping
+ it will be ignored.
+ */
+ main_thread = PyThread_get_thread_ident();
+ hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+ SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
#endif /* MS_WINDOWS */
- if (!initialized) {
- PyStructSequence_InitType(&StructTimeType,
- &struct_time_type_desc);
- }
- Py_INCREF(&StructTimeType);
- PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
- initialized = 1;
- return m;
+ if (!initialized) {
+ PyStructSequence_InitType(&StructTimeType,
+ &struct_time_type_desc);
+ }
+ Py_INCREF(&StructTimeType);
+ PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
+ initialized = 1;
+ return m;
}
@@ -972,38 +972,38 @@ PyInit_time(void)
static double
floattime(void)
{
- /* There are three ways to get the time:
- (1) gettimeofday() -- resolution in microseconds
- (2) ftime() -- resolution in milliseconds
- (3) time() -- resolution in seconds
- In all cases the return value is a float in seconds.
- Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
- fail, so we fall back on ftime() or time().
- Note: clock resolution does not imply clock accuracy! */
+ /* There are three ways to get the time:
+ (1) gettimeofday() -- resolution in microseconds
+ (2) ftime() -- resolution in milliseconds
+ (3) time() -- resolution in seconds
+ In all cases the return value is a float in seconds.
+ Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
+ fail, so we fall back on ftime() or time().
+ Note: clock resolution does not imply clock accuracy! */
#ifdef HAVE_GETTIMEOFDAY
- {
- struct timeval t;
+ {
+ struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
- if (gettimeofday(&t) == 0)
- return (double)t.tv_sec + t.tv_usec*0.000001;
+ if (gettimeofday(&t) == 0)
+ return (double)t.tv_sec + t.tv_usec*0.000001;
#else /* !GETTIMEOFDAY_NO_TZ */
- if (gettimeofday(&t, (struct timezone *)NULL) == 0)
- return (double)t.tv_sec + t.tv_usec*0.000001;
+ if (gettimeofday(&t, (struct timezone *)NULL) == 0)
+ return (double)t.tv_sec + t.tv_usec*0.000001;
#endif /* !GETTIMEOFDAY_NO_TZ */
- }
+ }
#endif /* !HAVE_GETTIMEOFDAY */
- {
+ {
#if defined(HAVE_FTIME)
- struct timeb t;
- ftime(&t);
- return (double)t.time + (double)t.millitm * (double)0.001;
+ struct timeb t;
+ ftime(&t);
+ return (double)t.time + (double)t.millitm * (double)0.001;
#else /* !HAVE_FTIME */
- time_t secs;
- time(&secs);
- return (double)secs;
+ time_t secs;
+ time(&secs);
+ return (double)secs;
#endif /* !HAVE_FTIME */
- }
+ }
}
@@ -1016,80 +1016,80 @@ floatsleep(double secs)
{
/* XXX Should test for MS_WINDOWS first! */
#if defined(HAVE_SELECT) && !defined(__EMX__)
- struct timeval t;
- double frac;
- frac = fmod(secs, 1.0);
- secs = floor(secs);
- t.tv_sec = (long)secs;
- t.tv_usec = (long)(frac*1000000.0);
- Py_BEGIN_ALLOW_THREADS
- if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
+ struct timeval t;
+ double frac;
+ frac = fmod(secs, 1.0);
+ secs = floor(secs);
+ t.tv_sec = (long)secs;
+ t.tv_usec = (long)(frac*1000000.0);
+ Py_BEGIN_ALLOW_THREADS
+ if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
#ifdef EINTR
- if (errno != EINTR) {
+ if (errno != EINTR) {
#else
- if (1) {
+ if (1) {
#endif
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- }
- Py_END_ALLOW_THREADS
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ }
+ Py_END_ALLOW_THREADS
#elif defined(__WATCOMC__) && !defined(__QNX__)
- /* XXX Can't interrupt this sleep */
- Py_BEGIN_ALLOW_THREADS
- delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
- Py_END_ALLOW_THREADS
+ /* XXX Can't interrupt this sleep */
+ Py_BEGIN_ALLOW_THREADS
+ delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
+ Py_END_ALLOW_THREADS
#elif defined(MS_WINDOWS)
- {
- double millisecs = secs * 1000.0;
- unsigned long ul_millis;
-
- if (millisecs > (double)ULONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "sleep length is too large");
- return -1;
- }
- Py_BEGIN_ALLOW_THREADS
- /* Allow sleep(0) to maintain win32 semantics, and as decreed
- * by Guido, only the main thread can be interrupted.
- */
- ul_millis = (unsigned long)millisecs;
- if (ul_millis == 0 ||
- main_thread != PyThread_get_thread_ident())
- Sleep(ul_millis);
- else {
- DWORD rc;
- ResetEvent(hInterruptEvent);
- rc = WaitForSingleObject(hInterruptEvent, ul_millis);
- if (rc == WAIT_OBJECT_0) {
- /* Yield to make sure real Python signal
- * handler called.
- */
- Sleep(1);
- Py_BLOCK_THREADS
- errno = EINTR;
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- }
- Py_END_ALLOW_THREADS
- }
+ {
+ double millisecs = secs * 1000.0;
+ unsigned long ul_millis;
+
+ if (millisecs > (double)ULONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "sleep length is too large");
+ return -1;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ /* Allow sleep(0) to maintain win32 semantics, and as decreed
+ * by Guido, only the main thread can be interrupted.
+ */
+ ul_millis = (unsigned long)millisecs;
+ if (ul_millis == 0 ||
+ main_thread != PyThread_get_thread_ident())
+ Sleep(ul_millis);
+ else {
+ DWORD rc;
+ ResetEvent(hInterruptEvent);
+ rc = WaitForSingleObject(hInterruptEvent, ul_millis);
+ if (rc == WAIT_OBJECT_0) {
+ /* Yield to make sure real Python signal
+ * handler called.
+ */
+ Sleep(1);
+ Py_BLOCK_THREADS
+ errno = EINTR;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ }
+ Py_END_ALLOW_THREADS
+ }
#elif defined(PYOS_OS2)
- /* This Sleep *IS* Interruptable by Exceptions */
- Py_BEGIN_ALLOW_THREADS
- if (DosSleep(secs * 1000) != NO_ERROR) {
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- Py_END_ALLOW_THREADS
+ /* This Sleep *IS* Interruptable by Exceptions */
+ Py_BEGIN_ALLOW_THREADS
+ if (DosSleep(secs * 1000) != NO_ERROR) {
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ Py_END_ALLOW_THREADS
#else
- /* XXX Can't interrupt this sleep */
- Py_BEGIN_ALLOW_THREADS
- sleep((int)secs);
- Py_END_ALLOW_THREADS
+ /* XXX Can't interrupt this sleep */
+ Py_BEGIN_ALLOW_THREADS
+ sleep((int)secs);
+ Py_END_ALLOW_THREADS
#endif
- return 0;
+ return 0;
}
diff --git a/Modules/tkappinit.c b/Modules/tkappinit.c
index cfbd20c..c1f97b0 100644
--- a/Modules/tkappinit.c
+++ b/Modules/tkappinit.c
@@ -26,154 +26,154 @@ static int tk_load_failed;
int
Tcl_AppInit(Tcl_Interp *interp)
{
- Tk_Window main_window;
- const char *_tkinter_skip_tk_init;
+ Tk_Window main_window;
+ const char *_tkinter_skip_tk_init;
#ifdef TKINTER_PROTECT_LOADTK
- const char *_tkinter_tk_failed;
+ const char *_tkinter_tk_failed;
#endif
#ifdef TK_AQUA
#ifndef MAX_PATH_LEN
#define MAX_PATH_LEN 1024
#endif
- char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN];
- Tcl_Obj* pathPtr;
+ char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN];
+ Tcl_Obj* pathPtr;
- /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */
- Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary",
- tclLibPath, MAX_PATH_LEN, 0);
+ /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */
+ Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary",
+ tclLibPath, MAX_PATH_LEN, 0);
- if (tclLibPath[0] != '\0') {
- Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
- }
-
- if (tclLibPath[0] != '\0') {
- Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
- }
+ if (tclLibPath[0] != '\0') {
+ Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
+ }
+
+ if (tclLibPath[0] != '\0') {
+ Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
+ }
#endif
- if (Tcl_Init (interp) == TCL_ERROR)
- return TCL_ERROR;
+ if (Tcl_Init (interp) == TCL_ERROR)
+ return TCL_ERROR;
#ifdef TK_AQUA
- /* pre- Tk_Init code copied from tkMacOSXAppInit.c */
- Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary",
- tkLibPath, MAX_PATH_LEN, 1);
+ /* pre- Tk_Init code copied from tkMacOSXAppInit.c */
+ Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary",
+ tkLibPath, MAX_PATH_LEN, 1);
- if (tclLibPath[0] != '\0') {
- pathPtr = Tcl_NewStringObj(tclLibPath, -1);
- } else {
- Tcl_Obj *pathPtr = TclGetLibraryPath();
- }
+ if (tclLibPath[0] != '\0') {
+ pathPtr = Tcl_NewStringObj(tclLibPath, -1);
+ } else {
+ Tcl_Obj *pathPtr = TclGetLibraryPath();
+ }
- if (tkLibPath[0] != '\0') {
- Tcl_Obj *objPtr;
+ if (tkLibPath[0] != '\0') {
+ Tcl_Obj *objPtr;
- Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY);
- objPtr = Tcl_NewStringObj(tkLibPath, -1);
- Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
- }
+ Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY);
+ objPtr = Tcl_NewStringObj(tkLibPath, -1);
+ Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
+ }
- TclSetLibraryPath(pathPtr);
+ TclSetLibraryPath(pathPtr);
#endif
#ifdef WITH_XXX
- /* Initialize modules that don't require Tk */
+ /* Initialize modules that don't require Tk */
#endif
- _tkinter_skip_tk_init = Tcl_GetVar(interp,
- "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
- if (_tkinter_skip_tk_init != NULL &&
- strcmp(_tkinter_skip_tk_init, "1") == 0) {
- return TCL_OK;
- }
+ _tkinter_skip_tk_init = Tcl_GetVar(interp,
+ "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
+ if (_tkinter_skip_tk_init != NULL &&
+ strcmp(_tkinter_skip_tk_init, "1") == 0) {
+ return TCL_OK;
+ }
#ifdef TKINTER_PROTECT_LOADTK
- _tkinter_tk_failed = Tcl_GetVar(interp,
- "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
+ _tkinter_tk_failed = Tcl_GetVar(interp,
+ "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
- if (tk_load_failed || (
- _tkinter_tk_failed != NULL &&
- strcmp(_tkinter_tk_failed, "1") == 0)) {
- Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC);
- return TCL_ERROR;
- }
+ if (tk_load_failed || (
+ _tkinter_tk_failed != NULL &&
+ strcmp(_tkinter_tk_failed, "1") == 0)) {
+ Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC);
+ return TCL_ERROR;
+ }
#endif
- if (Tk_Init(interp) == TCL_ERROR) {
+ if (Tk_Init(interp) == TCL_ERROR) {
#ifdef TKINTER_PROTECT_LOADTK
- tk_load_failed = 1;
- Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
+ tk_load_failed = 1;
+ Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
#endif
- return TCL_ERROR;
- }
+ return TCL_ERROR;
+ }
- main_window = Tk_MainWindow(interp);
+ main_window = Tk_MainWindow(interp);
#ifdef TK_AQUA
- TkMacOSXInitAppleEvents(interp);
- TkMacOSXInitMenus(interp);
+ TkMacOSXInitAppleEvents(interp);
+ TkMacOSXInitMenus(interp);
#endif
-
+
#ifdef WITH_MOREBUTTONS
- {
- extern Tcl_CmdProc studButtonCmd;
- extern Tcl_CmdProc triButtonCmd;
+ {
+ extern Tcl_CmdProc studButtonCmd;
+ extern Tcl_CmdProc triButtonCmd;
- Tcl_CreateCommand(interp, "studbutton", studButtonCmd,
- (ClientData) main_window, NULL);
- Tcl_CreateCommand(interp, "tributton", triButtonCmd,
- (ClientData) main_window, NULL);
- }
+ Tcl_CreateCommand(interp, "studbutton", studButtonCmd,
+ (ClientData) main_window, NULL);
+ Tcl_CreateCommand(interp, "tributton", triButtonCmd,
+ (ClientData) main_window, NULL);
+ }
#endif
#ifdef WITH_PIL /* 0.2b5 and later -- not yet released as of May 14 */
- {
- extern void TkImaging_Init(Tcl_Interp *);
- TkImaging_Init(interp);
- /* XXX TkImaging_Init() doesn't have the right return type */
- /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
- }
+ {
+ extern void TkImaging_Init(Tcl_Interp *);
+ TkImaging_Init(interp);
+ /* XXX TkImaging_Init() doesn't have the right return type */
+ /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
+ }
#endif
#ifdef WITH_PIL_OLD /* 0.2b4 and earlier */
- {
- extern void TkImaging_Init(void);
- /* XXX TkImaging_Init() doesn't have the right prototype */
- /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
- }
+ {
+ extern void TkImaging_Init(void);
+ /* XXX TkImaging_Init() doesn't have the right prototype */
+ /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
+ }
#endif
#ifdef WITH_TIX
- {
- extern int Tix_Init(Tcl_Interp *interp);
- extern int Tix_SafeInit(Tcl_Interp *interp);
- Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit);
- }
+ {
+ extern int Tix_Init(Tcl_Interp *interp);
+ extern int Tix_SafeInit(Tcl_Interp *interp);
+ Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit);
+ }
#endif
#ifdef WITH_BLT
- {
- extern int Blt_Init(Tcl_Interp *);
- extern int Blt_SafeInit(Tcl_Interp *);
- Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit);
- }
+ {
+ extern int Blt_Init(Tcl_Interp *);
+ extern int Blt_SafeInit(Tcl_Interp *);
+ Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit);
+ }
#endif
#ifdef WITH_TOGL
- {
- /* XXX I've heard rumors that this doesn't work */
- extern int Togl_Init(Tcl_Interp *);
- /* XXX Is there no Togl_SafeInit? */
- Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL);
- }
+ {
+ /* XXX I've heard rumors that this doesn't work */
+ extern int Togl_Init(Tcl_Interp *);
+ /* XXX Is there no Togl_SafeInit? */
+ Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL);
+ }
#endif
#ifdef WITH_XXX
#endif
- return TCL_OK;
+ return TCL_OK;
}
diff --git a/Modules/unicodedata.c b/Modules/unicodedata.c
index 92c312b..538c8ca 100644
--- a/Modules/unicodedata.c
+++ b/Modules/unicodedata.c
@@ -19,14 +19,14 @@
/* character properties */
typedef struct {
- const unsigned char category; /* index into
- _PyUnicode_CategoryNames */
- const unsigned char combining; /* combining class value 0 - 255 */
- const unsigned char bidirectional; /* index into
- _PyUnicode_BidirectionalNames */
- const unsigned char mirrored; /* true if mirrored in bidir mode */
- const unsigned char east_asian_width; /* index into
- _PyUnicode_EastAsianWidth */
+ const unsigned char category; /* index into
+ _PyUnicode_CategoryNames */
+ const unsigned char combining; /* combining class value 0 - 255 */
+ const unsigned char bidirectional; /* index into
+ _PyUnicode_BidirectionalNames */
+ const unsigned char mirrored; /* true if mirrored in bidir mode */
+ const unsigned char east_asian_width; /* index into
+ _PyUnicode_EastAsianWidth */
const unsigned char normalization_quick_check; /* see is_normalized() */
} _PyUnicode_DatabaseRecord;
@@ -67,7 +67,7 @@ typedef struct previous_version {
#define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v))
static PyMemberDef DB_members[] = {
- {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
+ {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
{NULL}
};
@@ -79,14 +79,14 @@ static PyObject*
new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4),
Py_UCS4 (*normalization)(Py_UCS4))
{
- PreviousDBVersion *self;
- self = PyObject_New(PreviousDBVersion, &UCD_Type);
- if (self == NULL)
- return NULL;
- self->name = name;
- self->getrecord = getrecord;
+ PreviousDBVersion *self;
+ self = PyObject_New(PreviousDBVersion, &UCD_Type);
+ if (self == NULL)
+ return NULL;
+ self->name = name;
+ self->getrecord = getrecord;
self->normalization = normalization;
- return (PyObject*)self;
+ return (PyObject*)self;
}
@@ -95,12 +95,12 @@ static Py_UCS4 getuchar(PyUnicodeObject *obj)
Py_UNICODE *v = PyUnicode_AS_UNICODE(obj);
if (PyUnicode_GET_SIZE(obj) == 1)
- return *v;
+ return *v;
#ifndef Py_UNICODE_WIDE
else if ((PyUnicode_GET_SIZE(obj) == 2) &&
(0xD800 <= v[0] && v[0] <= 0xDBFF) &&
(0xDC00 <= v[1] && v[1] <= 0xDFFF))
- return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000;
+ return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000;
#endif
PyErr_SetString(PyExc_TypeError,
"need a single Unicode character as parameter");
@@ -137,7 +137,7 @@ unicodedata_decimal(PyObject *self, PyObject *args)
/* unassigned */
have_old = 1;
rc = -1;
- }
+ }
else if (old->decimal_changed != 0xFF) {
have_old = 1;
rc = old->decimal_changed;
@@ -147,15 +147,15 @@ unicodedata_decimal(PyObject *self, PyObject *args)
if (!have_old)
rc = Py_UNICODE_TODECIMAL(c);
if (rc < 0) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "not a decimal");
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "not a decimal");
return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyLong_FromLong(rc);
}
@@ -182,14 +182,14 @@ unicodedata_digit(PyObject *self, PyObject *args)
return NULL;
rc = Py_UNICODE_TODIGIT(c);
if (rc < 0) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "not a digit");
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "not a digit");
return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyLong_FromLong(rc);
}
@@ -222,7 +222,7 @@ unicodedata_numeric(PyObject *self, PyObject *args)
/* unassigned */
have_old = 1;
rc = -1.0;
- }
+ }
else if (old->decimal_changed != 0xFF) {
have_old = 1;
rc = old->decimal_changed;
@@ -232,14 +232,14 @@ unicodedata_numeric(PyObject *self, PyObject *args)
if (!have_old)
rc = Py_UNICODE_TONUMERIC(c);
if (rc == -1.0) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "not a numeric character");
- return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "not a numeric character");
+ return NULL;
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyFloat_FromDouble(rc);
}
@@ -258,8 +258,8 @@ unicodedata_category(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:category",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -287,8 +287,8 @@ unicodedata_bidirectional(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:bidirectional",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -318,8 +318,8 @@ unicodedata_combining(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:combining",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -347,8 +347,8 @@ unicodedata_mirrored(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:mirrored",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -377,8 +377,8 @@ unicodedata_east_asian_width(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:east_asian_width",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -408,8 +408,8 @@ unicodedata_decomposition(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:decomposition",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -455,7 +455,7 @@ unicodedata_decomposition(PyObject *self, PyObject *args)
decomp_data[++index]);
i += strlen(decomp + i);
}
-
+
decomp[i] = '\0';
return PyUnicode_FromString(decomp);
@@ -466,7 +466,7 @@ get_decomp_record(PyObject *self, Py_UCS4 code, int *index, int *prefix, int *co
{
if (code >= 0x110000) {
*index = 0;
- } else if (self && UCD_Check(self) &&
+ } else if (self && UCD_Check(self) &&
get_old_record(self, code)->category_changed==0) {
/* unassigned in old version */
*index = 0;
@@ -476,7 +476,7 @@ get_decomp_record(PyObject *self, Py_UCS4 code, int *index, int *prefix, int *co
*index = decomp_index2[(*index<<DECOMP_SHIFT)+
(code&((1<<DECOMP_SHIFT)-1))];
}
-
+
/* high byte is number of hex bytes (usually one or two), low byte
is prefix code (from*/
*count = decomp_data[*index] >> 8;
@@ -501,11 +501,11 @@ nfd_nfkd(PyObject *self, PyObject *input, int k)
PyObject *result;
Py_UNICODE *i, *end, *o;
/* Longest decomposition in Unicode 3.2: U+FDFA */
- Py_UNICODE stack[20];
+ Py_UNICODE stack[20];
Py_ssize_t space, isize;
int index, prefix, count, stackptr;
unsigned char prev, cur;
-
+
stackptr = 0;
isize = PyUnicode_GET_SIZE(input);
/* Overallocate atmost 10 characters. */
@@ -642,12 +642,12 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
i = PyUnicode_AS_UNICODE(result);
end = i + PyUnicode_GET_SIZE(result);
o = PyUnicode_AS_UNICODE(result);
-
+
again:
while (i < end) {
for (index = 0; index < cskipped; index++) {
if (skipped[index] == i) {
- /* *i character is skipped.
+ /* *i character is skipped.
Remove from list. */
skipped[index] = skipped[cskipped-1];
cskipped--;
@@ -658,7 +658,7 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
/* Hangul Composition. We don't need to check for <LV,T>
pairs, since we always have decomposed data. */
if (LBase <= *i && *i < (LBase+LCount) &&
- i + 1 < end &&
+ i + 1 < end &&
VBase <= i[1] && i[1] <= (VBase+VCount)) {
int LIndex, VIndex;
LIndex = i[0] - LBase;
@@ -707,7 +707,7 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
(index&((1<<COMP_SHIFT)-1))];
if (code == 0)
goto not_combinable;
-
+
/* Replace the original character. */
*i = code;
/* Mark the second character unused. */
@@ -891,29 +891,29 @@ _getucname(PyObject *self, Py_UCS4 code, char* buffer, int buflen)
if (old->category_changed == 0) {
/* unassigned */
return 0;
- }
+ }
}
if (SBase <= code && code < SBase+SCount) {
- /* Hangul syllable. */
- int SIndex = code - SBase;
- int L = SIndex / NCount;
- int V = (SIndex % NCount) / TCount;
- int T = SIndex % TCount;
-
- if (buflen < 27)
- /* Worst case: HANGUL SYLLABLE <10chars>. */
- return 0;
- strcpy(buffer, "HANGUL SYLLABLE ");
- buffer += 16;
- strcpy(buffer, hangul_syllables[L][0]);
- buffer += strlen(hangul_syllables[L][0]);
- strcpy(buffer, hangul_syllables[V][1]);
- buffer += strlen(hangul_syllables[V][1]);
- strcpy(buffer, hangul_syllables[T][2]);
- buffer += strlen(hangul_syllables[T][2]);
- *buffer = '\0';
- return 1;
+ /* Hangul syllable. */
+ int SIndex = code - SBase;
+ int L = SIndex / NCount;
+ int V = (SIndex % NCount) / TCount;
+ int T = SIndex % TCount;
+
+ if (buflen < 27)
+ /* Worst case: HANGUL SYLLABLE <10chars>. */
+ return 0;
+ strcpy(buffer, "HANGUL SYLLABLE ");
+ buffer += 16;
+ strcpy(buffer, hangul_syllables[L][0]);
+ buffer += strlen(hangul_syllables[L][0]);
+ strcpy(buffer, hangul_syllables[V][1]);
+ buffer += strlen(hangul_syllables[V][1]);
+ strcpy(buffer, hangul_syllables[T][2]);
+ buffer += strlen(hangul_syllables[T][2]);
+ *buffer = '\0';
+ return 1;
}
if (is_unified_ideograph(code)) {
@@ -980,23 +980,23 @@ _cmpname(PyObject *self, int code, const char* name, int namelen)
return buffer[namelen] == '\0';
}
-static void
+static void
find_syllable(const char *str, int *len, int *pos, int count, int column)
{
int i, len1;
*len = -1;
for (i = 0; i < count; i++) {
- char *s = hangul_syllables[i][column];
- len1 = strlen(s);
- if (len1 <= *len)
- continue;
- if (strncmp(str, s, len1) == 0) {
- *len = len1;
- *pos = i;
- }
+ char *s = hangul_syllables[i][column];
+ len1 = strlen(s);
+ if (len1 <= *len)
+ continue;
+ if (strncmp(str, s, len1) == 0) {
+ *len = len1;
+ *pos = i;
+ }
}
if (*len == -1) {
- *len = 0;
+ *len = 0;
}
}
@@ -1009,18 +1009,18 @@ _getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code)
/* Check for hangul syllables. */
if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) {
- int len, L = -1, V = -1, T = -1;
- const char *pos = name + 16;
- find_syllable(pos, &len, &L, LCount, 0);
- pos += len;
- find_syllable(pos, &len, &V, VCount, 1);
- pos += len;
- find_syllable(pos, &len, &T, TCount, 2);
- pos += len;
- if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
- *code = SBase + (L*VCount+V)*TCount + T;
- return 1;
- }
+ int len, L = -1, V = -1, T = -1;
+ const char *pos = name + 16;
+ find_syllable(pos, &len, &L, LCount, 0);
+ pos += len;
+ find_syllable(pos, &len, &V, VCount, 1);
+ pos += len;
+ find_syllable(pos, &len, &T, TCount, 2);
+ pos += len;
+ if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
+ *code = SBase + (L*VCount+V)*TCount + T;
+ return 1;
+ }
/* Otherwise, it's an illegal syllable name. */
return 0;
}
@@ -1080,7 +1080,7 @@ _getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code)
}
}
-static const _PyUnicode_Name_CAPI hashAPI =
+static const _PyUnicode_Name_CAPI hashAPI =
{
sizeof(_PyUnicode_Name_CAPI),
_getucname,
@@ -1112,14 +1112,14 @@ unicodedata_name(PyObject* self, PyObject* args)
return NULL;
if (!_getucname(self, c, name, sizeof(name))) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "no such name");
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "no such name");
return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyUnicode_FromString(name);
@@ -1157,7 +1157,7 @@ unicodedata_lookup(PyObject* self, PyObject* args)
}
#endif
str[0] = (Py_UNICODE) code;
- return PyUnicode_FromUnicode(str, 1);
+ return PyUnicode_FromUnicode(str, 1);
}
/* XXX Add doc strings. */
@@ -1182,27 +1182,27 @@ static PyMethodDef unicodedata_functions[] = {
{"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__},
{"normalize", unicodedata_normalize, METH_VARARGS,
unicodedata_normalize__doc__},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject UCD_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "unicodedata.UCD", /*tp_name*/
- sizeof(PreviousDBVersion), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)PyObject_Del, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "unicodedata.UCD", /*tp_name*/
+ sizeof(PreviousDBVersion), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)PyObject_Del, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr,/*tp_getattro*/
@@ -1243,15 +1243,15 @@ http://www.unicode.org/reports/tr44/tr44-4.html).");
static struct PyModuleDef unicodedatamodule = {
- PyModuleDef_HEAD_INIT,
- "unicodedata",
- unicodedata_docstring,
- -1,
- unicodedata_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "unicodedata",
+ unicodedata_docstring,
+ -1,
+ unicodedata_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -1281,7 +1281,7 @@ PyInit_unicodedata(void)
return m;
}
-/*
+/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
diff --git a/Modules/xxmodule.c b/Modules/xxmodule.c
index a31341c..92c7673 100644
--- a/Modules/xxmodule.c
+++ b/Modules/xxmodule.c
@@ -19,23 +19,23 @@
static PyObject *ErrorObject;
typedef struct {
- PyObject_HEAD
- PyObject *x_attr; /* Attributes dictionary */
+ PyObject_HEAD
+ PyObject *x_attr; /* Attributes dictionary */
} XxoObject;
static PyTypeObject Xxo_Type;
-#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type)
+#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type)
static XxoObject *
newXxoObject(PyObject *arg)
{
- XxoObject *self;
- self = PyObject_New(XxoObject, &Xxo_Type);
- if (self == NULL)
- return NULL;
- self->x_attr = NULL;
- return self;
+ XxoObject *self;
+ self = PyObject_New(XxoObject, &Xxo_Type);
+ if (self == NULL)
+ return NULL;
+ self->x_attr = NULL;
+ return self;
}
/* Xxo methods */
@@ -43,101 +43,101 @@ newXxoObject(PyObject *arg)
static void
Xxo_dealloc(XxoObject *self)
{
- Py_XDECREF(self->x_attr);
- PyObject_Del(self);
+ Py_XDECREF(self->x_attr);
+ PyObject_Del(self);
}
static PyObject *
Xxo_demo(XxoObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":demo"))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":demo"))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef Xxo_methods[] = {
- {"demo", (PyCFunction)Xxo_demo, METH_VARARGS,
- PyDoc_STR("demo() -> None")},
- {NULL, NULL} /* sentinel */
+ {"demo", (PyCFunction)Xxo_demo, METH_VARARGS,
+ PyDoc_STR("demo() -> None")},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
Xxo_getattro(XxoObject *self, PyObject *name)
{
- if (self->x_attr != NULL) {
- PyObject *v = PyDict_GetItem(self->x_attr, name);
- if (v != NULL) {
- Py_INCREF(v);
- return v;
- }
- }
- return PyObject_GenericGetAttr((PyObject *)self, name);
+ if (self->x_attr != NULL) {
+ PyObject *v = PyDict_GetItem(self->x_attr, name);
+ if (v != NULL) {
+ Py_INCREF(v);
+ return v;
+ }
+ }
+ return PyObject_GenericGetAttr((PyObject *)self, name);
}
static int
Xxo_setattr(XxoObject *self, char *name, PyObject *v)
{
- if (self->x_attr == NULL) {
- self->x_attr = PyDict_New();
- if (self->x_attr == NULL)
- return -1;
- }
- if (v == NULL) {
- int rv = PyDict_DelItemString(self->x_attr, name);
- if (rv < 0)
- PyErr_SetString(PyExc_AttributeError,
- "delete non-existing Xxo attribute");
- return rv;
- }
- else
- return PyDict_SetItemString(self->x_attr, name, v);
+ if (self->x_attr == NULL) {
+ self->x_attr = PyDict_New();
+ if (self->x_attr == NULL)
+ return -1;
+ }
+ if (v == NULL) {
+ int rv = PyDict_DelItemString(self->x_attr, name);
+ if (rv < 0)
+ PyErr_SetString(PyExc_AttributeError,
+ "delete non-existing Xxo attribute");
+ return rv;
+ }
+ else
+ return PyDict_SetItemString(self->x_attr, name, v);
}
static PyTypeObject Xxo_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "xxmodule.Xxo", /*tp_name*/
- sizeof(XxoObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)Xxo_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)Xxo_setattr, /*tp_setattr*/
- 0, /*tp_reserved*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- (getattrofunc)Xxo_getattro, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- Xxo_methods, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "xxmodule.Xxo", /*tp_name*/
+ sizeof(XxoObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)Xxo_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)Xxo_setattr, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ (getattrofunc)Xxo_getattro, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ Xxo_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
/* --------------------------------------------------------------------- */
@@ -151,12 +151,12 @@ Return the sum of i and j.");
static PyObject *
xx_foo(PyObject *self, PyObject *args)
{
- long i, j;
- long res;
- if (!PyArg_ParseTuple(args, "ll:foo", &i, &j))
- return NULL;
- res = i+j; /* XXX Do something here */
- return PyLong_FromLong(res);
+ long i, j;
+ long res;
+ if (!PyArg_ParseTuple(args, "ll:foo", &i, &j))
+ return NULL;
+ res = i+j; /* XXX Do something here */
+ return PyLong_FromLong(res);
}
@@ -165,14 +165,14 @@ xx_foo(PyObject *self, PyObject *args)
static PyObject *
xx_new(PyObject *self, PyObject *args)
{
- XxoObject *rv;
-
- if (!PyArg_ParseTuple(args, ":new"))
- return NULL;
- rv = newXxoObject(args);
- if (rv == NULL)
- return NULL;
- return (PyObject *)rv;
+ XxoObject *rv;
+
+ if (!PyArg_ParseTuple(args, ":new"))
+ return NULL;
+ rv = newXxoObject(args);
+ if (rv == NULL)
+ return NULL;
+ return (PyObject *)rv;
}
/* Example with subtle bug from extensions manual ("Thin Ice"). */
@@ -180,20 +180,20 @@ xx_new(PyObject *self, PyObject *args)
static PyObject *
xx_bug(PyObject *self, PyObject *args)
{
- PyObject *list, *item;
+ PyObject *list, *item;
- if (!PyArg_ParseTuple(args, "O:bug", &list))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:bug", &list))
+ return NULL;
- item = PyList_GetItem(list, 0);
- /* Py_INCREF(item); */
- PyList_SetItem(list, 1, PyLong_FromLong(0L));
- PyObject_Print(item, stdout, 0);
- printf("\n");
- /* Py_DECREF(item); */
+ item = PyList_GetItem(list, 0);
+ /* Py_INCREF(item); */
+ PyList_SetItem(list, 1, PyLong_FromLong(0L));
+ PyObject_Print(item, stdout, 0);
+ printf("\n");
+ /* Py_DECREF(item); */
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test bad format character */
@@ -201,61 +201,61 @@ xx_bug(PyObject *self, PyObject *args)
static PyObject *
xx_roj(PyObject *self, PyObject *args)
{
- PyObject *a;
- long b;
- if (!PyArg_ParseTuple(args, "O#:roj", &a, &b))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *a;
+ long b;
+ if (!PyArg_ParseTuple(args, "O#:roj", &a, &b))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* ---------- */
static PyTypeObject Str_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "xxmodule.Str", /*tp_name*/
- 0, /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- 0, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 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*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- 0, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /* see PyInit_xx */ /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "xxmodule.Str", /*tp_name*/
+ 0, /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ 0, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 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*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ 0, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /* see PyInit_xx */ /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
/* ---------- */
@@ -263,54 +263,54 @@ static PyTypeObject Str_Type = {
static PyObject *
null_richcompare(PyObject *self, PyObject *other, int op)
{
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyTypeObject Null_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "xxmodule.Null", /*tp_name*/
- 0, /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- 0, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_reserved*/
- 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*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- null_richcompare, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- 0, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /* see PyInit_xx */ /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /* see PyInit_xx */ /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "xxmodule.Null", /*tp_name*/
+ 0, /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ 0, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_reserved*/
+ 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*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ null_richcompare, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ 0, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /* see PyInit_xx */ /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /* see PyInit_xx */ /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -320,15 +320,15 @@ static PyTypeObject Null_Type = {
/* List of functions defined in the module */
static PyMethodDef xx_methods[] = {
- {"roj", xx_roj, METH_VARARGS,
- PyDoc_STR("roj(a,b) -> None")},
- {"foo", xx_foo, METH_VARARGS,
- xx_foo_doc},
- {"new", xx_new, METH_VARARGS,
- PyDoc_STR("new() -> new Xx object")},
- {"bug", xx_bug, METH_VARARGS,
- PyDoc_STR("bug(o) -> None")},
- {NULL, NULL} /* sentinel */
+ {"roj", xx_roj, METH_VARARGS,
+ PyDoc_STR("roj(a,b) -> None")},
+ {"foo", xx_foo, METH_VARARGS,
+ xx_foo_doc},
+ {"new", xx_new, METH_VARARGS,
+ PyDoc_STR("new() -> new Xx object")},
+ {"bug", xx_bug, METH_VARARGS,
+ PyDoc_STR("bug(o) -> None")},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@@ -338,59 +338,59 @@ PyDoc_STRVAR(module_doc,
static struct PyModuleDef xxmodule = {
- PyModuleDef_HEAD_INIT,
- "xx",
- module_doc,
- -1,
- xx_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "xx",
+ module_doc,
+ -1,
+ xx_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_xx(void)
{
- PyObject *m = NULL;
-
- /* Due to cross platform compiler issues the slots must be filled
- * here. It's required for portability to Windows without requiring
- * C++. */
- Null_Type.tp_base = &PyBaseObject_Type;
- Null_Type.tp_new = PyType_GenericNew;
- Str_Type.tp_base = &PyUnicode_Type;
-
- /* Finalize the type object including setting type of the new type
- * object; doing it here is required for portability, too. */
- if (PyType_Ready(&Xxo_Type) < 0)
- goto fail;
-
- /* Create the module and add the functions */
- m = PyModule_Create(&xxmodule);
- if (m == NULL)
- goto fail;
-
- /* Add some symbolic constants to the module */
- if (ErrorObject == NULL) {
- ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
- if (ErrorObject == NULL)
- goto fail;
- }
- Py_INCREF(ErrorObject);
- PyModule_AddObject(m, "error", ErrorObject);
-
- /* Add Str */
- if (PyType_Ready(&Str_Type) < 0)
- goto fail;
- PyModule_AddObject(m, "Str", (PyObject *)&Str_Type);
-
- /* Add Null */
- if (PyType_Ready(&Null_Type) < 0)
- goto fail;
- PyModule_AddObject(m, "Null", (PyObject *)&Null_Type);
- return m;
+ PyObject *m = NULL;
+
+ /* Due to cross platform compiler issues the slots must be filled
+ * here. It's required for portability to Windows without requiring
+ * C++. */
+ Null_Type.tp_base = &PyBaseObject_Type;
+ Null_Type.tp_new = PyType_GenericNew;
+ Str_Type.tp_base = &PyUnicode_Type;
+
+ /* Finalize the type object including setting type of the new type
+ * object; doing it here is required for portability, too. */
+ if (PyType_Ready(&Xxo_Type) < 0)
+ goto fail;
+
+ /* Create the module and add the functions */
+ m = PyModule_Create(&xxmodule);
+ if (m == NULL)
+ goto fail;
+
+ /* Add some symbolic constants to the module */
+ if (ErrorObject == NULL) {
+ ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
+ if (ErrorObject == NULL)
+ goto fail;
+ }
+ Py_INCREF(ErrorObject);
+ PyModule_AddObject(m, "error", ErrorObject);
+
+ /* Add Str */
+ if (PyType_Ready(&Str_Type) < 0)
+ goto fail;
+ PyModule_AddObject(m, "Str", (PyObject *)&Str_Type);
+
+ /* Add Null */
+ if (PyType_Ready(&Null_Type) < 0)
+ goto fail;
+ PyModule_AddObject(m, "Null", (PyObject *)&Null_Type);
+ return m;
fail:
- Py_XDECREF(m);
- return NULL;
+ Py_XDECREF(m);
+ return NULL;
}
diff --git a/Modules/xxsubtype.c b/Modules/xxsubtype.c
index 91ba0f12..6944e37 100644
--- a/Modules/xxsubtype.c
+++ b/Modules/xxsubtype.c
@@ -19,291 +19,291 @@ PyDoc_STRVAR(xxsubtype__doc__,
/* spamlist -- a list subtype */
typedef struct {
- PyListObject list;
- int state;
+ PyListObject list;
+ int state;
} spamlistobject;
static PyObject *
spamlist_getstate(spamlistobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":getstate"))
- return NULL;
- return PyLong_FromLong(self->state);
+ if (!PyArg_ParseTuple(args, ":getstate"))
+ return NULL;
+ return PyLong_FromLong(self->state);
}
static PyObject *
spamlist_setstate(spamlistobject *self, PyObject *args)
{
- int state;
+ int state;
- if (!PyArg_ParseTuple(args, "i:setstate", &state))
- return NULL;
- self->state = state;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:setstate", &state))
+ return NULL;
+ self->state = state;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
spamlist_specialmeth(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *result = PyTuple_New(3);
-
- if (result != NULL) {
- if (self == NULL)
- self = Py_None;
- if (kw == NULL)
- kw = Py_None;
- Py_INCREF(self);
- PyTuple_SET_ITEM(result, 0, self);
- Py_INCREF(args);
- PyTuple_SET_ITEM(result, 1, args);
- Py_INCREF(kw);
- PyTuple_SET_ITEM(result, 2, kw);
- }
- return result;
+ PyObject *result = PyTuple_New(3);
+
+ if (result != NULL) {
+ if (self == NULL)
+ self = Py_None;
+ if (kw == NULL)
+ kw = Py_None;
+ Py_INCREF(self);
+ PyTuple_SET_ITEM(result, 0, self);
+ Py_INCREF(args);
+ PyTuple_SET_ITEM(result, 1, args);
+ Py_INCREF(kw);
+ PyTuple_SET_ITEM(result, 2, kw);
+ }
+ return result;
}
static PyMethodDef spamlist_methods[] = {
- {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS,
- PyDoc_STR("getstate() -> state")},
- {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS,
- PyDoc_STR("setstate(state)")},
- /* These entries differ only in the flags; they are used by the tests
- in test.test_descr. */
- {"classmeth", (PyCFunction)spamlist_specialmeth,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("classmeth(*args, **kw)")},
- {"staticmeth", (PyCFunction)spamlist_specialmeth,
- METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- PyDoc_STR("staticmeth(*args, **kw)")},
- {NULL, NULL},
+ {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS,
+ PyDoc_STR("getstate() -> state")},
+ {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS,
+ PyDoc_STR("setstate(state)")},
+ /* These entries differ only in the flags; they are used by the tests
+ in test.test_descr. */
+ {"classmeth", (PyCFunction)spamlist_specialmeth,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("classmeth(*args, **kw)")},
+ {"staticmeth", (PyCFunction)spamlist_specialmeth,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ PyDoc_STR("staticmeth(*args, **kw)")},
+ {NULL, NULL},
};
static int
spamlist_init(spamlistobject *self, PyObject *args, PyObject *kwds)
{
- if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
- return -1;
- self->state = 0;
- return 0;
+ if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
+ return -1;
+ self->state = 0;
+ return 0;
}
static PyObject *
spamlist_state_get(spamlistobject *self)
{
- return PyLong_FromLong(self->state);
+ return PyLong_FromLong(self->state);
}
static PyGetSetDef spamlist_getsets[] = {
- {"state", (getter)spamlist_state_get, NULL,
- PyDoc_STR("an int variable for demonstration purposes")},
- {0}
+ {"state", (getter)spamlist_state_get, NULL,
+ PyDoc_STR("an int variable for demonstration purposes")},
+ {0}
};
static PyTypeObject spamlist_type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "xxsubtype.spamlist",
- sizeof(spamlistobject),
- 0,
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- spamlist_methods, /* tp_methods */
- 0, /* tp_members */
- spamlist_getsets, /* tp_getset */
- DEFERRED_ADDRESS(&PyList_Type), /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)spamlist_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "xxsubtype.spamlist",
+ sizeof(spamlistobject),
+ 0,
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ spamlist_methods, /* tp_methods */
+ 0, /* tp_members */
+ spamlist_getsets, /* tp_getset */
+ DEFERRED_ADDRESS(&PyList_Type), /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)spamlist_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
};
/* spamdict -- a dict subtype */
typedef struct {
- PyDictObject dict;
- int state;
+ PyDictObject dict;
+ int state;
} spamdictobject;
static PyObject *
spamdict_getstate(spamdictobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":getstate"))
- return NULL;
- return PyLong_FromLong(self->state);
+ if (!PyArg_ParseTuple(args, ":getstate"))
+ return NULL;
+ return PyLong_FromLong(self->state);
}
static PyObject *
spamdict_setstate(spamdictobject *self, PyObject *args)
{
- int state;
+ int state;
- if (!PyArg_ParseTuple(args, "i:setstate", &state))
- return NULL;
- self->state = state;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:setstate", &state))
+ return NULL;
+ self->state = state;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef spamdict_methods[] = {
- {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS,
- PyDoc_STR("getstate() -> state")},
- {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS,
- PyDoc_STR("setstate(state)")},
- {NULL, NULL},
+ {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS,
+ PyDoc_STR("getstate() -> state")},
+ {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS,
+ PyDoc_STR("setstate(state)")},
+ {NULL, NULL},
};
static int
spamdict_init(spamdictobject *self, PyObject *args, PyObject *kwds)
{
- if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
- return -1;
- self->state = 0;
- return 0;
+ if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
+ return -1;
+ self->state = 0;
+ return 0;
}
static PyMemberDef spamdict_members[] = {
- {"state", T_INT, offsetof(spamdictobject, state), READONLY,
- PyDoc_STR("an int variable for demonstration purposes")},
- {0}
+ {"state", T_INT, offsetof(spamdictobject, state), READONLY,
+ PyDoc_STR("an int variable for demonstration purposes")},
+ {0}
};
static PyTypeObject spamdict_type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "xxsubtype.spamdict",
- sizeof(spamdictobject),
- 0,
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- spamdict_methods, /* tp_methods */
- spamdict_members, /* tp_members */
- 0, /* tp_getset */
- DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)spamdict_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "xxsubtype.spamdict",
+ sizeof(spamdictobject),
+ 0,
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ spamdict_methods, /* tp_methods */
+ spamdict_members, /* tp_members */
+ 0, /* tp_getset */
+ DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)spamdict_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
};
static PyObject *
spam_bench(PyObject *self, PyObject *args)
{
- PyObject *obj, *name, *res;
- int n = 1000;
- time_t t0, t1;
-
- if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n))
- return NULL;
- t0 = clock();
- while (--n >= 0) {
- res = PyObject_GetAttr(obj, name);
- if (res == NULL)
- return NULL;
- Py_DECREF(res);
- }
- t1 = clock();
- return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC);
+ PyObject *obj, *name, *res;
+ int n = 1000;
+ time_t t0, t1;
+
+ if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n))
+ return NULL;
+ t0 = clock();
+ while (--n >= 0) {
+ res = PyObject_GetAttr(obj, name);
+ if (res == NULL)
+ return NULL;
+ Py_DECREF(res);
+ }
+ t1 = clock();
+ return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC);
}
static PyMethodDef xxsubtype_functions[] = {
- {"bench", spam_bench, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"bench", spam_bench, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static struct PyModuleDef xxsubtypemodule = {
- PyModuleDef_HEAD_INIT,
- "xxsubtype",
- xxsubtype__doc__,
- -1,
- xxsubtype_functions,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "xxsubtype",
+ xxsubtype__doc__,
+ -1,
+ xxsubtype_functions,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_xxsubtype(void)
{
- PyObject *m;
-
- /* Fill in deferred data addresses. This must be done before
- PyType_Ready() is called. Note that PyType_Ready() automatically
- initializes the ob.ob_type field to &PyType_Type if it's NULL,
- so it's not necessary to fill in ob_type first. */
- spamdict_type.tp_base = &PyDict_Type;
- if (PyType_Ready(&spamdict_type) < 0)
- return NULL;
-
- spamlist_type.tp_base = &PyList_Type;
- if (PyType_Ready(&spamlist_type) < 0)
- return NULL;
-
- m = PyModule_Create(&xxsubtypemodule);
- if (m == NULL)
- return NULL;
-
- if (PyType_Ready(&spamlist_type) < 0)
- return NULL;
- if (PyType_Ready(&spamdict_type) < 0)
- return NULL;
-
- Py_INCREF(&spamlist_type);
- if (PyModule_AddObject(m, "spamlist",
- (PyObject *) &spamlist_type) < 0)
- return NULL;
-
- Py_INCREF(&spamdict_type);
- if (PyModule_AddObject(m, "spamdict",
- (PyObject *) &spamdict_type) < 0)
- return NULL;
- return m;
+ PyObject *m;
+
+ /* Fill in deferred data addresses. This must be done before
+ PyType_Ready() is called. Note that PyType_Ready() automatically
+ initializes the ob.ob_type field to &PyType_Type if it's NULL,
+ so it's not necessary to fill in ob_type first. */
+ spamdict_type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&spamdict_type) < 0)
+ return NULL;
+
+ spamlist_type.tp_base = &PyList_Type;
+ if (PyType_Ready(&spamlist_type) < 0)
+ return NULL;
+
+ m = PyModule_Create(&xxsubtypemodule);
+ if (m == NULL)
+ return NULL;
+
+ if (PyType_Ready(&spamlist_type) < 0)
+ return NULL;
+ if (PyType_Ready(&spamdict_type) < 0)
+ return NULL;
+
+ Py_INCREF(&spamlist_type);
+ if (PyModule_AddObject(m, "spamlist",
+ (PyObject *) &spamlist_type) < 0)
+ return NULL;
+
+ Py_INCREF(&spamdict_type);
+ if (PyModule_AddObject(m, "spamdict",
+ (PyObject *) &spamdict_type) < 0)
+ return NULL;
+ return m;
}
diff --git a/Modules/zipimport.c b/Modules/zipimport.c
index fed3e99..734445c 100644
--- a/Modules/zipimport.c
+++ b/Modules/zipimport.c
@@ -10,8 +10,8 @@
#define IS_PACKAGE 0x2
struct st_zip_searchorder {
- char suffix[14];
- int type;
+ char suffix[14];
+ int type;
};
/* zip_searchorder defines how we search for a module in the Zip
@@ -20,13 +20,13 @@ struct st_zip_searchorder {
are swapped by initzipimport() if we run in optimized mode. Also,
'/' is replaced by SEP there. */
static struct st_zip_searchorder zip_searchorder[] = {
- {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},
- {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE},
- {"/__init__.py", IS_PACKAGE | IS_SOURCE},
- {".pyc", IS_BYTECODE},
- {".pyo", IS_BYTECODE},
- {".py", IS_SOURCE},
- {"", 0}
+ {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},
+ {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE},
+ {"/__init__.py", IS_PACKAGE | IS_SOURCE},
+ {".pyc", IS_BYTECODE},
+ {".pyo", IS_BYTECODE},
+ {".py", IS_SOURCE},
+ {"", 0}
};
/* zipimporter object definition and support */
@@ -34,10 +34,10 @@ static struct st_zip_searchorder zip_searchorder[] = {
typedef struct _zipimporter ZipImporter;
struct _zipimporter {
- PyObject_HEAD
- PyObject *archive; /* pathname of the Zip archive */
- PyObject *prefix; /* file prefix: "a/sub/directory/" */
- PyObject *files; /* dict with file info {path: toc_entry} */
+ PyObject_HEAD
+ PyObject *archive; /* pathname of the Zip archive */
+ PyObject *prefix; /* file prefix: "a/sub/directory/" */
+ PyObject *files; /* dict with file info {path: toc_entry} */
};
static PyObject *ZipImportError;
@@ -47,7 +47,7 @@ static PyObject *zip_directory_cache = NULL;
static PyObject *read_directory(char *archive);
static PyObject *get_data(char *archive, PyObject *toc_entry);
static PyObject *get_module_code(ZipImporter *self, char *fullname,
- int *p_ispackage, char **p_modpath);
+ int *p_ispackage, char **p_modpath);
#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
@@ -60,147 +60,147 @@ static PyObject *get_module_code(ZipImporter *self, char *fullname,
static int
zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)
{
- char *path, *p, *prefix, buf[MAXPATHLEN+2];
- size_t len;
-
- if (!_PyArg_NoKeywords("zipimporter()", kwds))
- return -1;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter", &path))
- return -1;
-
- len = strlen(path);
- if (len == 0) {
- PyErr_SetString(ZipImportError, "archive path is empty");
- return -1;
- }
- if (len >= MAXPATHLEN) {
- PyErr_SetString(ZipImportError,
- "archive path too long");
- return -1;
- }
- strcpy(buf, path);
+ char *path, *p, *prefix, buf[MAXPATHLEN+2];
+ size_t len;
+
+ if (!_PyArg_NoKeywords("zipimporter()", kwds))
+ return -1;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter", &path))
+ return -1;
+
+ len = strlen(path);
+ if (len == 0) {
+ PyErr_SetString(ZipImportError, "archive path is empty");
+ return -1;
+ }
+ if (len >= MAXPATHLEN) {
+ PyErr_SetString(ZipImportError,
+ "archive path too long");
+ return -1;
+ }
+ strcpy(buf, path);
#ifdef ALTSEP
- for (p = buf; *p; p++) {
- if (*p == ALTSEP)
- *p = SEP;
- }
+ for (p = buf; *p; p++) {
+ if (*p == ALTSEP)
+ *p = SEP;
+ }
#endif
- path = NULL;
- prefix = NULL;
- for (;;) {
- struct stat statbuf;
- int rv;
-
- rv = stat(buf, &statbuf);
- if (rv == 0) {
- /* it exists */
- if (S_ISREG(statbuf.st_mode))
- /* it's a file */
- path = buf;
- break;
- }
- /* back up one path element */
- p = strrchr(buf, SEP);
- if (prefix != NULL)
- *prefix = SEP;
- if (p == NULL)
- break;
- *p = '\0';
- prefix = p;
- }
- if (path != NULL) {
- PyObject *files;
- files = PyDict_GetItemString(zip_directory_cache, path);
- if (files == NULL) {
- files = read_directory(buf);
- if (files == NULL)
- return -1;
- if (PyDict_SetItemString(zip_directory_cache, path,
- files) != 0)
- return -1;
- }
- else
- Py_INCREF(files);
- self->files = files;
- }
- else {
- PyErr_SetString(ZipImportError, "not a Zip file");
- return -1;
- }
-
- if (prefix == NULL)
- prefix = "";
- else {
- prefix++;
- len = strlen(prefix);
- if (prefix[len-1] != SEP) {
- /* add trailing SEP */
- prefix[len] = SEP;
- prefix[len + 1] = '\0';
- }
- }
-
- self->archive = PyUnicode_FromString(buf);
- if (self->archive == NULL)
- return -1;
-
- self->prefix = PyUnicode_FromString(prefix);
- if (self->prefix == NULL)
- return -1;
-
- return 0;
+ path = NULL;
+ prefix = NULL;
+ for (;;) {
+ struct stat statbuf;
+ int rv;
+
+ rv = stat(buf, &statbuf);
+ if (rv == 0) {
+ /* it exists */
+ if (S_ISREG(statbuf.st_mode))
+ /* it's a file */
+ path = buf;
+ break;
+ }
+ /* back up one path element */
+ p = strrchr(buf, SEP);
+ if (prefix != NULL)
+ *prefix = SEP;
+ if (p == NULL)
+ break;
+ *p = '\0';
+ prefix = p;
+ }
+ if (path != NULL) {
+ PyObject *files;
+ files = PyDict_GetItemString(zip_directory_cache, path);
+ if (files == NULL) {
+ files = read_directory(buf);
+ if (files == NULL)
+ return -1;
+ if (PyDict_SetItemString(zip_directory_cache, path,
+ files) != 0)
+ return -1;
+ }
+ else
+ Py_INCREF(files);
+ self->files = files;
+ }
+ else {
+ PyErr_SetString(ZipImportError, "not a Zip file");
+ return -1;
+ }
+
+ if (prefix == NULL)
+ prefix = "";
+ else {
+ prefix++;
+ len = strlen(prefix);
+ if (prefix[len-1] != SEP) {
+ /* add trailing SEP */
+ prefix[len] = SEP;
+ prefix[len + 1] = '\0';
+ }
+ }
+
+ self->archive = PyUnicode_FromString(buf);
+ if (self->archive == NULL)
+ return -1;
+
+ self->prefix = PyUnicode_FromString(prefix);
+ if (self->prefix == NULL)
+ return -1;
+
+ return 0;
}
/* GC support. */
static int
zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)
{
- ZipImporter *self = (ZipImporter *)obj;
- Py_VISIT(self->files);
- return 0;
+ ZipImporter *self = (ZipImporter *)obj;
+ Py_VISIT(self->files);
+ return 0;
}
static void
zipimporter_dealloc(ZipImporter *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->archive);
- Py_XDECREF(self->prefix);
- Py_XDECREF(self->files);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->archive);
+ Py_XDECREF(self->prefix);
+ Py_XDECREF(self->files);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
zipimporter_repr(ZipImporter *self)
{
- char *archive = "???";
- char *prefix = "";
-
- if (self->archive != NULL && PyUnicode_Check(self->archive))
- archive = _PyUnicode_AsString(self->archive);
- if (self->prefix != NULL && PyUnicode_Check(self->prefix))
- prefix = _PyUnicode_AsString(self->prefix);
- if (prefix != NULL && *prefix)
- return PyUnicode_FromFormat("<zipimporter object \"%.300s%c%.150s\">",
- archive, SEP, prefix);
- else
- return PyUnicode_FromFormat("<zipimporter object \"%.300s\">",
- archive);
+ char *archive = "???";
+ char *prefix = "";
+
+ if (self->archive != NULL && PyUnicode_Check(self->archive))
+ archive = _PyUnicode_AsString(self->archive);
+ if (self->prefix != NULL && PyUnicode_Check(self->prefix))
+ prefix = _PyUnicode_AsString(self->prefix);
+ if (prefix != NULL && *prefix)
+ return PyUnicode_FromFormat("<zipimporter object \"%.300s%c%.150s\">",
+ archive, SEP, prefix);
+ else
+ return PyUnicode_FromFormat("<zipimporter object \"%.300s\">",
+ archive);
}
/* return fullname.split(".")[-1] */
static char *
get_subname(char *fullname)
{
- char *subname = strrchr(fullname, '.');
- if (subname == NULL)
- subname = fullname;
- else
- subname++;
- return subname;
+ char *subname = strrchr(fullname, '.');
+ if (subname == NULL)
+ subname = fullname;
+ else
+ subname++;
+ return subname;
}
/* Given a (sub)modulename, write the potential file path in the
@@ -209,59 +209,59 @@ get_subname(char *fullname)
static int
make_filename(char *prefix, char *name, char *path)
{
- size_t len;
- char *p;
-
- len = strlen(prefix);
-
- /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */
- if (len + strlen(name) + 13 >= MAXPATHLEN) {
- PyErr_SetString(ZipImportError, "path too long");
- return -1;
- }
-
- strcpy(path, prefix);
- strcpy(path + len, name);
- for (p = path + len; *p; p++) {
- if (*p == '.')
- *p = SEP;
- }
- len += strlen(name);
- assert(len < INT_MAX);
- return (int)len;
+ size_t len;
+ char *p;
+
+ len = strlen(prefix);
+
+ /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */
+ if (len + strlen(name) + 13 >= MAXPATHLEN) {
+ PyErr_SetString(ZipImportError, "path too long");
+ return -1;
+ }
+
+ strcpy(path, prefix);
+ strcpy(path + len, name);
+ for (p = path + len; *p; p++) {
+ if (*p == '.')
+ *p = SEP;
+ }
+ len += strlen(name);
+ assert(len < INT_MAX);
+ return (int)len;
}
enum zi_module_info {
- MI_ERROR,
- MI_NOT_FOUND,
- MI_MODULE,
- MI_PACKAGE
+ MI_ERROR,
+ MI_NOT_FOUND,
+ MI_MODULE,
+ MI_PACKAGE
};
/* Return some information about a module. */
static enum zi_module_info
get_module_info(ZipImporter *self, char *fullname)
{
- char *subname, path[MAXPATHLEN + 1];
- int len;
- struct st_zip_searchorder *zso;
-
- subname = get_subname(fullname);
-
- len = make_filename(_PyUnicode_AsString(self->prefix), subname, path);
- if (len < 0)
- return MI_ERROR;
-
- for (zso = zip_searchorder; *zso->suffix; zso++) {
- strcpy(path + len, zso->suffix);
- if (PyDict_GetItemString(self->files, path) != NULL) {
- if (zso->type & IS_PACKAGE)
- return MI_PACKAGE;
- else
- return MI_MODULE;
- }
- }
- return MI_NOT_FOUND;
+ char *subname, path[MAXPATHLEN + 1];
+ int len;
+ struct st_zip_searchorder *zso;
+
+ subname = get_subname(fullname);
+
+ len = make_filename(_PyUnicode_AsString(self->prefix), subname, path);
+ if (len < 0)
+ return MI_ERROR;
+
+ for (zso = zip_searchorder; *zso->suffix; zso++) {
+ strcpy(path + len, zso->suffix);
+ if (PyDict_GetItemString(self->files, path) != NULL) {
+ if (zso->type & IS_PACKAGE)
+ return MI_PACKAGE;
+ else
+ return MI_MODULE;
+ }
+ }
+ return MI_NOT_FOUND;
}
/* Check whether we can satisfy the import of the module named by
@@ -269,86 +269,86 @@ get_module_info(ZipImporter *self, char *fullname)
static PyObject *
zipimporter_find_module(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- PyObject *path = NULL;
- char *fullname;
- enum zi_module_info mi;
-
- if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module",
- &fullname, &path))
- return NULL;
-
- mi = get_module_info(self, fullname);
- if (mi == MI_ERROR)
- return NULL;
- if (mi == MI_NOT_FOUND) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- Py_INCREF(self);
- return (PyObject *)self;
+ ZipImporter *self = (ZipImporter *)obj;
+ PyObject *path = NULL;
+ char *fullname;
+ enum zi_module_info mi;
+
+ if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module",
+ &fullname, &path))
+ return NULL;
+
+ mi = get_module_info(self, fullname);
+ if (mi == MI_ERROR)
+ return NULL;
+ if (mi == MI_NOT_FOUND) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ Py_INCREF(self);
+ return (PyObject *)self;
}
/* Load and return the module named by 'fullname'. */
static PyObject *
zipimporter_load_module(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- PyObject *code, *mod, *dict;
- char *fullname, *modpath;
- int ispackage;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter.load_module",
- &fullname))
- return NULL;
-
- code = get_module_code(self, fullname, &ispackage, &modpath);
- if (code == NULL)
- return NULL;
-
- mod = PyImport_AddModule(fullname);
- if (mod == NULL) {
- Py_DECREF(code);
- return NULL;
- }
- dict = PyModule_GetDict(mod);
-
- /* mod.__loader__ = self */
- if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
- goto error;
-
- if (ispackage) {
- /* add __path__ to the module *before* the code gets
- executed */
- PyObject *pkgpath, *fullpath;
- char *subname = get_subname(fullname);
- int err;
-
- fullpath = PyUnicode_FromFormat("%U%c%U%s",
- self->archive, SEP,
- self->prefix, subname);
- if (fullpath == NULL)
- goto error;
-
- pkgpath = Py_BuildValue("[O]", fullpath);
- Py_DECREF(fullpath);
- if (pkgpath == NULL)
- goto error;
- err = PyDict_SetItemString(dict, "__path__", pkgpath);
- Py_DECREF(pkgpath);
- if (err != 0)
- goto error;
- }
- mod = PyImport_ExecCodeModuleEx(fullname, code, modpath);
- Py_DECREF(code);
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # loaded from Zip %s\n",
- fullname, modpath);
- return mod;
+ ZipImporter *self = (ZipImporter *)obj;
+ PyObject *code, *mod, *dict;
+ char *fullname, *modpath;
+ int ispackage;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter.load_module",
+ &fullname))
+ return NULL;
+
+ code = get_module_code(self, fullname, &ispackage, &modpath);
+ if (code == NULL)
+ return NULL;
+
+ mod = PyImport_AddModule(fullname);
+ if (mod == NULL) {
+ Py_DECREF(code);
+ return NULL;
+ }
+ dict = PyModule_GetDict(mod);
+
+ /* mod.__loader__ = self */
+ if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
+ goto error;
+
+ if (ispackage) {
+ /* add __path__ to the module *before* the code gets
+ executed */
+ PyObject *pkgpath, *fullpath;
+ char *subname = get_subname(fullname);
+ int err;
+
+ fullpath = PyUnicode_FromFormat("%U%c%U%s",
+ self->archive, SEP,
+ self->prefix, subname);
+ if (fullpath == NULL)
+ goto error;
+
+ pkgpath = Py_BuildValue("[O]", fullpath);
+ Py_DECREF(fullpath);
+ if (pkgpath == NULL)
+ goto error;
+ err = PyDict_SetItemString(dict, "__path__", pkgpath);
+ Py_DECREF(pkgpath);
+ if (err != 0)
+ goto error;
+ }
+ mod = PyImport_ExecCodeModuleEx(fullname, code, modpath);
+ Py_DECREF(code);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # loaded from Zip %s\n",
+ fullname, modpath);
+ return mod;
error:
- Py_DECREF(code);
- Py_DECREF(mod);
- return NULL;
+ Py_DECREF(code);
+ Py_DECREF(mod);
+ return NULL;
}
/* Return a string matching __file__ for the named module */
@@ -362,13 +362,13 @@ zipimporter_get_filename(PyObject *obj, PyObject *args)
if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename",
&fullname))
- return NULL;
+ return NULL;
/* Deciding the filename requires working out where the code
would come from if the module was actually loaded */
code = get_module_code(self, fullname, &ispackage, &modpath);
if (code == NULL)
- return NULL;
+ return NULL;
Py_DECREF(code); /* Only need the path info */
return PyUnicode_FromString(modpath);
@@ -378,123 +378,123 @@ zipimporter_get_filename(PyObject *obj, PyObject *args)
static PyObject *
zipimporter_is_package(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- char *fullname;
- enum zi_module_info mi;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter.is_package",
- &fullname))
- return NULL;
-
- mi = get_module_info(self, fullname);
- if (mi == MI_ERROR)
- return NULL;
- if (mi == MI_NOT_FOUND) {
- PyErr_Format(ZipImportError, "can't find module '%.200s'",
- fullname);
- return NULL;
- }
- return PyBool_FromLong(mi == MI_PACKAGE);
+ ZipImporter *self = (ZipImporter *)obj;
+ char *fullname;
+ enum zi_module_info mi;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter.is_package",
+ &fullname))
+ return NULL;
+
+ mi = get_module_info(self, fullname);
+ if (mi == MI_ERROR)
+ return NULL;
+ if (mi == MI_NOT_FOUND) {
+ PyErr_Format(ZipImportError, "can't find module '%.200s'",
+ fullname);
+ return NULL;
+ }
+ return PyBool_FromLong(mi == MI_PACKAGE);
}
static PyObject *
zipimporter_get_data(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- char *path;
+ ZipImporter *self = (ZipImporter *)obj;
+ char *path;
#ifdef ALTSEP
- char *p, buf[MAXPATHLEN + 1];
+ char *p, buf[MAXPATHLEN + 1];
#endif
- PyObject *toc_entry;
- Py_ssize_t len;
- char *archive_str;
+ PyObject *toc_entry;
+ Py_ssize_t len;
+ char *archive_str;
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path))
+ return NULL;
#ifdef ALTSEP
- if (strlen(path) >= MAXPATHLEN) {
- PyErr_SetString(ZipImportError, "path too long");
- return NULL;
- }
- strcpy(buf, path);
- for (p = buf; *p; p++) {
- if (*p == ALTSEP)
- *p = SEP;
- }
- path = buf;
+ if (strlen(path) >= MAXPATHLEN) {
+ PyErr_SetString(ZipImportError, "path too long");
+ return NULL;
+ }
+ strcpy(buf, path);
+ for (p = buf; *p; p++) {
+ if (*p == ALTSEP)
+ *p = SEP;
+ }
+ path = buf;
#endif
- archive_str = _PyUnicode_AsStringAndSize(self->archive, &len);
- if ((size_t)len < strlen(path) &&
- strncmp(path, archive_str, len) == 0 &&
- path[len] == SEP) {
- path = path + len + 1;
- }
-
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry == NULL) {
- PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
- return NULL;
- }
- return get_data(archive_str, toc_entry);
+ archive_str = _PyUnicode_AsStringAndSize(self->archive, &len);
+ if ((size_t)len < strlen(path) &&
+ strncmp(path, archive_str, len) == 0 &&
+ path[len] == SEP) {
+ path = path + len + 1;
+ }
+
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry == NULL) {
+ PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
+ return NULL;
+ }
+ return get_data(archive_str, toc_entry);
}
static PyObject *
zipimporter_get_code(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- char *fullname;
+ ZipImporter *self = (ZipImporter *)obj;
+ char *fullname;
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname))
+ return NULL;
- return get_module_code(self, fullname, NULL, NULL);
+ return get_module_code(self, fullname, NULL, NULL);
}
static PyObject *
zipimporter_get_source(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- PyObject *toc_entry;
- char *fullname, *subname, path[MAXPATHLEN+1];
- int len;
- enum zi_module_info mi;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname))
- return NULL;
-
- mi = get_module_info(self, fullname);
- if (mi == MI_ERROR)
- return NULL;
- if (mi == MI_NOT_FOUND) {
- PyErr_Format(ZipImportError, "can't find module '%.200s'",
- fullname);
- return NULL;
- }
- subname = get_subname(fullname);
-
- len = make_filename(_PyUnicode_AsString(self->prefix), subname, path);
- if (len < 0)
- return NULL;
-
- if (mi == MI_PACKAGE) {
- path[len] = SEP;
- strcpy(path + len + 1, "__init__.py");
- }
- else
- strcpy(path + len, ".py");
-
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry != NULL) {
- PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry);
- PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes));
- Py_XDECREF(bytes);
- return res;
- }
-
- /* we have the module, but no source */
- Py_INCREF(Py_None);
- return Py_None;
+ ZipImporter *self = (ZipImporter *)obj;
+ PyObject *toc_entry;
+ char *fullname, *subname, path[MAXPATHLEN+1];
+ int len;
+ enum zi_module_info mi;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname))
+ return NULL;
+
+ mi = get_module_info(self, fullname);
+ if (mi == MI_ERROR)
+ return NULL;
+ if (mi == MI_NOT_FOUND) {
+ PyErr_Format(ZipImportError, "can't find module '%.200s'",
+ fullname);
+ return NULL;
+ }
+ subname = get_subname(fullname);
+
+ len = make_filename(_PyUnicode_AsString(self->prefix), subname, path);
+ if (len < 0)
+ return NULL;
+
+ if (mi == MI_PACKAGE) {
+ path[len] = SEP;
+ strcpy(path + len + 1, "__init__.py");
+ }
+ else
+ strcpy(path + len, ".py");
+
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry != NULL) {
+ PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry);
+ PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes));
+ Py_XDECREF(bytes);
+ return res;
+ }
+
+ /* we have the module, but no source */
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(doc_find_module,
@@ -545,28 +545,28 @@ PyDoc_STRVAR(doc_get_filename,
Return the filename for the specified module.");
static PyMethodDef zipimporter_methods[] = {
- {"find_module", zipimporter_find_module, METH_VARARGS,
- doc_find_module},
- {"load_module", zipimporter_load_module, METH_VARARGS,
- doc_load_module},
- {"get_data", zipimporter_get_data, METH_VARARGS,
- doc_get_data},
- {"get_code", zipimporter_get_code, METH_VARARGS,
- doc_get_code},
- {"get_source", zipimporter_get_source, METH_VARARGS,
- doc_get_source},
- {"get_filename", zipimporter_get_filename, METH_VARARGS,
- doc_get_filename},
- {"is_package", zipimporter_is_package, METH_VARARGS,
- doc_is_package},
- {NULL, NULL} /* sentinel */
+ {"find_module", zipimporter_find_module, METH_VARARGS,
+ doc_find_module},
+ {"load_module", zipimporter_load_module, METH_VARARGS,
+ doc_load_module},
+ {"get_data", zipimporter_get_data, METH_VARARGS,
+ doc_get_data},
+ {"get_code", zipimporter_get_code, METH_VARARGS,
+ doc_get_code},
+ {"get_source", zipimporter_get_source, METH_VARARGS,
+ doc_get_source},
+ {"get_filename", zipimporter_get_filename, METH_VARARGS,
+ doc_get_filename},
+ {"is_package", zipimporter_is_package, METH_VARARGS,
+ doc_is_package},
+ {NULL, NULL} /* sentinel */
};
static PyMemberDef zipimporter_members[] = {
- {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
- {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
- {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
- {NULL}
+ {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
+ {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
+ {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
+ {NULL}
};
PyDoc_STRVAR(zipimporter_doc,
@@ -586,46 +586,46 @@ zipfile targeted.");
#define DEFERRED_ADDRESS(ADDR) 0
static PyTypeObject ZipImporter_Type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "zipimport.zipimporter",
- sizeof(ZipImporter),
- 0, /* tp_itemsize */
- (destructor)zipimporter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)zipimporter_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_HAVE_GC, /* tp_flags */
- zipimporter_doc, /* tp_doc */
- zipimporter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- zipimporter_methods, /* tp_methods */
- zipimporter_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)zipimporter_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "zipimport.zipimporter",
+ sizeof(ZipImporter),
+ 0, /* tp_itemsize */
+ (destructor)zipimporter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)zipimporter_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ zipimporter_doc, /* tp_doc */
+ zipimporter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ zipimporter_methods, /* tp_methods */
+ zipimporter_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)zipimporter_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -636,16 +636,16 @@ static PyTypeObject ZipImporter_Type = {
marshal.c:r_long() */
static long
get_long(unsigned char *buf) {
- long x;
- x = buf[0];
- x |= (long)buf[1] << 8;
- x |= (long)buf[2] << 16;
- x |= (long)buf[3] << 24;
+ long x;
+ x = buf[0];
+ x |= (long)buf[1] << 8;
+ x |= (long)buf[2] << 16;
+ x |= (long)buf[3] << 24;
#if SIZEOF_LONG > 4
- /* Sign extension for 64-bit machines */
- x |= -(x & 0x80000000L);
+ /* Sign extension for 64-bit machines */
+ x |= -(x & 0x80000000L);
#endif
- return x;
+ return x;
}
/*
@@ -657,13 +657,13 @@ get_long(unsigned char *buf) {
A toc_entry is a tuple:
(__file__, # value to use for __file__, available for all files
- compress, # compression kind; 0 for uncompressed
- data_size, # size of compressed data on disk
- file_size, # size of decompressed data
- file_offset, # offset of file header from start of archive
- time, # mod time of file (in dos format)
- date, # mod data of file (in dos format)
- crc, # crc checksum of the data
+ compress, # compression kind; 0 for uncompressed
+ data_size, # size of compressed data on disk
+ file_size, # size of decompressed data
+ file_offset, # offset of file header from start of archive
+ time, # mod time of file (in dos format)
+ date, # mod data of file (in dos format)
+ crc, # crc checksum of the data
)
Directories can be recognized by the trailing SEP in the name,
@@ -672,115 +672,115 @@ get_long(unsigned char *buf) {
static PyObject *
read_directory(char *archive)
{
- PyObject *files = NULL;
- FILE *fp;
- long compress, crc, data_size, file_size, file_offset, date, time;
- long header_offset, name_size, header_size, header_position;
- long i, l, count;
- size_t length;
- char path[MAXPATHLEN + 5];
- char name[MAXPATHLEN + 5];
- char *p, endof_central_dir[22];
- long arc_offset; /* offset from beginning of file to start of zip-archive */
-
- if (strlen(archive) > MAXPATHLEN) {
- PyErr_SetString(PyExc_OverflowError,
- "Zip path name is too long");
- return NULL;
- }
- strcpy(path, archive);
-
- fp = fopen(archive, "rb");
- if (fp == NULL) {
- PyErr_Format(ZipImportError, "can't open Zip file: "
- "'%.200s'", archive);
- return NULL;
- }
- fseek(fp, -22, SEEK_END);
- header_position = ftell(fp);
- if (fread(endof_central_dir, 1, 22, fp) != 22) {
- fclose(fp);
- PyErr_Format(ZipImportError, "can't read Zip file: "
- "'%.200s'", archive);
- return NULL;
- }
- if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
- /* Bad: End of Central Dir signature */
- fclose(fp);
- PyErr_Format(ZipImportError, "not a Zip file: "
- "'%.200s'", archive);
- return NULL;
- }
-
- header_size = get_long((unsigned char *)endof_central_dir + 12);
- header_offset = get_long((unsigned char *)endof_central_dir + 16);
- arc_offset = header_position - header_offset - header_size;
- header_offset += arc_offset;
-
- files = PyDict_New();
- if (files == NULL)
- goto error;
-
- length = (long)strlen(path);
- path[length] = SEP;
-
- /* Start of Central Directory */
- count = 0;
- for (;;) {
- PyObject *t;
- int err;
-
- fseek(fp, header_offset, 0); /* Start of file header */
- l = PyMarshal_ReadLongFromFile(fp);
- if (l != 0x02014B50)
- break; /* Bad: Central Dir File Header */
- fseek(fp, header_offset + 10, 0);
- compress = PyMarshal_ReadShortFromFile(fp);
- time = PyMarshal_ReadShortFromFile(fp);
- date = PyMarshal_ReadShortFromFile(fp);
- crc = PyMarshal_ReadLongFromFile(fp);
- data_size = PyMarshal_ReadLongFromFile(fp);
- file_size = PyMarshal_ReadLongFromFile(fp);
- name_size = PyMarshal_ReadShortFromFile(fp);
- header_size = 46 + name_size +
- PyMarshal_ReadShortFromFile(fp) +
- PyMarshal_ReadShortFromFile(fp);
- fseek(fp, header_offset + 42, 0);
- file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
- if (name_size > MAXPATHLEN)
- name_size = MAXPATHLEN;
-
- p = name;
- for (i = 0; i < name_size; i++) {
- *p = (char)getc(fp);
- if (*p == '/')
- *p = SEP;
- p++;
- }
- *p = 0; /* Add terminating null byte */
- header_offset += header_size;
-
- strncpy(path + length + 1, name, MAXPATHLEN - length - 1);
-
- t = Py_BuildValue("siiiiiii", path, compress, data_size,
- file_size, file_offset, time, date, crc);
- if (t == NULL)
- goto error;
- err = PyDict_SetItemString(files, name, t);
- Py_DECREF(t);
- if (err != 0)
- goto error;
- count++;
- }
- fclose(fp);
- if (Py_VerboseFlag)
- PySys_WriteStderr("# zipimport: found %ld names in %s\n",
- count, archive);
- return files;
+ PyObject *files = NULL;
+ FILE *fp;
+ long compress, crc, data_size, file_size, file_offset, date, time;
+ long header_offset, name_size, header_size, header_position;
+ long i, l, count;
+ size_t length;
+ char path[MAXPATHLEN + 5];
+ char name[MAXPATHLEN + 5];
+ char *p, endof_central_dir[22];
+ long arc_offset; /* offset from beginning of file to start of zip-archive */
+
+ if (strlen(archive) > MAXPATHLEN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Zip path name is too long");
+ return NULL;
+ }
+ strcpy(path, archive);
+
+ fp = fopen(archive, "rb");
+ if (fp == NULL) {
+ PyErr_Format(ZipImportError, "can't open Zip file: "
+ "'%.200s'", archive);
+ return NULL;
+ }
+ fseek(fp, -22, SEEK_END);
+ header_position = ftell(fp);
+ if (fread(endof_central_dir, 1, 22, fp) != 22) {
+ fclose(fp);
+ PyErr_Format(ZipImportError, "can't read Zip file: "
+ "'%.200s'", archive);
+ return NULL;
+ }
+ if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
+ /* Bad: End of Central Dir signature */
+ fclose(fp);
+ PyErr_Format(ZipImportError, "not a Zip file: "
+ "'%.200s'", archive);
+ return NULL;
+ }
+
+ header_size = get_long((unsigned char *)endof_central_dir + 12);
+ header_offset = get_long((unsigned char *)endof_central_dir + 16);
+ arc_offset = header_position - header_offset - header_size;
+ header_offset += arc_offset;
+
+ files = PyDict_New();
+ if (files == NULL)
+ goto error;
+
+ length = (long)strlen(path);
+ path[length] = SEP;
+
+ /* Start of Central Directory */
+ count = 0;
+ for (;;) {
+ PyObject *t;
+ int err;
+
+ fseek(fp, header_offset, 0); /* Start of file header */
+ l = PyMarshal_ReadLongFromFile(fp);
+ if (l != 0x02014B50)
+ break; /* Bad: Central Dir File Header */
+ fseek(fp, header_offset + 10, 0);
+ compress = PyMarshal_ReadShortFromFile(fp);
+ time = PyMarshal_ReadShortFromFile(fp);
+ date = PyMarshal_ReadShortFromFile(fp);
+ crc = PyMarshal_ReadLongFromFile(fp);
+ data_size = PyMarshal_ReadLongFromFile(fp);
+ file_size = PyMarshal_ReadLongFromFile(fp);
+ name_size = PyMarshal_ReadShortFromFile(fp);
+ header_size = 46 + name_size +
+ PyMarshal_ReadShortFromFile(fp) +
+ PyMarshal_ReadShortFromFile(fp);
+ fseek(fp, header_offset + 42, 0);
+ file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
+ if (name_size > MAXPATHLEN)
+ name_size = MAXPATHLEN;
+
+ p = name;
+ for (i = 0; i < name_size; i++) {
+ *p = (char)getc(fp);
+ if (*p == '/')
+ *p = SEP;
+ p++;
+ }
+ *p = 0; /* Add terminating null byte */
+ header_offset += header_size;
+
+ strncpy(path + length + 1, name, MAXPATHLEN - length - 1);
+
+ t = Py_BuildValue("siiiiiii", path, compress, data_size,
+ file_size, file_offset, time, date, crc);
+ if (t == NULL)
+ goto error;
+ err = PyDict_SetItemString(files, name, t);
+ Py_DECREF(t);
+ if (err != 0)
+ goto error;
+ count++;
+ }
+ fclose(fp);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# zipimport: found %ld names in %s\n",
+ count, archive);
+ return files;
error:
- fclose(fp);
- Py_XDECREF(files);
- return NULL;
+ fclose(fp);
+ Py_XDECREF(files);
+ return NULL;
}
/* Return the zlib.decompress function object, or NULL if zlib couldn't
@@ -790,31 +790,31 @@ error:
static PyObject *
get_decompress_func(void)
{
- static PyObject *decompress = NULL;
-
- if (decompress == NULL) {
- PyObject *zlib;
- static int importing_zlib = 0;
-
- if (importing_zlib != 0)
- /* Someone has a zlib.py[co] in their Zip file;
- let's avoid a stack overflow. */
- return NULL;
- importing_zlib = 1;
- zlib = PyImport_ImportModuleNoBlock("zlib");
- importing_zlib = 0;
- if (zlib != NULL) {
- decompress = PyObject_GetAttrString(zlib,
- "decompress");
- Py_DECREF(zlib);
- }
- else
- PyErr_Clear();
- if (Py_VerboseFlag)
- PySys_WriteStderr("# zipimport: zlib %s\n",
- zlib != NULL ? "available": "UNAVAILABLE");
- }
- return decompress;
+ static PyObject *decompress = NULL;
+
+ if (decompress == NULL) {
+ PyObject *zlib;
+ static int importing_zlib = 0;
+
+ if (importing_zlib != 0)
+ /* Someone has a zlib.py[co] in their Zip file;
+ let's avoid a stack overflow. */
+ return NULL;
+ importing_zlib = 1;
+ zlib = PyImport_ImportModuleNoBlock("zlib");
+ importing_zlib = 0;
+ if (zlib != NULL) {
+ decompress = PyObject_GetAttrString(zlib,
+ "decompress");
+ Py_DECREF(zlib);
+ }
+ else
+ PyErr_Clear();
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# zipimport: zlib %s\n",
+ zlib != NULL ? "available": "UNAVAILABLE");
+ }
+ return decompress;
}
/* Given a path to a Zip file and a toc_entry, return the (uncompressed)
@@ -822,91 +822,91 @@ get_decompress_func(void)
static PyObject *
get_data(char *archive, PyObject *toc_entry)
{
- PyObject *raw_data, *data = NULL, *decompress;
- char *buf;
- FILE *fp;
- int err;
- Py_ssize_t bytes_read = 0;
- long l;
- char *datapath;
- long compress, data_size, file_size, file_offset, bytes_size;
- long time, date, crc;
-
- if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,
- &data_size, &file_size, &file_offset, &time,
- &date, &crc)) {
- return NULL;
- }
-
- fp = fopen(archive, "rb");
- if (!fp) {
- PyErr_Format(PyExc_IOError,
- "zipimport: can not open file %s", archive);
- return NULL;
- }
-
- /* Check to make sure the local file header is correct */
- fseek(fp, file_offset, 0);
- l = PyMarshal_ReadLongFromFile(fp);
- if (l != 0x04034B50) {
- /* Bad: Local File Header */
- PyErr_Format(ZipImportError,
- "bad local file header in %s",
- archive);
- fclose(fp);
- return NULL;
- }
- fseek(fp, file_offset + 26, 0);
- l = 30 + PyMarshal_ReadShortFromFile(fp) +
- PyMarshal_ReadShortFromFile(fp); /* local header size */
- file_offset += l; /* Start of file data */
-
- bytes_size = compress == 0 ? data_size : data_size + 1;
- if (bytes_size == 0)
- bytes_size++;
- raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size);
-
- if (raw_data == NULL) {
- fclose(fp);
- return NULL;
- }
- buf = PyBytes_AsString(raw_data);
-
- err = fseek(fp, file_offset, 0);
- if (err == 0)
- bytes_read = fread(buf, 1, data_size, fp);
- fclose(fp);
- if (err || bytes_read != data_size) {
- PyErr_SetString(PyExc_IOError,
- "zipimport: can't read data");
- Py_DECREF(raw_data);
- return NULL;
- }
-
- if (compress != 0) {
- buf[data_size] = 'Z'; /* saw this in zipfile.py */
- data_size++;
- }
- buf[data_size] = '\0';
-
- if (compress == 0) { /* data is not compressed */
- data = PyBytes_FromStringAndSize(buf, data_size);
- Py_DECREF(raw_data);
- return data;
- }
-
- /* Decompress with zlib */
- decompress = get_decompress_func();
- if (decompress == NULL) {
- PyErr_SetString(ZipImportError,
- "can't decompress data; "
- "zlib not available");
- goto error;
- }
- data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
+ PyObject *raw_data, *data = NULL, *decompress;
+ char *buf;
+ FILE *fp;
+ int err;
+ Py_ssize_t bytes_read = 0;
+ long l;
+ char *datapath;
+ long compress, data_size, file_size, file_offset, bytes_size;
+ long time, date, crc;
+
+ if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,
+ &data_size, &file_size, &file_offset, &time,
+ &date, &crc)) {
+ return NULL;
+ }
+
+ fp = fopen(archive, "rb");
+ if (!fp) {
+ PyErr_Format(PyExc_IOError,
+ "zipimport: can not open file %s", archive);
+ return NULL;
+ }
+
+ /* Check to make sure the local file header is correct */
+ fseek(fp, file_offset, 0);
+ l = PyMarshal_ReadLongFromFile(fp);
+ if (l != 0x04034B50) {
+ /* Bad: Local File Header */
+ PyErr_Format(ZipImportError,
+ "bad local file header in %s",
+ archive);
+ fclose(fp);
+ return NULL;
+ }
+ fseek(fp, file_offset + 26, 0);
+ l = 30 + PyMarshal_ReadShortFromFile(fp) +
+ PyMarshal_ReadShortFromFile(fp); /* local header size */
+ file_offset += l; /* Start of file data */
+
+ bytes_size = compress == 0 ? data_size : data_size + 1;
+ if (bytes_size == 0)
+ bytes_size++;
+ raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size);
+
+ if (raw_data == NULL) {
+ fclose(fp);
+ return NULL;
+ }
+ buf = PyBytes_AsString(raw_data);
+
+ err = fseek(fp, file_offset, 0);
+ if (err == 0)
+ bytes_read = fread(buf, 1, data_size, fp);
+ fclose(fp);
+ if (err || bytes_read != data_size) {
+ PyErr_SetString(PyExc_IOError,
+ "zipimport: can't read data");
+ Py_DECREF(raw_data);
+ return NULL;
+ }
+
+ if (compress != 0) {
+ buf[data_size] = 'Z'; /* saw this in zipfile.py */
+ data_size++;
+ }
+ buf[data_size] = '\0';
+
+ if (compress == 0) { /* data is not compressed */
+ data = PyBytes_FromStringAndSize(buf, data_size);
+ Py_DECREF(raw_data);
+ return data;
+ }
+
+ /* Decompress with zlib */
+ decompress = get_decompress_func();
+ if (decompress == NULL) {
+ PyErr_SetString(ZipImportError,
+ "can't decompress data; "
+ "zlib not available");
+ goto error;
+ }
+ data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
error:
- Py_DECREF(raw_data);
- return data;
+ Py_DECREF(raw_data);
+ return data;
}
/* Lenient date/time comparison function. The precision of the mtime
@@ -915,11 +915,11 @@ error:
static int
eq_mtime(time_t t1, time_t t2)
{
- time_t d = t1 - t2;
- if (d < 0)
- d = -d;
- /* dostime only stores even seconds, so be lenient */
- return d <= 1;
+ time_t d = t1 - t2;
+ if (d < 0)
+ d = -d;
+ /* dostime only stores even seconds, so be lenient */
+ return d <= 1;
}
/* Given the contents of a .py[co] file in a buffer, unmarshal the data
@@ -930,44 +930,44 @@ eq_mtime(time_t t1, time_t t2)
static PyObject *
unmarshal_code(char *pathname, PyObject *data, time_t mtime)
{
- PyObject *code;
- char *buf = PyBytes_AsString(data);
- Py_ssize_t size = PyBytes_Size(data);
-
- if (size <= 9) {
- PyErr_SetString(ZipImportError,
- "bad pyc data");
- return NULL;
- }
-
- if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s has bad magic\n",
- pathname);
- Py_INCREF(Py_None);
- return Py_None; /* signal caller to try alternative */
- }
-
- if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
- mtime)) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s has bad mtime\n",
- pathname);
- Py_INCREF(Py_None);
- return Py_None; /* signal caller to try alternative */
- }
-
- code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
- if (code == NULL)
- return NULL;
- if (!PyCode_Check(code)) {
- Py_DECREF(code);
- PyErr_Format(PyExc_TypeError,
- "compiled module %.200s is not a code object",
- pathname);
- return NULL;
- }
- return code;
+ PyObject *code;
+ char *buf = PyBytes_AsString(data);
+ Py_ssize_t size = PyBytes_Size(data);
+
+ if (size <= 9) {
+ PyErr_SetString(ZipImportError,
+ "bad pyc data");
+ return NULL;
+ }
+
+ if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s has bad magic\n",
+ pathname);
+ Py_INCREF(Py_None);
+ return Py_None; /* signal caller to try alternative */
+ }
+
+ if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
+ mtime)) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s has bad mtime\n",
+ pathname);
+ Py_INCREF(Py_None);
+ return Py_None; /* signal caller to try alternative */
+ }
+
+ code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
+ if (code == NULL)
+ return NULL;
+ if (!PyCode_Check(code)) {
+ Py_DECREF(code);
+ PyErr_Format(PyExc_TypeError,
+ "compiled module %.200s is not a code object",
+ pathname);
+ return NULL;
+ }
+ return code;
}
/* Replace any occurances of "\r\n?" in the input string with "\n".
@@ -977,38 +977,38 @@ unmarshal_code(char *pathname, PyObject *data, time_t mtime)
static PyObject *
normalize_line_endings(PyObject *source)
{
- char *buf, *q, *p = PyBytes_AsString(source);
- PyObject *fixed_source;
- int len = 0;
-
- if (!p) {
- return PyBytes_FromStringAndSize("\n\0", 2);
- }
-
- /* one char extra for trailing \n and one for terminating \0 */
- buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2);
- if (buf == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "zipimport: no memory to allocate "
- "source buffer");
- return NULL;
- }
- /* replace "\r\n?" by "\n" */
- for (q = buf; *p != '\0'; p++) {
- if (*p == '\r') {
- *q++ = '\n';
- if (*(p + 1) == '\n')
- p++;
- }
- else
- *q++ = *p;
- len++;
- }
- *q++ = '\n'; /* add trailing \n */
- *q = '\0';
- fixed_source = PyBytes_FromStringAndSize(buf, len + 2);
- PyMem_Free(buf);
- return fixed_source;
+ char *buf, *q, *p = PyBytes_AsString(source);
+ PyObject *fixed_source;
+ int len = 0;
+
+ if (!p) {
+ return PyBytes_FromStringAndSize("\n\0", 2);
+ }
+
+ /* one char extra for trailing \n and one for terminating \0 */
+ buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2);
+ if (buf == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "zipimport: no memory to allocate "
+ "source buffer");
+ return NULL;
+ }
+ /* replace "\r\n?" by "\n" */
+ for (q = buf; *p != '\0'; p++) {
+ if (*p == '\r') {
+ *q++ = '\n';
+ if (*(p + 1) == '\n')
+ p++;
+ }
+ else
+ *q++ = *p;
+ len++;
+ }
+ *q++ = '\n'; /* add trailing \n */
+ *q = '\0';
+ fixed_source = PyBytes_FromStringAndSize(buf, len + 2);
+ PyMem_Free(buf);
+ return fixed_source;
}
/* Given a string buffer containing Python source code, compile it
@@ -1016,16 +1016,16 @@ normalize_line_endings(PyObject *source)
static PyObject *
compile_source(char *pathname, PyObject *source)
{
- PyObject *code, *fixed_source;
+ PyObject *code, *fixed_source;
- fixed_source = normalize_line_endings(source);
- if (fixed_source == NULL)
- return NULL;
+ fixed_source = normalize_line_endings(source);
+ if (fixed_source == NULL)
+ return NULL;
- code = Py_CompileString(PyBytes_AsString(fixed_source), pathname,
- Py_file_input);
- Py_DECREF(fixed_source);
- return code;
+ code = Py_CompileString(PyBytes_AsString(fixed_source), pathname,
+ Py_file_input);
+ Py_DECREF(fixed_source);
+ return code;
}
/* Convert the date/time values found in the Zip archive to a value
@@ -1033,19 +1033,19 @@ compile_source(char *pathname, PyObject *source)
static time_t
parse_dostime(int dostime, int dosdate)
{
- struct tm stm;
+ struct tm stm;
- memset((void *) &stm, '\0', sizeof(stm));
+ memset((void *) &stm, '\0', sizeof(stm));
- stm.tm_sec = (dostime & 0x1f) * 2;
- stm.tm_min = (dostime >> 5) & 0x3f;
- stm.tm_hour = (dostime >> 11) & 0x1f;
- stm.tm_mday = dosdate & 0x1f;
- stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;
- stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;
- stm.tm_isdst = -1; /* wday/yday is ignored */
+ stm.tm_sec = (dostime & 0x1f) * 2;
+ stm.tm_min = (dostime >> 5) & 0x3f;
+ stm.tm_hour = (dostime >> 11) & 0x1f;
+ stm.tm_mday = dosdate & 0x1f;
+ stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;
+ stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;
+ stm.tm_isdst = -1; /* wday/yday is ignored */
- return mktime(&stm);
+ return mktime(&stm);
}
/* Given a path to a .pyc or .pyo file in the archive, return the
@@ -1054,106 +1054,106 @@ parse_dostime(int dostime, int dosdate)
static time_t
get_mtime_of_source(ZipImporter *self, char *path)
{
- PyObject *toc_entry;
- time_t mtime = 0;
- Py_ssize_t lastchar = strlen(path) - 1;
- char savechar = path[lastchar];
- path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry != NULL && PyTuple_Check(toc_entry) &&
- PyTuple_Size(toc_entry) == 8) {
- /* fetch the time stamp of the .py file for comparison
- with an embedded pyc time stamp */
- int time, date;
- time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5));
- date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6));
- mtime = parse_dostime(time, date);
- }
- path[lastchar] = savechar;
- return mtime;
+ PyObject *toc_entry;
+ time_t mtime = 0;
+ Py_ssize_t lastchar = strlen(path) - 1;
+ char savechar = path[lastchar];
+ path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry != NULL && PyTuple_Check(toc_entry) &&
+ PyTuple_Size(toc_entry) == 8) {
+ /* fetch the time stamp of the .py file for comparison
+ with an embedded pyc time stamp */
+ int time, date;
+ time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5));
+ date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6));
+ mtime = parse_dostime(time, date);
+ }
+ path[lastchar] = savechar;
+ return mtime;
}
/* Return the code object for the module named by 'fullname' from the
Zip archive as a new reference. */
static PyObject *
get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,
- time_t mtime, PyObject *toc_entry)
+ time_t mtime, PyObject *toc_entry)
{
- PyObject *data, *code;
- char *modpath;
- char *archive = _PyUnicode_AsString(self->archive);
-
- if (archive == NULL)
- return NULL;
-
- data = get_data(archive, toc_entry);
- if (data == NULL)
- return NULL;
-
- modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0));
-
- if (isbytecode) {
- code = unmarshal_code(modpath, data, mtime);
- }
- else {
- code = compile_source(modpath, data);
- }
- Py_DECREF(data);
- return code;
+ PyObject *data, *code;
+ char *modpath;
+ char *archive = _PyUnicode_AsString(self->archive);
+
+ if (archive == NULL)
+ return NULL;
+
+ data = get_data(archive, toc_entry);
+ if (data == NULL)
+ return NULL;
+
+ modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0));
+
+ if (isbytecode) {
+ code = unmarshal_code(modpath, data, mtime);
+ }
+ else {
+ code = compile_source(modpath, data);
+ }
+ Py_DECREF(data);
+ return code;
}
/* Get the code object assoiciated with the module specified by
'fullname'. */
static PyObject *
get_module_code(ZipImporter *self, char *fullname,
- int *p_ispackage, char **p_modpath)
+ int *p_ispackage, char **p_modpath)
{
- PyObject *toc_entry;
- char *subname, path[MAXPATHLEN + 1];
- int len;
- struct st_zip_searchorder *zso;
-
- subname = get_subname(fullname);
-
- len = make_filename(_PyUnicode_AsString(self->prefix), subname, path);
- if (len < 0)
- return NULL;
-
- for (zso = zip_searchorder; *zso->suffix; zso++) {
- PyObject *code = NULL;
-
- strcpy(path + len, zso->suffix);
- if (Py_VerboseFlag > 1)
- PySys_WriteStderr("# trying %s%c%s\n",
- _PyUnicode_AsString(self->archive),
- (int)SEP, path);
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry != NULL) {
- time_t mtime = 0;
- int ispackage = zso->type & IS_PACKAGE;
- int isbytecode = zso->type & IS_BYTECODE;
-
- if (isbytecode)
- mtime = get_mtime_of_source(self, path);
- if (p_ispackage != NULL)
- *p_ispackage = ispackage;
- code = get_code_from_data(self, ispackage,
- isbytecode, mtime,
- toc_entry);
- if (code == Py_None) {
- /* bad magic number or non-matching mtime
- in byte code, try next */
- Py_DECREF(code);
- continue;
- }
- if (code != NULL && p_modpath != NULL)
- *p_modpath = _PyUnicode_AsString(
- PyTuple_GetItem(toc_entry, 0));
- return code;
- }
- }
- PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);
- return NULL;
+ PyObject *toc_entry;
+ char *subname, path[MAXPATHLEN + 1];
+ int len;
+ struct st_zip_searchorder *zso;
+
+ subname = get_subname(fullname);
+
+ len = make_filename(_PyUnicode_AsString(self->prefix), subname, path);
+ if (len < 0)
+ return NULL;
+
+ for (zso = zip_searchorder; *zso->suffix; zso++) {
+ PyObject *code = NULL;
+
+ strcpy(path + len, zso->suffix);
+ if (Py_VerboseFlag > 1)
+ PySys_WriteStderr("# trying %s%c%s\n",
+ _PyUnicode_AsString(self->archive),
+ (int)SEP, path);
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry != NULL) {
+ time_t mtime = 0;
+ int ispackage = zso->type & IS_PACKAGE;
+ int isbytecode = zso->type & IS_BYTECODE;
+
+ if (isbytecode)
+ mtime = get_mtime_of_source(self, path);
+ if (p_ispackage != NULL)
+ *p_ispackage = ispackage;
+ code = get_code_from_data(self, ispackage,
+ isbytecode, mtime,
+ toc_entry);
+ if (code == Py_None) {
+ /* bad magic number or non-matching mtime
+ in byte code, try next */
+ Py_DECREF(code);
+ continue;
+ }
+ if (code != NULL && p_modpath != NULL)
+ *p_modpath = _PyUnicode_AsString(
+ PyTuple_GetItem(toc_entry, 0));
+ return code;
+ }
+ }
+ PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);
+ return NULL;
}
@@ -1174,65 +1174,65 @@ used by the builtin import mechanism for sys.path items that are paths\n\
to Zip archives.");
static struct PyModuleDef zipimportmodule = {
- PyModuleDef_HEAD_INIT,
- "zipimport",
- zipimport_doc,
- -1,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "zipimport",
+ zipimport_doc,
+ -1,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
PyInit_zipimport(void)
{
- PyObject *mod;
-
- if (PyType_Ready(&ZipImporter_Type) < 0)
- return NULL;
-
- /* Correct directory separator */
- zip_searchorder[0].suffix[0] = SEP;
- zip_searchorder[1].suffix[0] = SEP;
- zip_searchorder[2].suffix[0] = SEP;
- if (Py_OptimizeFlag) {
- /* Reverse *.pyc and *.pyo */
- struct st_zip_searchorder tmp;
- tmp = zip_searchorder[0];
- zip_searchorder[0] = zip_searchorder[1];
- zip_searchorder[1] = tmp;
- tmp = zip_searchorder[3];
- zip_searchorder[3] = zip_searchorder[4];
- zip_searchorder[4] = tmp;
- }
-
- mod = PyModule_Create(&zipimportmodule);
- if (mod == NULL)
- return NULL;
-
- ZipImportError = PyErr_NewException("zipimport.ZipImportError",
- PyExc_ImportError, NULL);
- if (ZipImportError == NULL)
- return NULL;
-
- Py_INCREF(ZipImportError);
- if (PyModule_AddObject(mod, "ZipImportError",
- ZipImportError) < 0)
- return NULL;
-
- Py_INCREF(&ZipImporter_Type);
- if (PyModule_AddObject(mod, "zipimporter",
- (PyObject *)&ZipImporter_Type) < 0)
- return NULL;
-
- zip_directory_cache = PyDict_New();
- if (zip_directory_cache == NULL)
- return NULL;
- Py_INCREF(zip_directory_cache);
- if (PyModule_AddObject(mod, "_zip_directory_cache",
- zip_directory_cache) < 0)
- return NULL;
- return mod;
+ PyObject *mod;
+
+ if (PyType_Ready(&ZipImporter_Type) < 0)
+ return NULL;
+
+ /* Correct directory separator */
+ zip_searchorder[0].suffix[0] = SEP;
+ zip_searchorder[1].suffix[0] = SEP;
+ zip_searchorder[2].suffix[0] = SEP;
+ if (Py_OptimizeFlag) {
+ /* Reverse *.pyc and *.pyo */
+ struct st_zip_searchorder tmp;
+ tmp = zip_searchorder[0];
+ zip_searchorder[0] = zip_searchorder[1];
+ zip_searchorder[1] = tmp;
+ tmp = zip_searchorder[3];
+ zip_searchorder[3] = zip_searchorder[4];
+ zip_searchorder[4] = tmp;
+ }
+
+ mod = PyModule_Create(&zipimportmodule);
+ if (mod == NULL)
+ return NULL;
+
+ ZipImportError = PyErr_NewException("zipimport.ZipImportError",
+ PyExc_ImportError, NULL);
+ if (ZipImportError == NULL)
+ return NULL;
+
+ Py_INCREF(ZipImportError);
+ if (PyModule_AddObject(mod, "ZipImportError",
+ ZipImportError) < 0)
+ return NULL;
+
+ Py_INCREF(&ZipImporter_Type);
+ if (PyModule_AddObject(mod, "zipimporter",
+ (PyObject *)&ZipImporter_Type) < 0)
+ return NULL;
+
+ zip_directory_cache = PyDict_New();
+ if (zip_directory_cache == NULL)
+ return NULL;
+ Py_INCREF(zip_directory_cache);
+ if (PyModule_AddObject(mod, "_zip_directory_cache",
+ zip_directory_cache) < 0)
+ return NULL;
+ return mod;
}
diff --git a/Modules/zlibmodule.c b/Modules/zlibmodule.c
index 353d11a..1f263ab 100644
--- a/Modules/zlibmodule.c
+++ b/Modules/zlibmodule.c
@@ -53,9 +53,9 @@ static void
zlib_error(z_stream zst, int err, char *msg)
{
if (zst.msg == Z_NULL)
- PyErr_Format(ZlibError, "Error %d %s", err, msg);
+ PyErr_Format(ZlibError, "Error %d %s", err, msg);
else
- PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg);
+ PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg);
}
PyDoc_STRVAR(compressobj__doc__,
@@ -74,17 +74,17 @@ newcompobject(PyTypeObject *type)
compobject *self;
self = PyObject_New(compobject, type);
if (self == NULL)
- return NULL;
+ return NULL;
self->is_initialised = 0;
self->unused_data = PyBytes_FromStringAndSize("", 0);
if (self->unused_data == NULL) {
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
self->unconsumed_tail = PyBytes_FromStringAndSize("", 0);
if (self->unconsumed_tail == NULL) {
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
#ifdef WITH_THREAD
self->lock = PyThread_allocate_lock();
@@ -108,7 +108,7 @@ PyZlib_compress(PyObject *self, PyObject *args)
/* require Python string object, optional 'level' arg */
if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level))
- return NULL;
+ return NULL;
input = pinput.buf;
length = pinput.len;
@@ -116,10 +116,10 @@ PyZlib_compress(PyObject *self, PyObject *args)
output = (Byte*)malloc(zst.avail_out);
if (output == NULL) {
- PyBuffer_Release(&pinput);
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory to compress data");
- return NULL;
+ PyBuffer_Release(&pinput);
+ PyErr_SetString(PyExc_MemoryError,
+ "Can't allocate memory to compress data");
+ return NULL;
}
/* Past the point of no return. From here on out, we need to make sure
@@ -134,19 +134,19 @@ PyZlib_compress(PyObject *self, PyObject *args)
switch(err) {
case(Z_OK):
- break;
+ break;
case(Z_MEM_ERROR):
- PyErr_SetString(PyExc_MemoryError,
- "Out of memory while compressing data");
- goto error;
+ PyErr_SetString(PyExc_MemoryError,
+ "Out of memory while compressing data");
+ goto error;
case(Z_STREAM_ERROR):
- PyErr_SetString(ZlibError,
- "Bad compression level");
- goto error;
+ PyErr_SetString(ZlibError,
+ "Bad compression level");
+ goto error;
default:
deflateEnd(&zst);
- zlib_error(zst, err, "while compressing data");
- goto error;
+ zlib_error(zst, err, "while compressing data");
+ goto error;
}
Py_BEGIN_ALLOW_THREADS;
@@ -154,17 +154,17 @@ PyZlib_compress(PyObject *self, PyObject *args)
Py_END_ALLOW_THREADS;
if (err != Z_STREAM_END) {
- zlib_error(zst, err, "while compressing data");
- deflateEnd(&zst);
- goto error;
+ zlib_error(zst, err, "while compressing data");
+ deflateEnd(&zst);
+ goto error;
}
err=deflateEnd(&zst);
if (err == Z_OK)
- ReturnVal = PyBytes_FromStringAndSize((char *)output,
+ ReturnVal = PyBytes_FromStringAndSize((char *)output,
zst.total_out);
else
- zlib_error(zst, err, "while finishing compression");
+ zlib_error(zst, err, "while finishing compression");
error:
PyBuffer_Release(&pinput);
@@ -191,20 +191,20 @@ PyZlib_decompress(PyObject *self, PyObject *args)
z_stream zst;
if (!PyArg_ParseTuple(args, "y*|in:decompress",
- &pinput, &wsize, &r_strlen))
- return NULL;
+ &pinput, &wsize, &r_strlen))
+ return NULL;
input = pinput.buf;
length = pinput.len;
if (r_strlen <= 0)
- r_strlen = 1;
+ r_strlen = 1;
zst.avail_in = length;
zst.avail_out = r_strlen;
if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen))) {
- PyBuffer_Release(&pinput);
- return NULL;
+ PyBuffer_Release(&pinput);
+ return NULL;
}
zst.zalloc = (alloc_func)NULL;
@@ -215,60 +215,60 @@ PyZlib_decompress(PyObject *self, PyObject *args)
switch(err) {
case(Z_OK):
- break;
+ break;
case(Z_MEM_ERROR):
- PyErr_SetString(PyExc_MemoryError,
- "Out of memory while decompressing data");
- goto error;
+ PyErr_SetString(PyExc_MemoryError,
+ "Out of memory while decompressing data");
+ goto error;
default:
inflateEnd(&zst);
- zlib_error(zst, err, "while preparing to decompress data");
- goto error;
+ zlib_error(zst, err, "while preparing to decompress data");
+ goto error;
}
do {
- Py_BEGIN_ALLOW_THREADS
- err=inflate(&zst, Z_FINISH);
- Py_END_ALLOW_THREADS
-
- switch(err) {
- case(Z_STREAM_END):
- break;
- case(Z_BUF_ERROR):
- /*
- * If there is at least 1 byte of room according to zst.avail_out
- * and we get this error, assume that it means zlib cannot
- * process the inflate call() due to an error in the data.
- */
- if (zst.avail_out > 0) {
- PyErr_Format(ZlibError, "Error %i while decompressing data",
- err);
- inflateEnd(&zst);
- goto error;
- }
- /* fall through */
- case(Z_OK):
- /* need more memory */
- if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) {
- inflateEnd(&zst);
- goto error;
- }
- zst.next_out =
+ Py_BEGIN_ALLOW_THREADS
+ err=inflate(&zst, Z_FINISH);
+ Py_END_ALLOW_THREADS
+
+ switch(err) {
+ case(Z_STREAM_END):
+ break;
+ case(Z_BUF_ERROR):
+ /*
+ * If there is at least 1 byte of room according to zst.avail_out
+ * and we get this error, assume that it means zlib cannot
+ * process the inflate call() due to an error in the data.
+ */
+ if (zst.avail_out > 0) {
+ PyErr_Format(ZlibError, "Error %i while decompressing data",
+ err);
+ inflateEnd(&zst);
+ goto error;
+ }
+ /* fall through */
+ case(Z_OK):
+ /* need more memory */
+ if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) {
+ inflateEnd(&zst);
+ goto error;
+ }
+ zst.next_out =
(unsigned char *)PyBytes_AS_STRING(result_str) + r_strlen;
- zst.avail_out = r_strlen;
- r_strlen = r_strlen << 1;
- break;
- default:
- inflateEnd(&zst);
- zlib_error(zst, err, "while decompressing data");
- goto error;
- }
+ zst.avail_out = r_strlen;
+ r_strlen = r_strlen << 1;
+ break;
+ default:
+ inflateEnd(&zst);
+ zlib_error(zst, err, "while decompressing data");
+ goto error;
+ }
} while (err != Z_STREAM_END);
err = inflateEnd(&zst);
if (err != Z_OK) {
- zlib_error(zst, err, "while finishing data decompression");
- goto error;
+ zlib_error(zst, err, "while finishing data decompression");
+ goto error;
}
if (_PyBytes_Resize(&result_str, zst.total_out) < 0)
@@ -291,12 +291,12 @@ PyZlib_compressobj(PyObject *selfptr, PyObject *args)
int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err;
if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits,
- &memLevel, &strategy))
- return NULL;
+ &memLevel, &strategy))
+ return NULL;
self = newcompobject(&Comptype);
if (self==NULL)
- return(NULL);
+ return(NULL);
self->zst.zalloc = (alloc_func)NULL;
self->zst.zfree = (free_func)Z_NULL;
self->zst.next_in = NULL;
@@ -304,21 +304,21 @@ PyZlib_compressobj(PyObject *selfptr, PyObject *args)
err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy);
switch(err) {
case (Z_OK):
- self->is_initialised = 1;
- return (PyObject*)self;
+ self->is_initialised = 1;
+ return (PyObject*)self;
case (Z_MEM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory for compression object");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_MemoryError,
+ "Can't allocate memory for compression object");
+ return NULL;
case(Z_STREAM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
+ return NULL;
default:
- zlib_error(self->zst, err, "while creating compression object");
+ zlib_error(self->zst, err, "while creating compression object");
Py_DECREF(self);
- return NULL;
+ return NULL;
}
}
@@ -328,11 +328,11 @@ PyZlib_decompressobj(PyObject *selfptr, PyObject *args)
int wbits=DEF_WBITS, err;
compobject *self;
if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits))
- return NULL;
+ return NULL;
self = newcompobject(&Decomptype);
if (self == NULL)
- return(NULL);
+ return(NULL);
self->zst.zalloc = (alloc_func)NULL;
self->zst.zfree = (free_func)Z_NULL;
self->zst.next_in = NULL;
@@ -340,21 +340,21 @@ PyZlib_decompressobj(PyObject *selfptr, PyObject *args)
err = inflateInit2(&self->zst, wbits);
switch(err) {
case (Z_OK):
- self->is_initialised = 1;
- return (PyObject*)self;
+ self->is_initialised = 1;
+ return (PyObject*)self;
case(Z_STREAM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
+ return NULL;
case (Z_MEM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory for decompression object");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_MemoryError,
+ "Can't allocate memory for decompression object");
+ return NULL;
default:
- zlib_error(self->zst, err, "while creating decompression object");
+ zlib_error(self->zst, err, "while creating decompression object");
Py_DECREF(self);
- return NULL;
+ return NULL;
}
}
@@ -404,13 +404,13 @@ PyZlib_objcompress(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "y*:compress", &pinput))
- return NULL;
+ return NULL;
input = pinput.buf;
inplen = pinput.len;
if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) {
- PyBuffer_Release(&pinput);
- return NULL;
+ PyBuffer_Release(&pinput);
+ return NULL;
}
ENTER_ZLIB(self);
@@ -428,19 +428,19 @@ PyZlib_objcompress(compobject *self, PyObject *args)
/* while Z_OK and the output buffer is full, there might be more output,
so extend the output buffer and try again */
while (err == Z_OK && self->zst.avail_out == 0) {
- if (_PyBytes_Resize(&RetVal, length << 1) < 0) {
+ if (_PyBytes_Resize(&RetVal, length << 1) < 0) {
Py_DECREF(RetVal);
RetVal = NULL;
- goto error;
+ goto error;
}
- self->zst.next_out =
+ self->zst.next_out =
(unsigned char *)PyBytes_AS_STRING(RetVal) + length;
- self->zst.avail_out = length;
- length = length << 1;
+ self->zst.avail_out = length;
+ length = length << 1;
- Py_BEGIN_ALLOW_THREADS
- err = deflate(&(self->zst), Z_NO_FLUSH);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ err = deflate(&(self->zst), Z_NO_FLUSH);
+ Py_END_ALLOW_THREADS
}
/* We will only get Z_BUF_ERROR if the output buffer was full but
there wasn't more output when we tried again, so it is not an error
@@ -448,10 +448,10 @@ PyZlib_objcompress(compobject *self, PyObject *args)
*/
if (err != Z_OK && err != Z_BUF_ERROR) {
- zlib_error(self->zst, err, "while compressing");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
+ zlib_error(self->zst, err, "while compressing");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) {
Py_DECREF(RetVal);
@@ -486,23 +486,23 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "y*|i:decompress", &pinput,
- &max_length))
- return NULL;
+ &max_length))
+ return NULL;
input = pinput.buf;
inplen = pinput.len;
if (max_length < 0) {
- PyBuffer_Release(&pinput);
- PyErr_SetString(PyExc_ValueError,
- "max_length must be greater than zero");
- return NULL;
+ PyBuffer_Release(&pinput);
+ PyErr_SetString(PyExc_ValueError,
+ "max_length must be greater than zero");
+ return NULL;
}
/* limit amount of data allocated to max_length */
if (max_length && length > max_length)
- length = max_length;
+ length = max_length;
if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) {
- PyBuffer_Release(&pinput);
- return NULL;
+ PyBuffer_Release(&pinput);
+ return NULL;
}
ENTER_ZLIB(self);
@@ -521,43 +521,43 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
So extend the output buffer and try again.
*/
while (err == Z_OK && self->zst.avail_out == 0) {
- /* If max_length set, don't continue decompressing if we've already
- reached the limit.
- */
- if (max_length && length >= max_length)
- break;
-
- /* otherwise, ... */
- old_length = length;
- length = length << 1;
- if (max_length && length > max_length)
- length = max_length;
-
- if (_PyBytes_Resize(&RetVal, length) < 0) {
+ /* If max_length set, don't continue decompressing if we've already
+ reached the limit.
+ */
+ if (max_length && length >= max_length)
+ break;
+
+ /* otherwise, ... */
+ old_length = length;
+ length = length << 1;
+ if (max_length && length > max_length)
+ length = max_length;
+
+ if (_PyBytes_Resize(&RetVal, length) < 0) {
Py_DECREF(RetVal);
RetVal = NULL;
- goto error;
+ goto error;
}
- self->zst.next_out =
+ self->zst.next_out =
(unsigned char *)PyBytes_AS_STRING(RetVal) + old_length;
- self->zst.avail_out = length - old_length;
+ self->zst.avail_out = length - old_length;
- Py_BEGIN_ALLOW_THREADS
- err = inflate(&(self->zst), Z_SYNC_FLUSH);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ err = inflate(&(self->zst), Z_SYNC_FLUSH);
+ Py_END_ALLOW_THREADS
}
/* Not all of the compressed data could be accommodated in the output buffer
of specified size. Return the unconsumed tail in an attribute.*/
if(max_length) {
- Py_DECREF(self->unconsumed_tail);
- self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in,
- self->zst.avail_in);
- if(!self->unconsumed_tail) {
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
- }
+ Py_DECREF(self->unconsumed_tail);
+ self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in,
+ self->zst.avail_in);
+ if(!self->unconsumed_tail) {
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
+ }
}
/* The end of the compressed data has been reached, so set the
@@ -567,22 +567,22 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
preserved.
*/
if (err == Z_STREAM_END) {
- Py_XDECREF(self->unused_data); /* Free original empty string */
- self->unused_data = PyBytes_FromStringAndSize(
- (char *)self->zst.next_in, self->zst.avail_in);
- if (self->unused_data == NULL) {
- Py_DECREF(RetVal);
- goto error;
- }
- /* We will only get Z_BUF_ERROR if the output buffer was full
- but there wasn't more output when we tried again, so it is
- not an error condition.
- */
+ Py_XDECREF(self->unused_data); /* Free original empty string */
+ self->unused_data = PyBytes_FromStringAndSize(
+ (char *)self->zst.next_in, self->zst.avail_in);
+ if (self->unused_data == NULL) {
+ Py_DECREF(RetVal);
+ goto error;
+ }
+ /* We will only get Z_BUF_ERROR if the output buffer was full
+ but there wasn't more output when we tried again, so it is
+ not an error condition.
+ */
} else if (err != Z_OK && err != Z_BUF_ERROR) {
- zlib_error(self->zst, err, "while decompressing");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
+ zlib_error(self->zst, err, "while decompressing");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) {
@@ -613,16 +613,16 @@ PyZlib_flush(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "|i:flush", &flushmode))
- return NULL;
+ return NULL;
/* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
doing any work at all; just return an empty string. */
if (flushmode == Z_NO_FLUSH) {
- return PyBytes_FromStringAndSize(NULL, 0);
+ return PyBytes_FromStringAndSize(NULL, 0);
}
if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB(self);
@@ -638,44 +638,44 @@ PyZlib_flush(compobject *self, PyObject *args)
/* while Z_OK and the output buffer is full, there might be more output,
so extend the output buffer and try again */
while (err == Z_OK && self->zst.avail_out == 0) {
- if (_PyBytes_Resize(&RetVal, length << 1) < 0) {
+ if (_PyBytes_Resize(&RetVal, length << 1) < 0) {
Py_DECREF(RetVal);
RetVal = NULL;
- goto error;
+ goto error;
}
- self->zst.next_out =
+ self->zst.next_out =
(unsigned char *)PyBytes_AS_STRING(RetVal) + length;
- self->zst.avail_out = length;
- length = length << 1;
+ self->zst.avail_out = length;
+ length = length << 1;
- Py_BEGIN_ALLOW_THREADS
- err = deflate(&(self->zst), flushmode);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ err = deflate(&(self->zst), flushmode);
+ Py_END_ALLOW_THREADS
}
/* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
various data structures. Note we should only get Z_STREAM_END when
flushmode is Z_FINISH, but checking both for safety*/
if (err == Z_STREAM_END && flushmode == Z_FINISH) {
- err = deflateEnd(&(self->zst));
- if (err != Z_OK) {
- zlib_error(self->zst, err, "from deflateEnd()");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
- }
- else
- self->is_initialised = 0;
-
- /* We will only get Z_BUF_ERROR if the output buffer was full
- but there wasn't more output when we tried again, so it is
- not an error condition.
- */
+ err = deflateEnd(&(self->zst));
+ if (err != Z_OK) {
+ zlib_error(self->zst, err, "from deflateEnd()");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
+ }
+ else
+ self->is_initialised = 0;
+
+ /* We will only get Z_BUF_ERROR if the output buffer was full
+ but there wasn't more output when we tried again, so it is
+ not an error condition.
+ */
} else if (err!=Z_OK && err!=Z_BUF_ERROR) {
- zlib_error(self->zst, err, "while flushing");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
+ zlib_error(self->zst, err, "while flushing");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) {
@@ -807,13 +807,13 @@ PyZlib_unflush(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "|i:flush", &length))
- return NULL;
+ return NULL;
if (length <= 0) {
- PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
+ return NULL;
}
if (!(retval = PyBytes_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB(self);
@@ -829,32 +829,32 @@ PyZlib_unflush(compobject *self, PyObject *args)
/* while Z_OK and the output buffer is full, there might be more output,
so extend the output buffer and try again */
while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) {
- if (_PyBytes_Resize(&retval, length << 1) < 0) {
+ if (_PyBytes_Resize(&retval, length << 1) < 0) {
Py_DECREF(retval);
retval = NULL;
- goto error;
+ goto error;
}
- self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length;
- self->zst.avail_out = length;
- length = length << 1;
+ self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length;
+ self->zst.avail_out = length;
+ length = length << 1;
- Py_BEGIN_ALLOW_THREADS
- err = inflate(&(self->zst), Z_FINISH);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ err = inflate(&(self->zst), Z_FINISH);
+ Py_END_ALLOW_THREADS
}
/* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
various data structures. Note we should only get Z_STREAM_END when
flushmode is Z_FINISH */
if (err == Z_STREAM_END) {
- err = inflateEnd(&(self->zst));
+ err = inflateEnd(&(self->zst));
self->is_initialised = 0;
- if (err != Z_OK) {
- zlib_error(self->zst, err, "from inflateEnd()");
- Py_DECREF(retval);
- retval = NULL;
- goto error;
- }
+ if (err != Z_OK) {
+ zlib_error(self->zst, err, "from inflateEnd()");
+ Py_DECREF(retval);
+ retval = NULL;
+ goto error;
+ }
}
if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) {
Py_DECREF(retval);
@@ -942,7 +942,7 @@ PyZlib_crc32(PyObject *self, PyObject *args)
int signed_val;
if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val))
- return NULL;
+ return NULL;
/* Releasing the GIL for very small buffers is inefficient
and may lower performance */
if (pbuf.len > 1024*5) {
@@ -950,7 +950,7 @@ PyZlib_crc32(PyObject *self, PyObject *args)
signed_val = crc32(crc32val, pbuf.buf, pbuf.len);
Py_END_ALLOW_THREADS
} else {
- signed_val = crc32(crc32val, pbuf.buf, pbuf.len);
+ signed_val = crc32(crc32val, pbuf.buf, pbuf.len);
}
PyBuffer_Release(&pbuf);
return PyLong_FromUnsignedLong(signed_val & 0xffffffffU);
@@ -1053,15 +1053,15 @@ PyDoc_STRVAR(zlib_module_documentation,
"objects support decompress() and flush().");
static struct PyModuleDef zlibmodule = {
- PyModuleDef_HEAD_INIT,
- "zlib",
- zlib_module_documentation,
- -1,
- zlib_methods,
- NULL,
- NULL,
- NULL,
- NULL
+ PyModuleDef_HEAD_INIT,
+ "zlib",
+ zlib_module_documentation,
+ -1,
+ zlib_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
};
PyMODINIT_FUNC
@@ -1069,17 +1069,17 @@ PyInit_zlib(void)
{
PyObject *m, *ver;
if (PyType_Ready(&Comptype) < 0)
- return NULL;
+ return NULL;
if (PyType_Ready(&Decomptype) < 0)
- return NULL;
+ return NULL;
m = PyModule_Create(&zlibmodule);
if (m == NULL)
- return NULL;
+ return NULL;
ZlibError = PyErr_NewException("zlib.error", NULL, NULL);
if (ZlibError != NULL) {
Py_INCREF(ZlibError);
- PyModule_AddObject(m, "error", ZlibError);
+ PyModule_AddObject(m, "error", ZlibError);
}
PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS);
PyModule_AddIntConstant(m, "DEFLATED", DEFLATED);
@@ -1098,7 +1098,7 @@ PyInit_zlib(void)
ver = PyUnicode_FromString(ZLIB_VERSION);
if (ver != NULL)
- PyModule_AddObject(m, "ZLIB_VERSION", ver);
+ PyModule_AddObject(m, "ZLIB_VERSION", ver);
PyModule_AddStringConstant(m, "__version__", "1.0");